file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
NVIDIA/warp/warp/tests/test_marching_cubes.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def make_field(field: wp.array3d(dtype=float), center: wp.vec3, radius: float): i, j, k = wp.tid() p = wp.vec3(float(i), float(j), float(k)) d = wp.length(p - center) - radius field[i, j, k] = d def test_marching_cubes(test, device): dim = 64 max_verts = 10**6 max_tris = 10**6 field = wp.zeros(shape=(dim, dim, dim), dtype=float, device=device) iso = wp.MarchingCubes(nx=dim, ny=dim, nz=dim, max_verts=max_verts, max_tris=max_tris, device=device) radius = dim / 4.0 wp.launch(make_field, dim=field.shape, inputs=[field, wp.vec3(dim / 2, dim / 2, dim / 2), radius], device=device) iso.surface(field=field, threshold=0.0) # check that all returned vertices lie on the surface of the sphere length = np.linalg.norm(iso.verts.numpy() - np.array([dim / 2, dim / 2, dim / 2]), axis=1) error = np.abs(length - radius) test.assertTrue(np.max(error) < 1.0) iso.resize(nx=dim * 2, ny=dim * 2, nz=dim * 2, max_verts=max_verts, max_tris=max_tris) devices = get_selected_cuda_test_devices() class TestMarchingCubes(unittest.TestCase): pass add_function_test(TestMarchingCubes, "test_marching_cubes", test_marching_cubes, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
1,843
Python
27.8125
117
0.691264
NVIDIA/warp/warp/tests/test_devices.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp from warp.tests.unittest_utils import * def test_devices_get_cuda_device_functions(test, device): test.assertTrue(device.is_cuda) test.assertTrue(wp.is_device_available(device)) device_ordinal = device.ordinal current_device = wp.get_cuda_device(device_ordinal) test.assertEqual(current_device, device) current_device = wp.get_cuda_device() # No-ordinal version test.assertTrue(wp.is_device_available(current_device)) if device == current_device: test.assertEqual(device, "cuda") else: test.assertNotEqual(device, "cuda") preferred_device = wp.get_preferred_device() test.assertTrue(wp.is_device_available(preferred_device)) def test_devices_map_cuda_device(test, device): with wp.ScopedDevice(device): saved_alias = device.alias # Map alias twice to check code path wp.map_cuda_device("new_alias") wp.map_cuda_device("new_alias") wp.context.runtime.rename_device(device, saved_alias) def test_devices_verify_cuda_device(test, device): verify_cuda_saved = wp.config.verify_cuda wp.config.verify_cuda = True wp.context.runtime.verify_cuda_device(device) wp.config.verify_cuda = verify_cuda_saved @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_devices_can_access_self(test, device): test.assertTrue(device.can_access(device)) for warp_device in wp.get_devices(): device_str = str(warp_device) if (device.is_cpu and warp_device.is_cuda) or (device.is_cuda and warp_device.is_cpu): test.assertFalse(device.can_access(warp_device)) test.assertNotEqual(device, warp_device) test.assertNotEqual(device, device_str) devices = get_test_devices() class TestDevices(unittest.TestCase): def test_devices_unmap_imaginary_device(self): with self.assertRaises(RuntimeError): wp.unmap_cuda_device("imaginary_device:0") add_function_test( TestDevices, "test_devices_get_cuda_device_functions", test_devices_get_cuda_device_functions, devices=get_selected_cuda_test_devices(), ) add_function_test( TestDevices, "test_devices_map_cuda_device", test_devices_map_cuda_device, devices=get_selected_cuda_test_devices() ) add_function_test(TestDevices, "test_devices_verify_cuda_device", test_devices_verify_cuda_device, devices=devices) add_function_test(TestDevices, "test_devices_can_access_self", test_devices_can_access_self, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
3,048
Python
32.877777
119
0.721457
NVIDIA/warp/warp/tests/test_utils.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import contextlib import inspect import io import unittest from warp.tests.unittest_utils import * def test_array_scan(test, device): rng = np.random.default_rng(123) for dtype in (int, float): if dtype == int: values = rng.integers(-1e6, high=1e6, size=100000, dtype=dtype) else: values = rng.uniform(low=-1e6, high=1e6, size=100000) expected = np.cumsum(values) values = wp.array(values, dtype=dtype, device=device) result_inc = wp.zeros_like(values) result_exc = wp.zeros_like(values) wp.utils.array_scan(values, result_inc, True) wp.utils.array_scan(values, result_exc, False) tolerance = 0 if dtype == int else 1e-3 result_inc = result_inc.numpy().squeeze() result_exc = result_exc.numpy().squeeze() error_inc = np.max(np.abs(result_inc - expected)) / abs(expected[-1]) error_exc = max(np.max(np.abs(result_exc[1:] - expected[:-1])), abs(result_exc[0])) / abs(expected[-2]) test.assertTrue(error_inc <= tolerance) test.assertTrue(error_exc <= tolerance) def test_array_scan_empty(test, device): values = wp.array((), dtype=int, device=device) result = wp.array((), dtype=int, device=device) wp.utils.array_scan(values, result) def test_array_scan_error_sizes_mismatch(test, device): values = wp.zeros(123, dtype=int, device=device) result = wp.zeros(234, dtype=int, device=device) with test.assertRaisesRegex( RuntimeError, r"Array storage sizes do not match$", ): wp.utils.array_scan(values, result, True) def test_array_scan_error_dtypes_mismatch(test, device): values = wp.zeros(123, dtype=int, device=device) result = wp.zeros(123, dtype=float, device=device) with test.assertRaisesRegex( RuntimeError, r"Array data types do not match$", ): wp.utils.array_scan(values, result, True) def test_array_scan_error_unsupported_dtype(test, device): values = wp.zeros(123, dtype=wp.vec3, device=device) result = wp.zeros(123, dtype=wp.vec3, device=device) with test.assertRaisesRegex( RuntimeError, r"Unsupported data type$", ): wp.utils.array_scan(values, result, True) def test_radix_sort_pairs(test, device): keys = wp.array((7, 2, 8, 4, 1, 6, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0), dtype=int, device=device) values = wp.array((1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0), dtype=int, device=device) wp.utils.radix_sort_pairs(keys, values, 8) assert_np_equal(keys.numpy()[:8], np.array((1, 2, 3, 4, 5, 6, 7, 8))) assert_np_equal(values.numpy()[:8], np.array((5, 2, 8, 4, 7, 6, 1, 3))) def test_radix_sort_pairs_empty(test, device): keys = wp.array((), dtype=int, device=device) values = wp.array((), dtype=int, device=device) wp.utils.radix_sort_pairs(keys, values, 0) def test_radix_sort_pairs_error_insufficient_storage(test, device): keys = wp.array((1, 2, 3), dtype=int, device=device) values = wp.array((1, 2, 3), dtype=int, device=device) with test.assertRaisesRegex( RuntimeError, r"Array storage must be large enough to contain 2\*count elements$", ): wp.utils.radix_sort_pairs(keys, values, 3) def test_radix_sort_pairs_error_unsupported_dtype(test, device): keys = wp.array((1.0, 2.0, 3.0), dtype=float, device=device) values = wp.array((1.0, 2.0, 3.0), dtype=float, device=device) with test.assertRaisesRegex( RuntimeError, r"Unsupported data type$", ): wp.utils.radix_sort_pairs(keys, values, 1) def test_array_sum(test, device): for dtype in (wp.float32, wp.float64): with test.subTest(dtype=dtype): values = wp.array((1.0, 2.0, 3.0), dtype=dtype, device=device) test.assertEqual(wp.utils.array_sum(values), 6.0) values = wp.array((1.0, 2.0, 3.0), dtype=dtype, device=device) result = wp.empty(shape=(1,), dtype=dtype, device=device) wp.utils.array_sum(values, out=result) test.assertEqual(result.numpy()[0], 6.0) def test_array_sum_error_out_dtype_mismatch(test, device): values = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) result = wp.empty(shape=(1,), dtype=wp.float64, device=device) with test.assertRaisesRegex( RuntimeError, r"out array should have type float32$", ): wp.utils.array_sum(values, out=result) def test_array_sum_error_out_shape_mismatch(test, device): values = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) result = wp.empty(shape=(2,), dtype=wp.float32, device=device) with test.assertRaisesRegex( RuntimeError, r"out array should have shape \(1,\)$", ): wp.utils.array_sum(values, out=result) def test_array_sum_error_unsupported_dtype(test, device): values = wp.array((1, 2, 3), dtype=int, device=device) with test.assertRaisesRegex( RuntimeError, r"Unsupported data type$", ): wp.utils.array_sum(values) def test_array_inner(test, device): for dtype in (wp.float32, wp.float64): a = wp.array((1.0, 2.0, 3.0), dtype=dtype, device=device) b = wp.array((1.0, 2.0, 3.0), dtype=dtype, device=device) test.assertEqual(wp.utils.array_inner(a, b), 14.0) a = wp.array((1.0, 2.0, 3.0), dtype=dtype, device=device) b = wp.array((1.0, 2.0, 3.0), dtype=dtype, device=device) result = wp.empty(shape=(1,), dtype=dtype, device=device) wp.utils.array_inner(a, b, out=result) test.assertEqual(result.numpy()[0], 14.0) def test_array_inner_error_sizes_mismatch(test, device): a = wp.array((1.0, 2.0), dtype=wp.float32, device=device) b = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) with test.assertRaisesRegex( RuntimeError, r"Array storage sizes do not match$", ): wp.utils.array_inner(a, b) def test_array_inner_error_dtypes_mismatch(test, device): a = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) b = wp.array((1.0, 2.0, 3.0), dtype=wp.float64, device=device) with test.assertRaisesRegex( RuntimeError, r"Array data types do not match$", ): wp.utils.array_inner(a, b) def test_array_inner_error_out_dtype_mismatch(test, device): a = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) b = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) result = wp.empty(shape=(1,), dtype=wp.float64, device=device) with test.assertRaisesRegex( RuntimeError, r"out array should have type float32$", ): wp.utils.array_inner(a, b, result) def test_array_inner_error_out_shape_mismatch(test, device): a = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) b = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device=device) result = wp.empty(shape=(2,), dtype=wp.float32, device=device) with test.assertRaisesRegex( RuntimeError, r"out array should have shape \(1,\)$", ): wp.utils.array_inner(a, b, result) def test_array_inner_error_unsupported_dtype(test, device): a = wp.array((1, 2, 3), dtype=int, device=device) b = wp.array((1, 2, 3), dtype=int, device=device) with test.assertRaisesRegex( RuntimeError, r"Unsupported data type$", ): wp.utils.array_inner(a, b) def test_array_cast(test, device): values = wp.array((1, 2, 3), dtype=int, device=device) result = wp.empty(3, dtype=float, device=device) wp.utils.array_cast(values, result) test.assertEqual(result.dtype, wp.float32) test.assertEqual(result.shape, (3,)) assert_np_equal(result.numpy(), np.array((1.0, 2.0, 3.0), dtype=float)) values = wp.array((1, 2, 3, 4), dtype=int, device=device) result = wp.empty((2, 2), dtype=float, device=device) wp.utils.array_cast(values, result) test.assertEqual(result.dtype, wp.float32) test.assertEqual(result.shape, (2, 2)) assert_np_equal(result.numpy(), np.array(((1.0, 2.0), (3.0, 4.0)), dtype=float)) values = wp.array(((1, 2), (3, 4)), dtype=wp.vec2, device=device) result = wp.zeros(2, dtype=float, device=device) wp.utils.array_cast(values, result, count=1) test.assertEqual(result.dtype, wp.float32) test.assertEqual(result.shape, (2,)) assert_np_equal(result.numpy(), np.array((1.0, 2.0), dtype=float)) values = wp.array(((1, 2), (3, 4)), dtype=int, device=device) result = wp.zeros((2, 2), dtype=int, device=device) wp.utils.array_cast(values, result) test.assertEqual(result.dtype, wp.int32) test.assertEqual(result.shape, (2, 2)) assert_np_equal(result.numpy(), np.array(((1, 2), (3, 4)), dtype=int)) def test_array_cast_error_unsupported_partial_cast(test, device): values = wp.array(((1, 2), (3, 4)), dtype=int, device=device) result = wp.zeros((2, 2), dtype=float, device=device) with test.assertRaisesRegex( RuntimeError, r"Partial cast is not supported for arrays with more than one dimension$", ): wp.utils.array_cast(values, result, count=1) devices = get_test_devices() class TestUtils(unittest.TestCase): def test_warn(self): # Multiple warnings get printed out each time. with contextlib.redirect_stdout(io.StringIO()) as f: wp.utils.warn("hello, world!") wp.utils.warn("hello, world!") expected = "Warp UserWarning: hello, world!\n" "Warp UserWarning: hello, world!\n" self.assertEqual(f.getvalue(), expected) # Test verbose warnings saved_verbosity = wp.config.verbose_warnings try: wp.config.verbose_warnings = True with contextlib.redirect_stdout(io.StringIO()) as f: frame_info = inspect.getframeinfo(inspect.currentframe()) wp.utils.warn("hello, world!") wp.utils.warn("hello, world!") expected = ( f"Warp UserWarning: hello, world! ({frame_info.filename}:{frame_info.lineno + 1})\n" ' wp.utils.warn("hello, world!")\n' f"Warp UserWarning: hello, world! ({frame_info.filename}:{frame_info.lineno + 2})\n" ' wp.utils.warn("hello, world!")\n' ) self.assertEqual(f.getvalue(), expected) finally: # make sure to restore warning verbosity wp.config.verbose_warnings = saved_verbosity # Multiple similar deprecation warnings get printed out only once. with contextlib.redirect_stdout(io.StringIO()) as f: wp.utils.warn("hello, world!", category=DeprecationWarning) wp.utils.warn("hello, world!", category=DeprecationWarning) expected = "Warp DeprecationWarning: hello, world!\n" self.assertEqual(f.getvalue(), expected) # Multiple different deprecation warnings get printed out each time. with contextlib.redirect_stdout(io.StringIO()) as f: wp.utils.warn("foo", category=DeprecationWarning) wp.utils.warn("bar", category=DeprecationWarning) expected = "Warp DeprecationWarning: foo\n" "Warp DeprecationWarning: bar\n" self.assertEqual(f.getvalue(), expected) def test_transform_expand(self): t = (1.0, 2.0, 3.0, 4.0, 3.0, 2.0, 1.0) self.assertEqual( wp.utils.transform_expand(t), wp.transformf(p=(1.0, 2.0, 3.0), q=(4.0, 3.0, 2.0, 1.0)), ) @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_array_scan_error_devices_mismatch(self): values = wp.zeros(123, dtype=int, device="cpu") result = wp.zeros_like(values, device="cuda:0") with self.assertRaisesRegex( RuntimeError, r"Array storage devices do not match$", ): wp.utils.array_scan(values, result, True) @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_radix_sort_pairs_error_devices_mismatch(self): keys = wp.array((1, 2, 3), dtype=int, device="cpu") values = wp.array((1, 2, 3), dtype=int, device="cuda:0") with self.assertRaisesRegex( RuntimeError, r"Array storage devices do not match$", ): wp.utils.radix_sort_pairs(keys, values, 1) @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_array_inner_error_out_device_mismatch(self): a = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device="cpu") b = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device="cpu") result = wp.empty(shape=(1,), dtype=wp.float32, device="cuda:0") with self.assertRaisesRegex( RuntimeError, r"out storage device should match values array$", ): wp.utils.array_inner(a, b, result) @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_array_sum_error_out_device_mismatch(self): values = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device="cpu") result = wp.empty(shape=(1,), dtype=wp.float32, device="cuda:0") with self.assertRaisesRegex( RuntimeError, r"out storage device should match values array$", ): wp.utils.array_sum(values, out=result) @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_array_inner_error_devices_mismatch(self): a = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device="cpu") b = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, device="cuda:0") with self.assertRaisesRegex( RuntimeError, r"Array storage devices do not match$", ): wp.utils.array_inner(a, b) @unittest.skipUnless(wp.is_cuda_available(), "Requires CUDA") def test_array_cast_error_devices_mismatch(self): values = wp.array((1, 2, 3), dtype=int, device="cpu") result = wp.empty(3, dtype=float, device="cuda:0") with self.assertRaisesRegex( RuntimeError, r"Array storage devices do not match$", ): wp.utils.array_cast(values, result) def test_mesh_adjacency(self): triangles = ( (0, 3, 1), (0, 2, 3), ) adj = wp.utils.MeshAdjacency(triangles, len(triangles)) expected_edges = { (0, 3): (0, 3, 1, 2, 0, 1), (1, 3): (3, 1, 0, -1, 0, -1), (0, 1): (1, 0, 3, -1, 0, -1), (0, 2): (0, 2, 3, -1, 1, -1), (2, 3): (2, 3, 0, -1, 1, -1), } edges = {k: (e.v0, e.v1, e.o0, e.o1, e.f0, e.f1) for k, e in adj.edges.items()} self.assertDictEqual(edges, expected_edges) def test_mesh_adjacency_error_manifold(self): triangles = ( (0, 3, 1), (0, 2, 3), (3, 0, 1), ) with contextlib.redirect_stdout(io.StringIO()) as f: wp.utils.MeshAdjacency(triangles, len(triangles)) self.assertEqual(f.getvalue(), "Detected non-manifold edge\n") def test_scoped_timer(self): with contextlib.redirect_stdout(io.StringIO()) as f: with wp.ScopedTimer("hello"): pass self.assertRegex(f.getvalue(), r"^hello took \d+\.\d+ ms$") with contextlib.redirect_stdout(io.StringIO()) as f: with wp.ScopedTimer("hello", detailed=True): pass self.assertRegex(f.getvalue(), r"^ 4 function calls in \d+\.\d+ seconds") self.assertRegex(f.getvalue(), r"hello took \d+\.\d+ ms$") add_function_test(TestUtils, "test_array_scan", test_array_scan, devices=devices) add_function_test(TestUtils, "test_array_scan_empty", test_array_scan_empty, devices=devices) add_function_test( TestUtils, "test_array_scan_error_sizes_mismatch", test_array_scan_error_sizes_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_scan_error_dtypes_mismatch", test_array_scan_error_dtypes_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_scan_error_unsupported_dtype", test_array_scan_error_unsupported_dtype, devices=devices ) add_function_test(TestUtils, "test_radix_sort_pairs", test_radix_sort_pairs, devices=devices) add_function_test(TestUtils, "test_radix_sort_pairs_empty", test_radix_sort_pairs, devices=devices) add_function_test( TestUtils, "test_radix_sort_pairs_error_insufficient_storage", test_radix_sort_pairs_error_insufficient_storage, devices=devices, ) add_function_test( TestUtils, "test_radix_sort_pairs_error_unsupported_dtype", test_radix_sort_pairs_error_unsupported_dtype, devices=devices, ) add_function_test(TestUtils, "test_array_sum", test_array_sum, devices=devices) add_function_test( TestUtils, "test_array_sum_error_out_dtype_mismatch", test_array_sum_error_out_dtype_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_sum_error_out_shape_mismatch", test_array_sum_error_out_shape_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_sum_error_unsupported_dtype", test_array_sum_error_unsupported_dtype, devices=devices ) add_function_test(TestUtils, "test_array_inner", test_array_inner, devices=devices) add_function_test( TestUtils, "test_array_inner_error_sizes_mismatch", test_array_inner_error_sizes_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_inner_error_dtypes_mismatch", test_array_inner_error_dtypes_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_inner_error_out_dtype_mismatch", test_array_inner_error_out_dtype_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_inner_error_out_shape_mismatch", test_array_inner_error_out_shape_mismatch, devices=devices ) add_function_test( TestUtils, "test_array_inner_error_unsupported_dtype", test_array_inner_error_unsupported_dtype, devices=devices ) add_function_test(TestUtils, "test_array_cast", test_array_cast, devices=devices) add_function_test( TestUtils, "test_array_cast_error_unsupported_partial_cast", test_array_cast_error_unsupported_partial_cast, devices=devices, ) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
18,801
Python
37.449898
118
0.633264
NVIDIA/warp/warp/tests/test_conditional.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp from warp.tests.unittest_utils import * @wp.kernel def test_conditional_if_else(): a = 0.5 b = 2.0 if a > b: c = 1.0 else: c = -1.0 wp.expect_eq(c, -1.0) @wp.kernel def test_conditional_if_else_nested(): a = 1.0 b = 2.0 if a > b: c = 3.0 d = 4.0 if c > d: e = 1.0 else: e = -1.0 else: c = 6.0 d = 7.0 if c > d: e = 2.0 else: e = -2.0 wp.expect_eq(e, -2.0) @wp.kernel def test_boolean_and(): a = 1.0 b = 2.0 c = 1.0 if a > 0.0 and b > 0.0: c = -1.0 wp.expect_eq(c, -1.0) @wp.kernel def test_boolean_or(): a = 1.0 b = 2.0 c = 1.0 if a > 0.0 and b > 0.0: c = -1.0 wp.expect_eq(c, -1.0) @wp.kernel def test_boolean_compound(): a = 1.0 b = 2.0 c = 3.0 d = 1.0 if a > 0.0 and b > 0.0 or c > a: d = -1.0 wp.expect_eq(d, -1.0) @wp.kernel def test_boolean_literal(): t = True f = False r = 1.0 if t == (not f): r = -1.0 wp.expect_eq(r, -1.0) @wp.kernel def test_int_logical_not(): x = 0 if not 123: x = 123 wp.expect_eq(x, 0) @wp.kernel def test_int_conditional_assign_overload(): if 123: x = 123 if 234: x = 234 wp.expect_eq(x, 234) @wp.kernel def test_bool_param_conditional(foo: bool): if foo: x = 123 wp.expect_eq(x, 123) @wp.kernel def test_conditional_chain_basic(): x = -1 if 0 < x < 1: success = False else: success = True wp.expect_eq(success, True) @wp.kernel def test_conditional_chain_empty_range(): x = -1 y = 4 if -2 <= x <= 10 <= y: success = False else: success = True wp.expect_eq(success, True) @wp.kernel def test_conditional_chain_faker(): x = -1 # Not actually a chained inequality if (-2 < x) < (1 > 0): success = False else: success = True wp.expect_eq(success, True) @wp.kernel def test_conditional_chain_and(): x = -1 if (-2 < x < 0) and (-1 <= x <= -1): success = True else: success = False wp.expect_eq(success, True) @wp.kernel def test_conditional_chain_eqs(): x = wp.int32(10) y = 10 z = -10 if x == y != z: success = True else: success = False wp.expect_eq(success, True) @wp.kernel def test_conditional_chain_mixed(): x = 0 if x < 10 == 1: success = False else: success = True wp.expect_eq(success, True) def test_conditional_unequal_types(test: unittest.TestCase, device): # The bad kernel must be in a separate module, otherwise the current module would fail to load from warp.tests.aux_test_conditional_unequal_types_kernels import ( unequal_types_kernel, ) with test.assertRaises(TypeError): wp.launch(unequal_types_kernel, dim=(1,), inputs=[], device=device) # remove all references to the bad module so that subsequent calls to wp.force_load() # won't try to load it unless we explicitly re-import it again del wp.context.user_modules["warp.tests.aux_test_conditional_unequal_types_kernels"] del sys.modules["warp.tests.aux_test_conditional_unequal_types_kernels"] devices = get_test_devices() class TestConditional(unittest.TestCase): pass add_kernel_test(TestConditional, kernel=test_conditional_if_else, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_if_else_nested, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_boolean_and, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_boolean_or, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_boolean_compound, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_boolean_literal, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_int_logical_not, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_int_conditional_assign_overload, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_bool_param_conditional, dim=1, inputs=[True], devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_chain_basic, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_chain_empty_range, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_chain_faker, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_chain_and, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_chain_eqs, dim=1, devices=devices) add_kernel_test(TestConditional, kernel=test_conditional_chain_mixed, dim=1, devices=devices) add_function_test(TestConditional, "test_conditional_unequal_types", test_conditional_unequal_types, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
5,501
Python
21.457143
117
0.635703
NVIDIA/warp/warp/tests/unused_test_misc.py
# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import numpy as np import warp as wp @wp.kernel def arange(out: wp.array(dtype=int)): tid = wp.tid() out[tid] = tid device = "cuda:0" cmds = [] n = 10 arrays = [] for _i in range(5): arrays.append(wp.zeros(n, dtype=int, device=device)) # setup CUDA graph wp.capture_begin() # launch kernels and keep command object around for i in range(5): cmd = wp.launch(arange, dim=n, inputs=[arrays[i]], device=device, record_cmd=True) cmds.append(cmd) graph = wp.capture_end() # --------------------------------------- ref = np.arange(0, n, dtype=int) wp.capture_launch(graph) for i in range(5): print(arrays[i].numpy()) # --------------------------------------- n = 16 arrays = [] for _i in range(5): arrays.append(wp.zeros(n, dtype=int, device=device)) # update graph params for i in range(5): cmd.set_dim(n) cmd.set_param(arrays[i]) cmd.update_graph() wp.capture_launch(graph) wp.synchronize() ref = np.arange(0, n, dtype=int) for i in range(5): print(arrays[i].numpy())
1,454
Python
19.785714
86
0.657497
NVIDIA/warp/warp/tests/test_noise.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def pnoise( kernel_seed: int, W: int, px: int, py: int, noise_values: wp.array(dtype=float), pixel_values: wp.array(dtype=float) ): tid = wp.tid() state = wp.rand_init(kernel_seed) x = (float(tid % W) + 0.5) * 0.2 y = (float(tid / W) + 0.5) * 0.2 p = wp.vec2(x, y) n = wp.pnoise(state, p, px, py) noise_values[tid] = n g = ((n + 1.0) / 2.0) * 255.0 pixel_values[tid] = g @wp.kernel def curlnoise(kernel_seed: int, W: int, noise_coords: wp.array(dtype=wp.vec2), noise_vectors: wp.array(dtype=wp.vec2)): tid = wp.tid() state = wp.rand_init(kernel_seed) x = (float(tid % W) + 0.5) * 0.2 y = (float(tid / W) + 0.5) * 0.2 p = wp.vec2(x, y) v = wp.curlnoise(state, p) noise_coords[tid] = p noise_vectors[tid] = v def test_pnoise(test, device): # image dim W = 256 H = 256 N = W * H seed = 42 # periodic perlin noise test px = 16 py = 16 noise_values = wp.zeros(N, dtype=float, device=device) pixel_values = wp.zeros(N, dtype=float, device=device) wp.launch(kernel=pnoise, dim=N, inputs=[seed, W, px, py, noise_values, pixel_values], outputs=[], device=device) # Perlin theoretical range is [-0.5*sqrt(n), 0.5*sqrt(n)] for n dimensions n = noise_values.numpy() # max = np.max(n) # min = np.min(n) img = pixel_values.numpy() img = np.reshape(img, (W, H)) ### Figure viewing ### # img = img.astype(np.uint8) # imgplot = plt.imshow(img, 'gray') # plt.savefig("pnoise_test.png") ### Generating pnoise_test_result_true.npy ### # np.save(os.path.join(os.path.dirname(__file__), "assets/pnoise_golden.npy"), img) ### Golden image comparison ### img_true = np.load(os.path.join(os.path.dirname(__file__), "assets/pnoise_golden.npy")) test.assertTrue(img.shape == img_true.shape) err = np.max(np.abs(img - img_true)) tolerance = 1.5e-3 test.assertTrue(err < tolerance, f"err is {err} which is >= {tolerance}") def test_curlnoise(test, device): # image dim W = 128 H = 128 N = W * H seed = 42 # curl noise test quiver_coords_host = wp.zeros(N, dtype=wp.vec2, device="cpu") quiver_coords = wp.zeros(N, dtype=wp.vec2, device=device) quiver_arrows_host = wp.zeros(N, dtype=wp.vec2, device="cpu") quiver_arrows = wp.zeros(N, dtype=wp.vec2, device=device) wp.launch(kernel=curlnoise, dim=N, inputs=[seed, W, quiver_coords, quiver_arrows], outputs=[], device=device) wp.copy(quiver_coords_host, quiver_coords) wp.copy(quiver_arrows_host, quiver_arrows) wp.synchronize() xy_coords = quiver_coords_host.numpy() uv_coords = quiver_arrows_host.numpy() # normalize norms = uv_coords[:, 0] * uv_coords[:, 0] + uv_coords[:, 1] * uv_coords[:, 1] uv_coords = uv_coords / np.sqrt(np.max(norms)) X = xy_coords[:, 0] Y = xy_coords[:, 1] U = uv_coords[:, 0] V = uv_coords[:, 1] ### Figure viewing ### # fig, ax = plt.subplots(figsize=(25,25)) # ax.quiver(X, Y, U, V) # ax.axis([0.0, 25.0, 0.0, 25.0]) # ax.set_aspect('equal') # plt.savefig("curlnoise_test.png") ### Generating curlnoise_test_result_true.npy ### result = np.stack((xy_coords, uv_coords)) # np.save(os.path.join(os.path.dirname(__file__), "assets/curlnoise_golden.npy"), result) ### Golden image comparison ### result_true = np.load(os.path.join(os.path.dirname(__file__), "assets/curlnoise_golden.npy")) test.assertTrue(result.shape, result_true.shape) err = np.max(np.abs(result - result_true)) test.assertTrue(err < 1e-04) @wp.kernel def noise_loss_kernel( kernel_seed: int, query_positions: wp.array(dtype=wp.vec2), noise_values: wp.array(dtype=float), noise_loss: wp.array(dtype=float), ): tid = wp.tid() state = wp.rand_init(kernel_seed) p = query_positions[tid] n = wp.noise(state, p) noise_values[tid] = n wp.atomic_add(noise_loss, 0, n) @wp.kernel def noise_cd(kernel_seed: int, query_positions: wp.array(dtype=wp.vec2), gradients: wp.array(dtype=wp.vec2)): tid = wp.tid() state = wp.rand_init(kernel_seed) p = query_positions[tid] eps = 1.0e-3 pl = wp.vec2(p[0] - eps, p[1]) pr = wp.vec2(p[0] + eps, p[1]) pd = wp.vec2(p[0], p[1] - eps) pu = wp.vec2(p[0], p[1] + eps) nl = wp.noise(state, pl) nr = wp.noise(state, pr) nd = wp.noise(state, pd) nu = wp.noise(state, pu) gx = (nr - nl) / (2.0 * eps) gy = (nu - nd) / (2.0 * eps) gradients[tid] = wp.vec2(gx, gy) def test_adj_noise(test, device): # grid dim N = 9 seed = 42 tape = wp.Tape() positions = np.array( [ [-0.1, -0.1], [0.0, -0.1], [0.1, -0.1], [-0.1, 0.0], [0.0, 0.0], [0.1, 0.0], [-0.1, 0.1], [0.0, 0.1], [0.1, 0.1], ] ) with tape: query_positions = wp.array(positions, dtype=wp.vec2, device=device, requires_grad=True) noise_values = wp.zeros(N, dtype=float, device=device) noise_loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True) wp.launch( kernel=noise_loss_kernel, dim=N, inputs=[seed, query_positions, noise_values, noise_loss], device=device ) # analytic tape.backward(loss=noise_loss) analytic = tape.gradients[query_positions].numpy().reshape((3, 3, 2)) # central difference gradients = wp.zeros(N, dtype=wp.vec2, device=device) wp.launch(kernel=noise_cd, dim=N, inputs=[seed, query_positions, gradients], device=device) gradients_host = gradients.numpy().reshape((3, 3, 2)) diff = analytic - gradients_host result = np.sum(diff * diff, axis=2) err = np.where(result > 1.0e-3, result, 0).sum() test.assertTrue(err < 1.0e-8) devices = get_test_devices() class TestNoise(unittest.TestCase): pass add_function_test(TestNoise, "test_pnoise", test_pnoise, devices=devices) add_function_test(TestNoise, "test_curlnoise", test_curlnoise, devices=devices) add_function_test(TestNoise, "test_adj_noise", test_adj_noise, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
6,826
Python
26.865306
120
0.607237
NVIDIA/warp/warp/tests/test_transient_module.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os import tempfile import unittest from importlib import util import warp as wp from warp.tests.unittest_utils import * CODE = """# -*- coding: utf-8 -*- import warp as wp @wp.struct class Data: x: wp.array(dtype=int) @wp.func def increment(x: int): # This shouldn't be picked up. return x + 123 @wp.func def increment(x: int): return x + 1 @wp.kernel def compute(data: Data): data.x[0] = increment(data.x[0]) """ def load_code_as_module(code, name): file, file_path = tempfile.mkstemp(suffix=".py") try: with os.fdopen(file, "w") as f: f.write(code) spec = util.spec_from_file_location(name, file_path) module = util.module_from_spec(spec) spec.loader.exec_module(module) finally: os.remove(file_path) return module def test_transient_module(test, device): module = load_code_as_module(CODE, "") # Loading it a second time shouldn't be an issue. module = load_code_as_module(CODE, "") assert len(module.compute.module.structs) == 1 assert len(module.compute.module.functions) == 1 data = module.Data() data.x = wp.array([123], dtype=int, device=device) wp.set_module_options({"foo": "bar"}, module=module) assert wp.get_module_options(module=module).get("foo") == "bar" assert module.compute.module.options.get("foo") == "bar" wp.launch(module.compute, dim=1, inputs=[data], device=device) assert_np_equal(data.x.numpy(), np.array([124])) devices = get_test_devices() class TestTransientModule(unittest.TestCase): pass add_function_test(TestTransientModule, "test_transient_module", test_transient_module, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
2,212
Python
24.732558
103
0.686709
NVIDIA/warp/warp/tests/test_copy.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def mul_1d(a: wp.array1d(dtype=float), s: float): i = wp.tid() a[i] = a[i] * s @wp.kernel def mul_2d(a: wp.array2d(dtype=float), s: float): i, j = wp.tid() a[i, j] = a[i, j] * s @wp.kernel def mul_3d(a: wp.array3d(dtype=float), s: float): i, j, k = wp.tid() a[i, j, k] = a[i, j, k] * s @wp.kernel def mul_4d(a: wp.array4d(dtype=float), s: float): i, j, k, l = wp.tid() a[i, j, k, l] = a[i, j, k, l] * s def test_copy_strided(test, device): with wp.ScopedDevice(device): np_data1 = np.arange(10, dtype=np.float32) np_data2 = np.arange(100, dtype=np.float32).reshape((10, 10)) np_data3 = np.arange(1000, dtype=np.float32).reshape((10, 10, 10)) np_data4 = np.arange(10000, dtype=np.float32).reshape((10, 10, 10, 10)) wp_data1 = wp.array(data=np_data1, copy=True) wp_data2 = wp.array(data=np_data2, copy=True) wp_data3 = wp.array(data=np_data3, copy=True) wp_data4 = wp.array(data=np_data4, copy=True) expected1 = np_data1[1::2] expected2 = np_data2[1::2, 1::2] expected3 = np_data3[1::2, 1::2, 1::2] expected4 = np_data4[1::2, 1::2, 1::2, 1::2] a1 = wp_data1[1::2] a2 = wp_data2[1::2, 1::2] a3 = wp_data3[1::2, 1::2, 1::2] a4 = wp_data4[1::2, 1::2, 1::2, 1::2] assert_np_equal(a1.numpy(), expected1) assert_np_equal(a2.numpy(), expected2) assert_np_equal(a3.numpy(), expected3) assert_np_equal(a4.numpy(), expected4) b1 = wp.zeros_like(a1) b2 = wp.zeros_like(a2) b3 = wp.zeros_like(a3) b4 = wp.zeros_like(a4) test.assertFalse(a1.is_contiguous) test.assertFalse(a2.is_contiguous) test.assertFalse(a3.is_contiguous) test.assertFalse(a4.is_contiguous) test.assertTrue(b1.is_contiguous) test.assertTrue(b2.is_contiguous) test.assertTrue(b3.is_contiguous) test.assertTrue(b4.is_contiguous) # copy non-contiguous to contiguous wp.copy(b1, a1) wp.copy(b2, a2) wp.copy(b3, a3) wp.copy(b4, a4) assert_np_equal(a1.numpy(), b1.numpy()) assert_np_equal(a2.numpy(), b2.numpy()) assert_np_equal(a3.numpy(), b3.numpy()) assert_np_equal(a4.numpy(), b4.numpy()) s = 2.0 wp.launch(mul_1d, dim=b1.shape, inputs=[b1, s]) wp.launch(mul_2d, dim=b2.shape, inputs=[b2, s]) wp.launch(mul_3d, dim=b3.shape, inputs=[b3, s]) wp.launch(mul_4d, dim=b4.shape, inputs=[b4, s]) # copy contiguous to non-contiguous wp.copy(a1, b1) wp.copy(a2, b2) wp.copy(a3, b3) wp.copy(a4, b4) assert_np_equal(a1.numpy(), b1.numpy()) assert_np_equal(a2.numpy(), b2.numpy()) assert_np_equal(a3.numpy(), b3.numpy()) assert_np_equal(a4.numpy(), b4.numpy()) assert_np_equal(a1.numpy(), expected1 * s) assert_np_equal(a2.numpy(), expected2 * s) assert_np_equal(a3.numpy(), expected3 * s) assert_np_equal(a4.numpy(), expected4 * s) def test_copy_indexed(test, device): with wp.ScopedDevice(device): np_data1 = np.arange(10, dtype=np.float32) np_data2 = np.arange(100, dtype=np.float32).reshape((10, 10)) np_data3 = np.arange(1000, dtype=np.float32).reshape((10, 10, 10)) np_data4 = np.arange(10000, dtype=np.float32).reshape((10, 10, 10, 10)) wp_data1 = wp.array(data=np_data1, copy=True) wp_data2 = wp.array(data=np_data2, copy=True) wp_data3 = wp.array(data=np_data3, copy=True) wp_data4 = wp.array(data=np_data4, copy=True) np_indices = np.array([1, 5, 8, 9]) wp_indices = wp.array(data=np_indices, dtype=wp.int32) # Note: Indexing using multiple index arrays works differently # in Numpy and Warp, so the syntax is different. expected1 = np_data1[np_indices] expected2 = np_data2[np_indices][:, np_indices] expected3 = np_data3[np_indices][:, np_indices][:, :, np_indices] expected4 = np_data4[np_indices][:, np_indices][:, :, np_indices][:, :, :, np_indices] a1 = wp_data1[wp_indices] a2 = wp_data2[wp_indices, wp_indices] a3 = wp_data3[wp_indices, wp_indices, wp_indices] a4 = wp_data4[wp_indices, wp_indices, wp_indices, wp_indices] assert_np_equal(a1.numpy(), expected1) assert_np_equal(a2.numpy(), expected2) assert_np_equal(a3.numpy(), expected3) assert_np_equal(a4.numpy(), expected4) b1 = wp.zeros_like(a1) b2 = wp.zeros_like(a2) b3 = wp.zeros_like(a3) b4 = wp.zeros_like(a4) test.assertFalse(a1.is_contiguous) test.assertFalse(a2.is_contiguous) test.assertFalse(a3.is_contiguous) test.assertFalse(a4.is_contiguous) test.assertTrue(b1.is_contiguous) test.assertTrue(b2.is_contiguous) test.assertTrue(b3.is_contiguous) test.assertTrue(b4.is_contiguous) # copy non-contiguous to contiguous wp.copy(b1, a1) wp.copy(b2, a2) wp.copy(b3, a3) wp.copy(b4, a4) assert_np_equal(a1.numpy(), b1.numpy()) assert_np_equal(a2.numpy(), b2.numpy()) assert_np_equal(a3.numpy(), b3.numpy()) assert_np_equal(a4.numpy(), b4.numpy()) s = 2.0 wp.launch(mul_1d, dim=b1.shape, inputs=[b1, s]) wp.launch(mul_2d, dim=b2.shape, inputs=[b2, s]) wp.launch(mul_3d, dim=b3.shape, inputs=[b3, s]) wp.launch(mul_4d, dim=b4.shape, inputs=[b4, s]) # copy contiguous to non-contiguous wp.copy(a1, b1) wp.copy(a2, b2) wp.copy(a3, b3) wp.copy(a4, b4) assert_np_equal(a1.numpy(), b1.numpy()) assert_np_equal(a2.numpy(), b2.numpy()) assert_np_equal(a3.numpy(), b3.numpy()) assert_np_equal(a4.numpy(), b4.numpy()) assert_np_equal(a1.numpy(), expected1 * s) assert_np_equal(a2.numpy(), expected2 * s) assert_np_equal(a3.numpy(), expected3 * s) assert_np_equal(a4.numpy(), expected4 * s) def test_copy_adjoint(test, device): state_in = wp.from_numpy( np.array([1.0, 2.0, 3.0]).astype(np.float32), dtype=wp.float32, requires_grad=True, device=device ) state_out = wp.zeros(state_in.shape, dtype=wp.float32, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.copy(state_out, state_in) grads = {state_out: wp.from_numpy(np.array([1.0, 1.0, 1.0]).astype(np.float32), dtype=wp.float32, device=device)} tape.backward(grads=grads) assert_np_equal(state_in.grad.numpy(), np.array([1.0, 1.0, 1.0]).astype(np.float32)) devices = get_test_devices() class TestCopy(unittest.TestCase): pass add_function_test(TestCopy, "test_copy_strided", test_copy_strided, devices=devices) add_function_test(TestCopy, "test_copy_indexed", test_copy_indexed, devices=devices) add_function_test(TestCopy, "test_copy_adjoint", test_copy_adjoint, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
7,709
Python
32.376623
117
0.601245
NVIDIA/warp/warp/tests/test_types.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest from warp.tests.unittest_utils import * def test_integers(test, device, dtype): value = dtype(0) test.assertIsInstance(bool(value), bool) test.assertIsInstance(int(value), int) test.assertIsInstance(float(value), float) test.assertEqual(bool(value), False) test.assertEqual(int(value), 0) test.assertEqual(float(value), 0.0) try: ctypes.c_bool(value) ctypes.c_int(value) ctypes.c_float(value) except Exception: test.fail() value = dtype(123) test.assertIsInstance(bool(value), bool) test.assertIsInstance(int(value), int) test.assertIsInstance(float(value), float) test.assertEqual(bool(value), True) test.assertEqual(int(value), 123) test.assertEqual(float(value), 123.0) try: ctypes.c_bool(value) ctypes.c_int(value) ctypes.c_float(value) except Exception: test.fail() def test_floats(test, device, dtype): value = dtype(0.0) test.assertIsInstance(bool(value), bool) test.assertIsInstance(int(value), int) test.assertIsInstance(float(value), float) test.assertEqual(bool(value), False) test.assertEqual(int(value), 0) test.assertEqual(float(value), 0.0) try: ctypes.c_bool(value) ctypes.c_float(value) except Exception: test.fail() value = dtype(1.25) test.assertIsInstance(bool(value), bool) test.assertIsInstance(int(value), int) test.assertIsInstance(float(value), float) test.assertEqual(bool(value), True) test.assertEqual(int(value), 1) test.assertEqual(float(value), 1.25) try: ctypes.c_bool(value) ctypes.c_float(value) except Exception: test.fail() def test_vector(test, device, dtype): def make_scalar(x): # Cast to the correct integer type to simulate wrapping. if dtype in wp.types.int_types: return dtype._type_(x).value return x def make_vec(*args): if dtype in wp.types.int_types: # Cast to the correct integer type to simulate wrapping. return tuple(dtype._type_(x).value for x in args) return args vec3_cls = wp.vec(3, dtype) vec4_cls = wp.vec(4, dtype) v = vec4_cls(1, 2, 3, 4) test.assertEqual(v[0], make_scalar(1)) test.assertEqual(v.x, make_scalar(1)) test.assertEqual(v.y, make_scalar(2)) test.assertEqual(v.z, make_scalar(3)) test.assertEqual(v.w, make_scalar(4)) test.assertSequenceEqual(v[0:2], make_vec(1, 2)) test.assertSequenceEqual(v, make_vec(1, 2, 3, 4)) v[0] = -1 test.assertEqual(v[0], make_scalar(-1)) test.assertEqual(v.x, make_scalar(-1)) test.assertEqual(v.y, make_scalar(2)) test.assertEqual(v.z, make_scalar(3)) test.assertEqual(v.w, make_scalar(4)) test.assertSequenceEqual(v[0:2], make_vec(-1, 2)) test.assertSequenceEqual(v, make_vec(-1, 2, 3, 4)) v[1:3] = (-2, -3) test.assertEqual(v[0], make_scalar(-1)) test.assertEqual(v.x, make_scalar(-1)) test.assertEqual(v.y, make_scalar(-2)) test.assertEqual(v.z, make_scalar(-3)) test.assertEqual(v.w, make_scalar(4)) test.assertSequenceEqual(v[0:2], make_vec(-1, -2)) test.assertSequenceEqual(v, make_vec(-1, -2, -3, 4)) v.x = 1 test.assertEqual(v[0], make_scalar(1)) test.assertEqual(v.x, make_scalar(1)) test.assertEqual(v.y, make_scalar(-2)) test.assertEqual(v.z, make_scalar(-3)) test.assertEqual(v.w, make_scalar(4)) test.assertSequenceEqual(v[0:2], make_vec(1, -2)) test.assertSequenceEqual(v, make_vec(1, -2, -3, 4)) v = vec3_cls(2, 4, 6) test.assertSequenceEqual(+v, make_vec(2, 4, 6)) test.assertSequenceEqual(-v, make_vec(-2, -4, -6)) test.assertSequenceEqual(v + vec3_cls(1, 1, 1), make_vec(3, 5, 7)) test.assertSequenceEqual(v - vec3_cls(1, 1, 1), make_vec(1, 3, 5)) test.assertSequenceEqual(v * dtype(2), make_vec(4, 8, 12)) test.assertSequenceEqual(dtype(2) * v, make_vec(4, 8, 12)) test.assertSequenceEqual(v / dtype(2), make_vec(1, 2, 3)) test.assertSequenceEqual(dtype(12) / v, make_vec(6, 3, 2)) test.assertTrue(v != vec3_cls(1, 2, 3)) test.assertEqual(str(v), "[{}]".format(", ".join(str(x) for x in v))) # Check added purely for coverage reasons but is this really a desired # behaviour? Not allowing to define new attributes using systems like # `__slots__` could help improving memory usage. v.foo = 123 test.assertEqual(v.foo, 123) devices = [x for x in get_test_devices() if x.is_cpu] class TestTypes(unittest.TestCase): def test_bool(self): value = wp.bool(False) self.assertIsInstance(bool(value), bool) self.assertIsInstance(int(value), int) self.assertIsInstance(float(value), float) self.assertEqual(bool(value), False) self.assertEqual(int(value), 0) self.assertEqual(float(value), 0.0) try: ctypes.c_bool(value) except Exception: self.fail() value = wp.bool(True) self.assertIsInstance(bool(value), bool) self.assertIsInstance(int(value), int) self.assertIsInstance(float(value), float) self.assertEqual(bool(value), True) self.assertEqual(int(value), 1) self.assertEqual(float(value), 1.0) try: ctypes.c_bool(value) except Exception: self.fail() value = wp.bool(0.0) self.assertIsInstance(bool(value), bool) self.assertIsInstance(int(value), int) self.assertIsInstance(float(value), float) self.assertEqual(bool(value), False) self.assertEqual(int(value), 0) self.assertEqual(float(value), 0.0) try: ctypes.c_bool(value) except Exception: self.fail() value = wp.bool(123) self.assertIsInstance(bool(value), bool) self.assertIsInstance(int(value), int) self.assertIsInstance(float(value), float) self.assertEqual(bool(value), True) self.assertEqual(int(value), 1) self.assertEqual(float(value), 1.0) try: ctypes.c_bool(value) except Exception: self.fail() def test_constant(self): const = wp.constant(123) self.assertEqual(const, 123) const = wp.constant(1.25) self.assertEqual(const, 1.25) const = wp.constant(True) self.assertEqual(const, True) const = wp.constant(wp.float16(1.25)) self.assertEqual(const.value, 1.25) const = wp.constant(wp.int16(123)) self.assertEqual(const.value, 123) const = wp.constant(wp.vec3i(1, 2, 3)) self.assertEqual(const, wp.vec3i(1, 2, 3)) def test_constant_error_invalid_type(self): with self.assertRaisesRegex(RuntimeError, r"Invalid constant type: <class 'tuple'>$"): wp.constant((1, 2, 3)) def test_vector_assign(self): v = wp.vec3s() v[0] = 1 v[1] = wp.int8(2) v[2] = np.int8(3) self.assertEqual(v, (1, 2, 3)) v = wp.vec3h() v[0] = 1.0 v[1] = wp.float16(2.0) v[2] = np.float16(3.0) self.assertEqual(v, (1.0, 2.0, 3.0)) def test_vector_error_invalid_arg_count(self): with self.assertRaisesRegex( ValueError, r"Invalid number of arguments in vector constructor, expected 3 elements, got 2$" ): wp.vec3(1, 2) def test_vector_error_invalid_ptr(self): with self.assertRaisesRegex(RuntimeError, r"NULL pointer exception"): wp.vec3.from_ptr(0) def test_vector_error_invalid_get_item_key(self): v = wp.vec3(1, 2, 3) with self.assertRaisesRegex(KeyError, r"Invalid key None, expected int or slice"): v[None] def test_vector_error_invalid_set_item_key(self): v = wp.vec3(1, 2, 3) with self.assertRaisesRegex(KeyError, r"Invalid key None, expected int or slice"): v[None] = 0 def test_vector_error_invalid_set_item_value(self): v1 = wp.vec3i(1, 2, 3) v2 = wp.vec3h(1, 2, 3) with self.assertRaisesRegex(TypeError, r"Expected to assign a `int32` value but got `str` instead"): v1[0] = "123.0" with self.assertRaisesRegex( TypeError, r"Expected to assign a slice from a sequence of values but got `int` instead" ): v1[:] = 123 with self.assertRaisesRegex( TypeError, r"Expected to assign a slice from a sequence of `int32` values but got `vec3i` instead" ): v1[:1] = (v1,) with self.assertRaisesRegex(ValueError, r"Can only assign sequence of same size"): v1[:1] = (1, 2) with self.assertRaisesRegex( TypeError, r"Expected to assign a slice from a sequence of `float16` values but got `vec3h` instead" ): v2[:1] = (v2,) def test_matrix(self): for dtype in tuple(wp.types.float_types) + (float,): def make_scalar(x, dtype=dtype): # Cast to the correct integer type to simulate wrapping. if dtype in wp.types.int_types: return dtype._type_(x).value return x def make_vec(*args, dtype=dtype): if dtype in wp.types.int_types: # Cast to the correct integer type to simulate wrapping. return tuple(dtype._type_(x).value for x in args) return args def make_mat(*args, dtype=dtype): if dtype in wp.types.int_types: # Cast to the correct integer type to simulate wrapping. return tuple(tuple(dtype._type_(x).value for x in row) for row in args) return args mat22_cls = wp.mat((2, 2), dtype) mat33_cls = wp.mat((3, 3), dtype) vec2_cls = wp.vec(2, dtype) m = mat33_cls(((1, 2, 3), (4, 5, 6), (7, 8, 9))) self.assertEqual(m[0][0], make_scalar(1)) self.assertEqual(m[0][1], make_scalar(2)) self.assertEqual(m[0][2], make_scalar(3)) self.assertEqual(m[1][0], make_scalar(4)) self.assertEqual(m[1][1], make_scalar(5)) self.assertEqual(m[1][2], make_scalar(6)) self.assertEqual(m[2][0], make_scalar(7)) self.assertEqual(m[2][1], make_scalar(8)) self.assertEqual(m[2][2], make_scalar(9)) self.assertEqual(m[0, 0], make_scalar(1)) self.assertEqual(m[0, 1], make_scalar(2)) self.assertEqual(m[0, 2], make_scalar(3)) self.assertEqual(m[1, 0], make_scalar(4)) self.assertEqual(m[1, 1], make_scalar(5)) self.assertEqual(m[1, 2], make_scalar(6)) self.assertEqual(m[2, 0], make_scalar(7)) self.assertEqual(m[2, 1], make_scalar(8)) self.assertEqual(m[2, 2], make_scalar(9)) self.assertSequenceEqual(m[0], make_vec(1, 2, 3)) self.assertSequenceEqual(m[1], make_vec(4, 5, 6)) self.assertSequenceEqual(m[2], make_vec(7, 8, 9)) self.assertSequenceEqual(m[0][1:3], make_vec(2, 3)) self.assertSequenceEqual(m[1][0:2], make_vec(4, 5)) self.assertSequenceEqual(m[2][0:3], make_vec(7, 8, 9)) # self.assertSequenceEqual(m[0, 1:3], make_vec(2, 3)) # self.assertSequenceEqual(m[1, 0:2], make_vec(4, 5)) # self.assertSequenceEqual(m[2, 0:3], make_vec(7, 8, 9)) self.assertSequenceEqual(m, make_mat((1, 2, 3), (4, 5, 6), (7, 8, 9))) m[1, 0] = -4 self.assertEqual(m[0][0], make_scalar(1)) self.assertEqual(m[0][1], make_scalar(2)) self.assertEqual(m[0][2], make_scalar(3)) self.assertEqual(m[1][0], make_scalar(-4)) self.assertEqual(m[1][1], make_scalar(5)) self.assertEqual(m[1][2], make_scalar(6)) self.assertEqual(m[2][0], make_scalar(7)) self.assertEqual(m[2][1], make_scalar(8)) self.assertEqual(m[2][2], make_scalar(9)) self.assertEqual(m[0, 0], make_scalar(1)) self.assertEqual(m[0, 1], make_scalar(2)) self.assertEqual(m[0, 2], make_scalar(3)) self.assertEqual(m[1, 0], make_scalar(-4)) self.assertEqual(m[1, 1], make_scalar(5)) self.assertEqual(m[1, 2], make_scalar(6)) self.assertEqual(m[2, 0], make_scalar(7)) self.assertEqual(m[2, 1], make_scalar(8)) self.assertEqual(m[2, 2], make_scalar(9)) self.assertSequenceEqual(m[0], make_vec(1, 2, 3)) self.assertSequenceEqual(m[1], make_vec(-4, 5, 6)) self.assertSequenceEqual(m[2], make_vec(7, 8, 9)) self.assertSequenceEqual(m[0][1:3], make_vec(2, 3)) self.assertSequenceEqual(m[1][0:2], make_vec(-4, 5)) self.assertSequenceEqual(m[2][0:3], make_vec(7, 8, 9)) # self.assertSequenceEqual(m[0, 1:3], make_vec(2, 3)) # self.assertSequenceEqual(m[1, 0:2], make_vec(-4, 5)) # self.assertSequenceEqual(m[2, 0:3], make_vec(7, 8, 9)) self.assertSequenceEqual(m, make_mat((1, 2, 3), (-4, 5, 6), (7, 8, 9))) m[2] = (-7, 8, -9) self.assertEqual(m[0][0], make_scalar(1)) self.assertEqual(m[0][1], make_scalar(2)) self.assertEqual(m[0][2], make_scalar(3)) self.assertEqual(m[1][0], make_scalar(-4)) self.assertEqual(m[1][1], make_scalar(5)) self.assertEqual(m[1][2], make_scalar(6)) self.assertEqual(m[2][0], make_scalar(-7)) self.assertEqual(m[2][1], make_scalar(8)) self.assertEqual(m[2][2], make_scalar(-9)) self.assertEqual(m[0, 0], make_scalar(1)) self.assertEqual(m[0, 1], make_scalar(2)) self.assertEqual(m[0, 2], make_scalar(3)) self.assertEqual(m[1, 0], make_scalar(-4)) self.assertEqual(m[1, 1], make_scalar(5)) self.assertEqual(m[1, 2], make_scalar(6)) self.assertEqual(m[2, 0], make_scalar(-7)) self.assertEqual(m[2, 1], make_scalar(8)) self.assertEqual(m[2, 2], make_scalar(-9)) self.assertSequenceEqual(m[0], make_vec(1, 2, 3)) self.assertSequenceEqual(m[1], make_vec(-4, 5, 6)) self.assertSequenceEqual(m[2], make_vec(-7, 8, -9)) self.assertSequenceEqual(m[0][1:3], make_vec(2, 3)) self.assertSequenceEqual(m[1][0:2], make_vec(-4, 5)) self.assertSequenceEqual(m[2][0:3], make_vec(-7, 8, -9)) # self.assertSequenceEqual(m[0, 1:3], make_vec(2, 3)) # self.assertSequenceEqual(m[1, 0:2], make_vec(-4, 5)) # self.assertSequenceEqual(m[2, 0:3], make_vec(-7, 8, -9)) self.assertSequenceEqual(m, make_mat((1, 2, 3), (-4, 5, 6), (-7, 8, -9))) m = mat22_cls(2, 4, 6, 8) self.assertSequenceEqual(+m, make_mat((2, 4), (6, 8))) self.assertSequenceEqual(-m, make_mat((-2, -4), (-6, -8))) self.assertSequenceEqual(m + mat22_cls(1, 1, 1, 1), make_mat((3, 5), (7, 9))) self.assertSequenceEqual(m - mat22_cls(1, 1, 1, 1), make_mat((1, 3), (5, 7))) self.assertSequenceEqual(m * dtype(2), make_mat((4, 8), (12, 16))) self.assertSequenceEqual(dtype(2) * m, make_mat((4, 8), (12, 16))) self.assertSequenceEqual(m / dtype(2), make_mat((1, 2), (3, 4))) self.assertSequenceEqual(dtype(24) / m, make_mat((12, 6), (4, 3))) self.assertSequenceEqual(m * vec2_cls(1, 2), make_vec(10, 22)) self.assertSequenceEqual(m @ vec2_cls(1, 2), make_vec(10, 22)) self.assertSequenceEqual(vec2_cls(1, 2) * m, make_vec(14, 20)) self.assertSequenceEqual(vec2_cls(1, 2) @ m, make_vec(14, 20)) self.assertTrue(m != mat22_cls(1, 2, 3, 4)) self.assertEqual( str(m), "[{}]".format(",\n ".join("[{}]".format(", ".join(str(y) for y in m[x])) for x in range(m._shape_[0]))), ) # Check added purely for coverage reasons but is this really a desired # behaviour? Not allowing to define new attributes using systems like # `__slots__` could help improving memory usage. m.foo = 123 self.assertEqual(m.foo, 123) def test_matrix_error_invalid_arg_count(self): with self.assertRaisesRegex( ValueError, r"Invalid number of arguments in matrix constructor, expected 4 elements, got 3$" ): wp.mat22(1, 2, 3) def test_matrix_error_invalid_row_count(self): with self.assertRaisesRegex( TypeError, r"Invalid argument in matrix constructor, expected row of length 2, got \(1, 2, 3\)$" ): wp.mat22((1, 2, 3), (3, 4, 5)) def test_matrix_error_invalid_ptr(self): with self.assertRaisesRegex(RuntimeError, r"NULL pointer exception"): wp.mat22.from_ptr(0) def test_matrix_error_invalid_set_row_index(self): m = wp.mat22(1, 2, 3, 4) with self.assertRaisesRegex(IndexError, r"Invalid row index$"): m.set_row(2, (0, 0)) def test_matrix_error_invalid_get_item_key(self): m = wp.mat22(1, 2, 3, 4) with self.assertRaisesRegex(KeyError, r"Invalid key None, expected int or pair of ints"): m[None] def test_matrix_error_invalid_get_item_key_length(self): m = wp.mat22(1, 2, 3, 4) with self.assertRaisesRegex(KeyError, r"Invalid key, expected one or two indices, got 3"): m[0, 1, 2] def test_matrix_error_invalid_set_item_key(self): m = wp.mat22(1, 2, 3, 4) with self.assertRaisesRegex(KeyError, r"Invalid key None, expected int or pair of ints"): m[None] = 0 def test_matrix_error_invalid_set_item_key_length(self): m = wp.mat22(1, 2, 3, 4) with self.assertRaisesRegex(KeyError, r"Invalid key, expected one or two indices, got 3"): m[0, 1, 2] = (0, 0) def test_matrix_error_invalid_set_item_value(self): m = wp.mat22h(1, 2, 3, 4) with self.assertRaisesRegex(TypeError, r"Expected to assign a `float16` value but got `str` instead"): m[0, 0] = "123.0" with self.assertRaisesRegex(TypeError, r"Expected to assign a `float16` value but got `str` instead"): m[0][0] = "123.0" with self.assertRaisesRegex( TypeError, r"Expected to assign a slice from a sequence of values but got `int` instead" ): m[0] = 123 with self.assertRaisesRegex( TypeError, r"Expected to assign a slice from a sequence of `float16` values but got `mat22h` instead" ): m[0] = (m,) with self.assertRaisesRegex( KeyError, r"Slices are not supported when indexing matrices using the `m\[start:end\]` notation" ): m[:] = 123 with self.assertRaisesRegex( KeyError, r"Slices are not supported when indexing matrices using the `m\[i, j\]` notation" ): m[0, :1] = (123,) with self.assertRaisesRegex(ValueError, r"Can only assign sequence of same size"): m[0][:1] = (1, 2) def test_dtype_from_numpy(self): import numpy as np def test_conversions(np_type, warp_type): self.assertEqual(wp.dtype_from_numpy(np_type), warp_type) self.assertEqual(wp.dtype_from_numpy(np.dtype(np_type)), warp_type) test_conversions(np.float16, wp.float16) test_conversions(np.float32, wp.float32) test_conversions(np.float64, wp.float64) test_conversions(np.int8, wp.int8) test_conversions(np.int16, wp.int16) test_conversions(np.int32, wp.int32) test_conversions(np.int64, wp.int64) test_conversions(np.uint8, wp.uint8) test_conversions(np.uint16, wp.uint16) test_conversions(np.uint32, wp.uint32) test_conversions(np.uint64, wp.uint64) test_conversions(np.bool_, wp.bool) test_conversions(np.byte, wp.int8) test_conversions(np.ubyte, wp.uint8) def test_dtype_to_numpy(self): import numpy as np def test_conversions(warp_type, np_type): self.assertEqual(wp.dtype_to_numpy(warp_type), np_type) test_conversions(wp.float16, np.float16) test_conversions(wp.float32, np.float32) test_conversions(wp.float64, np.float64) test_conversions(wp.int8, np.int8) test_conversions(wp.int16, np.int16) test_conversions(wp.int32, np.int32) test_conversions(wp.int64, np.int64) test_conversions(wp.uint8, np.uint8) test_conversions(wp.uint16, np.uint16) test_conversions(wp.uint32, np.uint32) test_conversions(wp.uint64, np.uint64) test_conversions(wp.bool, np.bool_) for dtype in wp.types.int_types: add_function_test(TestTypes, f"test_integers_{dtype.__name__}", test_integers, devices=devices, dtype=dtype) for dtype in wp.types.float_types: add_function_test(TestTypes, f"test_floats_{dtype.__name__}", test_floats, devices=devices, dtype=dtype) for dtype in tuple(wp.types.scalar_types) + (int, float): add_function_test(TestTypes, f"test_vector_{dtype.__name__}", test_vector, devices=devices, dtype=dtype) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
22,115
Python
38.848649
120
0.588605
NVIDIA/warp/warp/tests/test_compile_consts.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp import warp.tests.aux_test_compile_consts_dummy from warp.tests.unittest_utils import * LOCAL_ONE = wp.constant(1) SQRT3_OVER_3 = wp.constant(0.57735026919) UNIT_VEC = wp.constant(wp.vec3(SQRT3_OVER_3, SQRT3_OVER_3, SQRT3_OVER_3)) ONE_FP16 = wp.constant(wp.float16(1.0)) TEST_BOOL = wp.constant(True) class Foobar: ONE = wp.constant(1) TWO = wp.constant(2) @wp.kernel def test_bool(): if TEST_BOOL: expect_eq(1.0, 1.0) else: expect_eq(1.0, -1.0) @wp.kernel def test_int(a: int): if Foobar.ONE > 0: a = 123 + Foobar.TWO + warp.tests.aux_test_compile_consts_dummy.MINUS_ONE else: a = 456 + LOCAL_ONE expect_eq(a, 124) @wp.kernel def test_float(x: float): x = SQRT3_OVER_3 for i in range(3): expect_eq(UNIT_VEC[i], x) approx_one = wp.dot(UNIT_VEC, UNIT_VEC) expect_near(approx_one, 1.0, 1e-6) # test casting expect_near(wp.float32(ONE_FP16), 1.0, 1e-6) def test_closure_capture(test, device): def make_closure_kernel(cst): def closure_kernel_fn(expected: int): wp.expect_eq(cst, expected) return wp.Kernel(func=closure_kernel_fn) one_closure = make_closure_kernel(Foobar.ONE) two_closure = make_closure_kernel(Foobar.TWO) wp.launch(one_closure, dim=(1), inputs=[1], device=device) wp.launch(two_closure, dim=(1), inputs=[2], device=device) def test_hash_global_capture(test, device): """Verifies that global variables are included in the module hash""" a = 0 wp.launch(test_int, (1,), inputs=[a], device=device) module_constants = wp.get_module(test_int.__module__).constants # Ensure the expected constants and values are in the dictionary used in hashing # Depending on what's been launched already, there might be additional constants present test.assertEqual(module_constants["Foobar.ONE"], 1) test.assertEqual(module_constants["Foobar.TWO"], 2) test.assertEqual(module_constants["warp.tests.aux_test_compile_consts_dummy.MINUS_ONE"], -1) test.assertEqual(module_constants["LOCAL_ONE"], 1) def test_hash_redefine_kernel(test, device): """This test defines a second ``test_function`` so that the second launch returns the correct result.""" @wp.kernel def test_function(data: wp.array(dtype=wp.float32)): i = wp.tid() data[i] = TEST_CONSTANT TEST_CONSTANT = wp.constant(1.0) test_array = wp.empty(1, dtype=wp.float32, device=device) wp.launch(test_function, (1,), inputs=[test_array], device=device) test.assertEqual(test_array.numpy()[0], 1.0) module_hash_0 = wp.get_module(test_function.__module__).hash_module() module_constants = wp.get_module(test_function.__module__).constants test.assertEqual(module_constants["TEST_CONSTANT"], 1.0) @wp.kernel def test_function(data: wp.array(dtype=wp.float32)): i = wp.tid() data[i] = TEST_CONSTANT TEST_CONSTANT = wp.constant(2.0) wp.launch(test_function, (1,), inputs=[test_array], device=device) test.assertEqual(test_array.numpy()[0], 2.0) module_hash_1 = wp.get_module(test_function.__module__).hash_module() module_constants = wp.get_module(test_function.__module__).constants test.assertEqual(module_constants["TEST_CONSTANT"], 2.0) test.assertNotEqual(module_hash_0, module_hash_1) def test_hash_redefine_constant_only(test, device): """This test does not define a second ``test_function``, so the second launch does not invalidate the cache. For now this is expected behavior, but we can verify that the content has is different. """ @wp.kernel def test_function(data: wp.array(dtype=wp.float32)): i = wp.tid() data[i] = TEST_CONSTANT TEST_CONSTANT = wp.constant(1.0) test_array = wp.empty(1, dtype=wp.float32, device=device) wp.launch(test_function, (1,), inputs=[test_array], device=device) test.assertEqual(test_array.numpy()[0], 1.0) module_hash_0 = wp.get_module(test_function.__module__).hash_module() module_constants = wp.get_module(test_function.__module__).constants test.assertEqual(module_constants["TEST_CONSTANT"], 1.0) TEST_CONSTANT = wp.constant(2.0) module_hash_1 = wp.get_module(test_function.__module__).hash_module(recompute_content_hash=True) module_constants = wp.get_module(test_function.__module__).constants test.assertEqual(module_constants["TEST_CONSTANT"], 2.0) test.assertNotEqual(module_hash_0, module_hash_1, "Module hashes should be different if TEST_CONSTANT is changed.") TEST_CONSTANT = wp.constant(1.0) module_hash_2 = wp.get_module(test_function.__module__).hash_module(recompute_content_hash=True) module_constants = wp.get_module(test_function.__module__).constants test.assertEqual(module_constants["TEST_CONSTANT"], 1.0) test.assertEqual(module_hash_0, module_hash_2, "Module hashes should be the same if TEST_CONSTANT is the same.") def test_hash_shadowed_var(test, device): """Tests to ensure shadowed variables are not mistakenly added to the module hash""" TEST_CONSTANT_SHADOW_0 = wp.constant(1.0) TEST_CONSTANT_SHADOW_1 = wp.constant(1.0) TEST_CONSTANT_SHADOW_2 = wp.constant(1.0) @wp.kernel def test_function(data: wp.array(dtype=wp.float32)): i = wp.tid() TEST_CONSTANT_SHADOW_0 = 2.0 TEST_CONSTANT_SHADOW_1, TEST_CONSTANT_SHADOW_2 = 4.0, 8.0 data[i] = TEST_CONSTANT_SHADOW_0 + TEST_CONSTANT_SHADOW_1 + TEST_CONSTANT_SHADOW_2 test_array = wp.empty(1, dtype=wp.float32, device=device) wp.launch(test_function, (1,), inputs=[test_array], device=device) test.assertEqual(test_array.numpy()[0], 14.0) module_hash_0 = wp.get_module(test_function.__module__).hash_module() module_constants = wp.get_module(test_function.__module__).constants test.assertFalse("TEST_CONSTANT_SHADOW_0" in module_constants, "Constant should not be in dictionary.") test.assertFalse("TEST_CONSTANT_SHADOW_1" in module_constants, "Constant should not be in dictionary.") test.assertFalse("TEST_CONSTANT_SHADOW_2" in module_constants, "Constant should not be in dictionary.") TEST_CONSTANT_SHADOW_0 = wp.constant(0.0) TEST_CONSTANT_SHADOW_1 = wp.constant(0.0) TEST_CONSTANT_SHADOW_2 = wp.constant(0.0) module_hash_1 = wp.get_module(test_function.__module__).hash_module(recompute_content_hash=True) test.assertEqual(module_hash_0, module_hash_1, "Module hashes should be the same since all constants are shadowed.") class TestConstants(unittest.TestCase): def test_constant_math(self): # test doing math with python defined constants in *python* scope twopi = wp.pi * 2.0 import math self.assertEqual(twopi, math.pi * 2.0) a = 0 x = 0.0 devices = get_test_devices() add_kernel_test(TestConstants, test_bool, dim=1, inputs=[], devices=devices) add_kernel_test(TestConstants, test_int, dim=1, inputs=[a], devices=devices) add_kernel_test(TestConstants, test_float, dim=1, inputs=[x], devices=devices) add_function_test(TestConstants, "test_closure_capture", test_closure_capture, devices=devices) add_function_test(TestConstants, "test_hash_global_capture", test_hash_global_capture, devices=devices) add_function_test(TestConstants, "test_hash_redefine_kernel", test_hash_redefine_kernel, devices=devices) add_function_test(TestConstants, "test_hash_redefine_constant_only", test_hash_redefine_constant_only, devices=devices) add_function_test(TestConstants, "test_hash_shadowed_var", test_hash_shadowed_var, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
8,147
Python
36.376147
120
0.696821
NVIDIA/warp/warp/tests/test_reload.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import importlib import os import unittest import numpy as np import warp as wp # dummy modules used for testing reload with dependencies import warp.tests.aux_test_dependent as test_dependent import warp.tests.aux_test_reference as test_reference import warp.tests.aux_test_reference_reference as test_reference_reference # dummy module used for testing reload import warp.tests.aux_test_square as test_square from warp.tests.unittest_utils import * def reload_module(module): # Clearing the .pyc file associated with a module is a necessary workaround # for `importlib.reload` to work as expected when run from within Kit. cache_file = importlib.util.cache_from_source(module.__file__) os.remove(cache_file) importlib.reload(module) def test_redefine(test, device): # -------------------------------------------- # first pass @wp.kernel def basic(x: wp.array(dtype=float)): tid = wp.tid() x[tid] = float(tid) * 1.0 n = 32 x = wp.zeros(n, dtype=float, device=device) wp.launch(kernel=basic, dim=n, inputs=[x], device=device) # -------------------------------------------- # redefine kernel, should trigger a recompile @wp.kernel def basic(x: wp.array(dtype=float)): tid = wp.tid() x[tid] = float(tid) * 2.0 y = wp.zeros(n, dtype=float, device=device) wp.launch(kernel=basic, dim=n, inputs=[y], device=device) assert_np_equal(np.arange(0, n, 1), x.numpy()) assert_np_equal(np.arange(0, n, 1) * 2.0, y.numpy()) square_two = """import warp as wp @wp.func def sqr(x: float): return x * x @wp.kernel def kern(expect: float): wp.expect_eq(sqr(2.0), expect) def run(expect, device): wp.launch(kern, dim=1, inputs=[expect], device=device) """ square_four = """import warp as wp @wp.func def multiply(x: float): return x * x @wp.kernel def kern(expect: float): wp.expect_eq(multiply(4.0), expect) def run(expect, device): wp.launch(kern, dim=1, inputs=[expect], device=device) """ def test_reload(test, device): # write out the module python and import it f = open(os.path.abspath(os.path.join(os.path.dirname(__file__), "aux_test_square.py")), "w") f.writelines(square_two) f.flush() f.close() reload_module(test_square) test_square.run(expect=4.0, device=device) # 2*2=4 f = open(os.path.abspath(os.path.join(os.path.dirname(__file__), "aux_test_square.py")), "w") f.writelines(square_four) f.flush() f.close() # reload module, this should trigger all of the funcs / kernels to be updated reload_module(test_square) test_square.run(expect=16.0, device=device) # 4*4 = 16 def test_reload_class(test, device): def test_func(): import importlib as imp import warp.tests.aux_test_class_kernel from warp.tests.aux_test_class_kernel import ClassKernelTest imp.reload(warp.tests.aux_test_class_kernel) ctest = ClassKernelTest(device) expected = np.zeros((10, 3, 3), dtype=np.float32) expected[:] = np.eye(3) assert_np_equal(expected, ctest.identities.numpy()) test_func() test_func() template_ref = """# This file is used to test reloading module references. import warp as wp import warp.tests.aux_test_reference_reference as refref @wp.func def magic(): return {} * refref.more_magic() """ template_refref = """# This file is used to test reloading module references. import warp as wp @wp.func def more_magic(): return {} """ def test_reload_references(test, device): path_ref = os.path.abspath(os.path.join(os.path.dirname(__file__), "aux_test_reference.py")) path_refref = os.path.abspath(os.path.join(os.path.dirname(__file__), "aux_test_reference_reference.py")) # rewrite both dependency modules and reload them with open(path_ref, "w") as f: f.writelines(template_ref.format(1.0)) importlib.reload(test_reference) with open(path_refref, "w") as f: f.writelines(template_refref.format(1.0)) importlib.reload(test_reference_reference) test_dependent.run(expect=1.0, device=device) # 1 * 1 = 1 # rewrite and reload the first dependency module with open(path_ref, "w") as f: f.writelines(template_ref.format(2.0)) importlib.reload(test_reference) test_dependent.run(expect=2.0, device=device) # 2 * 1 = 1 # rewrite and reload the second dependency module with open(path_refref, "w") as f: f.writelines(template_refref.format(2.0)) importlib.reload(test_reference_reference) test_dependent.run(expect=4.0, device=device) # 2 * 2 = 4 devices = get_test_devices() class TestReload(unittest.TestCase): pass add_function_test(TestReload, "test_redefine", test_redefine, devices=devices) add_function_test(TestReload, "test_reload", test_reload, devices=devices) add_function_test(TestReload, "test_reload_class", test_reload_class, devices=devices) add_function_test(TestReload, "test_reload_references", test_reload_references, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
5,617
Python
26.009615
109
0.673135
NVIDIA/warp/warp/tests/test_spatial.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * np_float_types = [np.float32, np.float64, np.float16] kernel_cache = {} def getkernel(func, suffix=""): key = func.__name__ + "_" + suffix if key not in kernel_cache: kernel_cache[key] = wp.Kernel(func=func, key=key) return kernel_cache[key] def get_select_kernel(dtype): def output_select_kernel_fn( input: wp.array(dtype=dtype), index: int, out: wp.array(dtype=dtype), ): out[0] = input[index] return getkernel(output_select_kernel_fn, suffix=dtype.__name__) ############################################################ def test_spatial_vector_constructors(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec3 = wp.types.vector(length=3, dtype=wptype) spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_vector_component_constructor( input: wp.array(dtype=wptype), out: wp.array(dtype=wptype), ): result = spatial_vector(input[0], input[1], input[2], input[3], input[4], input[5]) # multiply the output by 2 so we've got something to backpropagate: out[0] = wptype(2) * result[0] out[1] = wptype(2) * result[1] out[2] = wptype(2) * result[2] out[3] = wptype(2) * result[3] out[4] = wptype(2) * result[4] out[5] = wptype(2) * result[5] def check_spatial_vector_vector_constructor( input: wp.array(dtype=wptype), out: wp.array(dtype=wptype), ): result = spatial_vector(vec3(input[0], input[1], input[2]), vec3(input[3], input[4], input[5])) # multiply the output by 2 so we've got something to backpropagate: out[0] = wptype(2) * result[0] out[1] = wptype(2) * result[1] out[2] = wptype(2) * result[2] out[3] = wptype(2) * result[3] out[4] = wptype(2) * result[4] out[5] = wptype(2) * result[5] kernel = getkernel(check_spatial_vector_component_constructor, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) vec_kernel = getkernel(check_spatial_vector_vector_constructor, suffix=dtype.__name__) if register_kernels: return input = wp.array(rng.standard_normal(size=6).astype(dtype), requires_grad=True, device=device) output = wp.zeros_like(input) wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol) for i in range(len(input)): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(len(input)) expectedgrads[i] = 2 assert_np_equal(tape.gradients[input].numpy(), expectedgrads) tape.zero() input = wp.array(rng.standard_normal(size=6).astype(dtype), requires_grad=True, device=device) output = wp.zeros_like(input) wp.launch(vec_kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol) for i in range(len(input)): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(len(input)) expectedgrads[i] = 2 assert_np_equal(tape.gradients[input].numpy(), expectedgrads) tape.zero() def test_spatial_vector_indexing(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_vector_indexing( input: wp.array(dtype=spatial_vector), out: wp.array(dtype=wptype), ): inpt = input[0] # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): out[idx] = wptype(2) * inpt[i] idx = idx + 1 kernel = getkernel(check_spatial_vector_indexing, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return input = wp.array( rng.standard_normal(size=(1, 6)).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device ) outcmps = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device) assert_np_equal(outcmps.numpy(), 2 * input.numpy().ravel(), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outcmps, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(6, dtype=dtype) expectedresult[i] = 2 assert_np_equal(tape.gradients[input].numpy()[0], expectedresult) tape.zero() def test_spatial_vector_scalar_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_vector_scalar_mul( s: wp.array(dtype=wptype), q: wp.array(dtype=spatial_vector), outcmps_l: wp.array(dtype=wptype), outcmps_r: wp.array(dtype=wptype), ): lresult = s[0] * q[0] rresult = q[0] * s[0] # multiply outputs by 2 so we've got something to backpropagate: for i in range(6): outcmps_l[i] = wptype(2) * lresult[i] outcmps_r[i] = wptype(2) * rresult[i] kernel = getkernel(check_spatial_vector_scalar_mul, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return s = wp.array(rng.standard_normal(size=1).astype(dtype), requires_grad=True, device=device) q = wp.array( rng.standard_normal(size=(1, 6)).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device ) outcmps_l = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) outcmps_r = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[s, q], outputs=[ outcmps_l, outcmps_r, ], device=device, ) assert_np_equal(outcmps_l.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol) assert_np_equal(outcmps_r.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): # test left/right mul gradients: for wrt in [outcmps_l, outcmps_r]: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[s, q], outputs=[outcmps_l, outcmps_r], device=device) wp.launch(output_select_kernel, dim=1, inputs=[wrt, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(6, dtype=dtype) expectedresult[i] = 2 * s.numpy()[0] assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[s].numpy()[0], 2 * q.numpy()[0, i], tol=tol) tape.zero() def test_spatial_vector_add_sub(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_vector_add_sub( q: wp.array(dtype=spatial_vector), v: wp.array(dtype=spatial_vector), outputs_add: wp.array(dtype=wptype), outputs_sub: wp.array(dtype=wptype), ): addresult = q[0] + v[0] subresult = q[0] - v[0] for i in range(6): outputs_add[i] = wptype(2) * addresult[i] outputs_sub[i] = wptype(2) * subresult[i] kernel = getkernel(check_spatial_vector_add_sub, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return q = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) v = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) outputs_add = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) outputs_sub = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ q, v, ], outputs=[outputs_add, outputs_sub], device=device, ) assert_np_equal(outputs_add.numpy(), 2 * (q.numpy() + v.numpy()), tol=tol) assert_np_equal(outputs_sub.numpy(), 2 * (q.numpy() - v.numpy()), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): # test add gradients: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_add, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(6, dtype=dtype) expectedresult[i] = 2 assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=tol) tape.zero() # test subtraction gradients: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_sub, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(6, dtype=dtype) expectedresult[i] = 2 assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[v].numpy()[0], -expectedresult, tol=tol) tape.zero() def test_spatial_dot(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_dot( s: wp.array(dtype=spatial_vector), v: wp.array(dtype=spatial_vector), dot: wp.array(dtype=wptype), ): dot[0] = wptype(2) * wp.spatial_dot(v[0], s[0]) kernel = getkernel(check_spatial_dot, suffix=dtype.__name__) if register_kernels: return s = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) v = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) dot = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, v, ], outputs=[dot], device=device, ) assert_np_equal(dot.numpy()[0], 2.0 * (v.numpy() * s.numpy()).sum(), tol=tol) tape.backward(loss=dot) sgrads = tape.gradients[s].numpy()[0] expected_grads = 2.0 * v.numpy()[0] assert_np_equal(sgrads, expected_grads, tol=10 * tol) vgrads = tape.gradients[v].numpy()[0] expected_grads = 2.0 * s.numpy()[0] assert_np_equal(vgrads, expected_grads, tol=tol) def test_spatial_cross(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_cross( s: wp.array(dtype=spatial_vector), v: wp.array(dtype=spatial_vector), outputs: wp.array(dtype=wptype), outputs_dual: wp.array(dtype=wptype), outputs_wcrossw: wp.array(dtype=wptype), outputs_vcrossw: wp.array(dtype=wptype), outputs_wcrossv: wp.array(dtype=wptype), outputs_vcrossv: wp.array(dtype=wptype), ): c = wp.spatial_cross(s[0], v[0]) d = wp.spatial_cross_dual(s[0], v[0]) # multiply outputs by 2 so we've got something to backpropagate: for i in range(6): outputs[i] = wptype(2) * c[i] outputs_dual[i] = wptype(2) * d[i] sw = wp.spatial_top(s[0]) sv = wp.spatial_bottom(s[0]) vw = wp.spatial_top(v[0]) vv = wp.spatial_bottom(v[0]) wcrossw = wp.cross(sw, vw) vcrossw = wp.cross(sv, vw) wcrossv = wp.cross(sw, vv) vcrossv = wp.cross(sv, vv) for i in range(3): outputs_wcrossw[i] = wcrossw[i] outputs_vcrossw[i] = vcrossw[i] outputs_wcrossv[i] = wcrossv[i] outputs_vcrossv[i] = vcrossv[i] kernel = getkernel(check_spatial_cross, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return s = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) v = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) outputs = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) outputs_dual = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) outputs_wcrossw = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) outputs_vcrossw = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) outputs_wcrossv = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) outputs_vcrossv = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ s, v, ], outputs=[outputs, outputs_dual, outputs_wcrossw, outputs_vcrossw, outputs_wcrossv, outputs_vcrossv], device=device, ) sw = s.numpy()[0, :3] sv = s.numpy()[0, 3:] vw = v.numpy()[0, :3] vv = v.numpy()[0, 3:] wcrossw = np.cross(sw, vw) vcrossw = np.cross(sv, vw) wcrossv = np.cross(sw, vv) vcrossv = np.cross(sv, vv) assert_np_equal(outputs.numpy()[:3], 2 * wcrossw, tol=tol) assert_np_equal(outputs.numpy()[3:], 2 * (vcrossw + wcrossv), tol=tol) assert_np_equal(outputs_dual.numpy()[:3], 2 * (wcrossw + vcrossv), tol=tol) assert_np_equal(outputs_dual.numpy()[3:], 2 * wcrossv, tol=tol) for i in range(3): cmp_w = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_v = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_w_dual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_v_dual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_wcrossw = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_vcrossw = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_wcrossv = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_vcrossv = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, v, ], outputs=[outputs, outputs_dual, outputs_wcrossw, outputs_vcrossw, outputs_wcrossv, outputs_vcrossv], device=device, ) # ith w and v vector components of spatial_cross: wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp_w], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i + 3], outputs=[cmp_v], device=device) # ith w and v vector components of spatial_cross_dual: wp.launch(output_select_kernel, dim=1, inputs=[outputs_dual, i], outputs=[cmp_w_dual], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_dual, i + 3], outputs=[cmp_v_dual], device=device) # ith vector components of some cross products: wp.launch(output_select_kernel, dim=1, inputs=[outputs_wcrossw, i], outputs=[cmp_wcrossw], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_vcrossw, i], outputs=[cmp_vcrossw], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_wcrossv, i], outputs=[cmp_wcrossv], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_vcrossv, i], outputs=[cmp_vcrossv], device=device) def getgrads(cmp, tape=tape): tape.backward(loss=cmp) sgrads = 1.0 * tape.gradients[s].numpy() vgrads = 1.0 * tape.gradients[v].numpy() tape.zero() return sgrads, vgrads dcmp_w_ds, dcmp_w_dv = getgrads(cmp_w) dcmp_v_ds, dcmp_v_dv = getgrads(cmp_v) dcmp_w_dual_ds, dcmp_w_dual_dv = getgrads(cmp_w_dual) dcmp_v_dual_ds, dcmp_v_dual_dv = getgrads(cmp_v_dual) dcmp_wcrossw_ds, dcmp_wcrossw_dv = getgrads(cmp_wcrossw) dcmp_vcrossw_ds, dcmp_vcrossw_dv = getgrads(cmp_vcrossw) dcmp_wcrossv_ds, dcmp_wcrossv_dv = getgrads(cmp_wcrossv) dcmp_vcrossv_ds, dcmp_vcrossv_dv = getgrads(cmp_vcrossv) assert_np_equal(dcmp_w_ds, 2 * dcmp_wcrossw_ds, tol=tol) assert_np_equal(dcmp_w_dv, 2 * dcmp_wcrossw_dv, tol=tol) assert_np_equal(dcmp_v_ds, 2 * (dcmp_vcrossw_ds + dcmp_wcrossv_ds), tol=tol) assert_np_equal(dcmp_v_dv, 2 * (dcmp_vcrossw_dv + dcmp_wcrossv_dv), tol=tol) assert_np_equal(dcmp_w_dual_ds, 2 * (dcmp_wcrossw_ds + dcmp_vcrossv_ds), tol=tol) assert_np_equal(dcmp_w_dual_dv, 2 * (dcmp_wcrossw_dv + dcmp_vcrossv_dv), tol=tol) assert_np_equal(dcmp_v_dual_ds, 2 * dcmp_wcrossv_ds, tol=tol) assert_np_equal(dcmp_v_dual_dv, 2 * dcmp_wcrossv_dv, tol=tol) def test_spatial_top_bottom(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) def check_spatial_top_bottom( s: wp.array(dtype=spatial_vector), outputs: wp.array(dtype=wptype), ): top = wp.spatial_top(s[0]) bottom = wp.spatial_bottom(s[0]) outputs[0] = wptype(2) * top[0] outputs[1] = wptype(2) * top[1] outputs[2] = wptype(2) * top[2] outputs[3] = wptype(2) * bottom[0] outputs[4] = wptype(2) * bottom[1] outputs[5] = wptype(2) * bottom[2] kernel = getkernel(check_spatial_top_bottom, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return s = wp.array(rng.standard_normal(size=6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device) outputs = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ s, ], outputs=[outputs], device=device, ) assert_np_equal(outputs.numpy(), 2.0 * s.numpy(), tol=tol) for i in range(6): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, ], outputs=[outputs], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(6) expectedgrads[i] = 2 assert_np_equal(tape.gradients[s].numpy(), expectedgrads.reshape((1, 6))) tape.zero() def test_transform_constructors(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec3 = wp.types.vector(length=3, dtype=wptype) transform = wp.types.transformation(dtype=wptype) quat = wp.types.quaternion(dtype=wptype) def check_transform_constructor( input: wp.array(dtype=wptype), out: wp.array(dtype=wptype), ): result = transform(vec3(input[0], input[1], input[2]), quat(input[3], input[4], input[5], input[6])) # multiply the output by 2 so we've got something to backpropagate: out[0] = wptype(2) * result[0] out[1] = wptype(2) * result[1] out[2] = wptype(2) * result[2] out[3] = wptype(2) * result[3] out[4] = wptype(2) * result[4] out[5] = wptype(2) * result[5] out[6] = wptype(2) * result[6] kernel = getkernel(check_transform_constructor, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return p = rng.standard_normal(size=3).astype(dtype) q = rng.standard_normal(size=4).astype(dtype) q /= np.linalg.norm(q) input = wp.array(np.concatenate((p, q)), requires_grad=True, device=device) output = wp.zeros_like(input) wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol) for i in range(len(input)): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(len(input)) expectedgrads[i] = 2 assert_np_equal(tape.gradients[input].numpy(), expectedgrads) tape.zero() def test_transform_indexing(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) def check_transform_indexing( input: wp.array(dtype=transform), out: wp.array(dtype=wptype), ): inpt = input[0] # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(7): out[idx] = wptype(2) * inpt[i] idx = idx + 1 kernel = getkernel(check_transform_indexing, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return input = wp.array(rng.standard_normal(size=(1, 7)).astype(dtype), dtype=transform, requires_grad=True, device=device) outcmps = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device) assert_np_equal(outcmps.numpy(), 2 * input.numpy().ravel(), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(7): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outcmps, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(7, dtype=dtype) expectedresult[i] = 2 assert_np_equal(tape.gradients[input].numpy()[0], expectedresult) tape.zero() def test_transform_scalar_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) def check_transform_scalar_mul( s: wp.array(dtype=wptype), q: wp.array(dtype=transform), outcmps_l: wp.array(dtype=wptype), outcmps_r: wp.array(dtype=wptype), ): lresult = s[0] * q[0] rresult = q[0] * s[0] # multiply outputs by 2 so we've got something to backpropagate: for i in range(7): outcmps_l[i] = wptype(2) * lresult[i] outcmps_r[i] = wptype(2) * rresult[i] kernel = getkernel(check_transform_scalar_mul, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return s = wp.array(rng.standard_normal(size=1).astype(dtype), requires_grad=True, device=device) q = wp.array(rng.standard_normal(size=(1, 7)).astype(dtype), dtype=transform, requires_grad=True, device=device) outcmps_l = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) outcmps_r = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[s, q], outputs=[ outcmps_l, outcmps_r, ], device=device, ) assert_np_equal(outcmps_l.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol) assert_np_equal(outcmps_r.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(7): # test left/right mul gradients: for wrt in [outcmps_l, outcmps_r]: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[s, q], outputs=[outcmps_l, outcmps_r], device=device) wp.launch(output_select_kernel, dim=1, inputs=[wrt, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(7, dtype=dtype) expectedresult[i] = 2 * s.numpy()[0] assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[s].numpy()[0], 2 * q.numpy()[0, i], tol=tol) tape.zero() def test_transform_add_sub(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) def check_transform_add_sub( q: wp.array(dtype=transform), v: wp.array(dtype=transform), outputs_add: wp.array(dtype=wptype), outputs_sub: wp.array(dtype=wptype), ): addresult = q[0] + v[0] subresult = q[0] - v[0] for i in range(7): outputs_add[i] = wptype(2) * addresult[i] outputs_sub[i] = wptype(2) * subresult[i] kernel = getkernel(check_transform_add_sub, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return q = wp.array(rng.standard_normal(size=7).astype(dtype), dtype=transform, requires_grad=True, device=device) v = wp.array(rng.standard_normal(size=7).astype(dtype), dtype=transform, requires_grad=True, device=device) outputs_add = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) outputs_sub = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ q, v, ], outputs=[outputs_add, outputs_sub], device=device, ) assert_np_equal(outputs_add.numpy(), 2 * (q.numpy() + v.numpy()), tol=tol) assert_np_equal(outputs_sub.numpy(), 2 * (q.numpy() - v.numpy()), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(7): # test add gradients: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_add, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(7, dtype=dtype) expectedresult[i] = 2 assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=tol) tape.zero() # test subtraction gradients: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_sub, i], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros(7, dtype=dtype) expectedresult[i] = 2 assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[v].numpy()[0], -expectedresult, tol=tol) tape.zero() def test_transform_get_trans_rot(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) def check_transform_get_trans_rot( s: wp.array(dtype=transform), outputs: wp.array(dtype=wptype), ): trans = wp.transform_get_translation(s[0]) q = wp.transform_get_rotation(s[0]) outputs[0] = wptype(2) * trans[0] outputs[1] = wptype(2) * trans[1] outputs[2] = wptype(2) * trans[2] outputs[3] = wptype(2) * q[0] outputs[4] = wptype(2) * q[1] outputs[5] = wptype(2) * q[2] outputs[6] = wptype(2) * q[3] kernel = getkernel(check_transform_get_trans_rot, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return s = wp.array(rng.standard_normal(size=7).astype(dtype), dtype=transform, requires_grad=True, device=device) outputs = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ s, ], outputs=[outputs], device=device, ) assert_np_equal(outputs.numpy(), 2.0 * s.numpy(), tol=tol) for i in range(7): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, ], outputs=[outputs], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(7) expectedgrads[i] = 2 assert_np_equal(tape.gradients[s].numpy(), expectedgrads.reshape((1, 7))) tape.zero() def test_transform_multiply(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) def check_transform_multiply( a: wp.array(dtype=transform), b: wp.array(dtype=transform), outputs: wp.array(dtype=wptype), outputs_fn: wp.array(dtype=wptype), outputs_manual: wp.array(dtype=wptype), ): result = a[0] * b[0] result_fn = wp.transform_multiply(a[0], b[0]) # let's just work out the transform multiplication manually # and compare value/gradients with that: atrans = wp.transform_get_translation(a[0]) arot = wp.transform_get_rotation(a[0]) btrans = wp.transform_get_translation(b[0]) brot = wp.transform_get_rotation(b[0]) trans = wp.quat_rotate(arot, btrans) + atrans rot = arot * brot result_manual = transform(trans, rot) for i in range(7): outputs[i] = wptype(2) * result[i] outputs_fn[i] = wptype(2) * result_fn[i] outputs_manual[i] = wptype(2) * result_manual[i] kernel = getkernel(check_transform_multiply, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return q = rng.standard_normal(size=7) s = rng.standard_normal(size=7) q[3:] /= np.linalg.norm(q[3:]) s[3:] /= np.linalg.norm(s[3:]) q = wp.array(q.astype(dtype), dtype=transform, requires_grad=True, device=device) s = wp.array(s.astype(dtype), dtype=transform, requires_grad=True, device=device) outputs = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) outputs_fn = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) outputs_manual = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ q, s, ], outputs=[outputs, outputs_fn, outputs_manual], device=device, ) assert_np_equal(outputs.numpy(), outputs_fn.numpy(), tol=tol) assert_np_equal(outputs.numpy(), outputs_manual.numpy(), tol=tol) for i in range(7): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_fn = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ q, s, ], outputs=[outputs, outputs_fn, outputs_manual], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_fn, i], outputs=[cmp_fn], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_manual, i], outputs=[cmp_manual], device=device) tape.backward(loss=cmp) qgrads = 1.0 * tape.gradients[q].numpy() sgrads = 1.0 * tape.gradients[s].numpy() tape.zero() tape.backward(loss=cmp_fn) qgrads_fn = 1.0 * tape.gradients[q].numpy() sgrads_fn = 1.0 * tape.gradients[s].numpy() tape.zero() tape.backward(loss=cmp_manual) qgrads_manual = 1.0 * tape.gradients[q].numpy() sgrads_manual = 1.0 * tape.gradients[s].numpy() tape.zero() assert_np_equal(qgrads, qgrads_fn, tol=tol) assert_np_equal(sgrads, sgrads_fn, tol=tol) assert_np_equal(qgrads, qgrads_manual, tol=tol) assert_np_equal(sgrads, sgrads_manual, tol=tol) def test_transform_inverse(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) def check_transform_inverse( a: wp.array(dtype=transform), outputs: wp.array(dtype=wptype), outputs_shouldbeidentity: wp.array(dtype=wptype), outputs_manual: wp.array(dtype=wptype), ): result = wp.transform_inverse(a[0]) idt = result * a[0] # let's just work out the transform inverse manually # and compare value/gradients with that: atrans = wp.transform_get_translation(a[0]) arot = wp.transform_get_rotation(a[0]) rotinv = wp.quat_inverse(arot) result_manual = transform(-wp.quat_rotate(rotinv, atrans), rotinv) for i in range(7): outputs[i] = wptype(2) * result[i] outputs_shouldbeidentity[i] = wptype(2) * idt[i] outputs_manual[i] = wptype(2) * result_manual[i] kernel = getkernel(check_transform_inverse, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return q = rng.standard_normal(size=7) s = rng.standard_normal(size=7) q[3:] /= np.linalg.norm(q[3:]) s[3:] /= np.linalg.norm(s[3:]) q = wp.array(q.astype(dtype), dtype=transform, requires_grad=True, device=device) outputs = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) outputs_shouldbeidentity = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) outputs_manual = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ q, ], outputs=[outputs, outputs_shouldbeidentity, outputs_manual], device=device, ) # check inverse: assert_np_equal(outputs_shouldbeidentity.numpy(), np.array([0, 0, 0, 0, 0, 0, 2]), tol=tol) # same as manual result: assert_np_equal(outputs.numpy(), outputs_manual.numpy(), tol=tol) for i in range(7): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ q, ], outputs=[outputs, outputs_shouldbeidentity, outputs_manual], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_manual, i], outputs=[cmp_manual], device=device) tape.backward(loss=cmp) qgrads = 1.0 * tape.gradients[q].numpy() tape.zero() tape.backward(loss=cmp_manual) qgrads_manual = 1.0 * tape.gradients[q].numpy() tape.zero() # check gradients against manual result: assert_np_equal(qgrads, qgrads_manual, tol=tol) def test_transform_point_vector(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] transform = wp.types.transformation(dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) def check_transform_point_vector( t: wp.array(dtype=transform), v: wp.array(dtype=vec3), outputs_pt: wp.array(dtype=wptype), outputs_pt_manual: wp.array(dtype=wptype), outputs_vec: wp.array(dtype=wptype), outputs_vec_manual: wp.array(dtype=wptype), ): result_pt = wp.transform_point(t[0], v[0]) result_pt_manual = wp.transform_get_translation(t[0]) + wp.quat_rotate(wp.transform_get_rotation(t[0]), v[0]) result_vec = wp.transform_vector(t[0], v[0]) result_vec_manual = wp.quat_rotate(wp.transform_get_rotation(t[0]), v[0]) for i in range(3): outputs_pt[i] = wptype(2) * result_pt[i] outputs_pt_manual[i] = wptype(2) * result_pt_manual[i] outputs_vec[i] = wptype(2) * result_vec[i] outputs_vec_manual[i] = wptype(2) * result_vec_manual[i] kernel = getkernel(check_transform_point_vector, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return q = rng.standard_normal(size=7) q[3:] /= np.linalg.norm(q[3:]) t = wp.array(q.astype(dtype), dtype=transform, requires_grad=True, device=device) v = wp.array(rng.standard_normal(size=3), dtype=vec3, requires_grad=True, device=device) outputs_pt = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) outputs_pt_manual = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) outputs_vec = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) outputs_vec_manual = wp.zeros(3, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[t, v], outputs=[outputs_pt, outputs_pt_manual, outputs_vec, outputs_vec_manual], device=device, ) # same as manual results: assert_np_equal(outputs_pt.numpy(), outputs_pt_manual.numpy(), tol=tol) assert_np_equal(outputs_vec.numpy(), outputs_vec_manual.numpy(), tol=tol) for i in range(3): cmp_pt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_pt_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_vec = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) cmp_vec_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[t, v], outputs=[outputs_pt, outputs_pt_manual, outputs_vec, outputs_vec_manual], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outputs_pt, i], outputs=[cmp_pt], device=device) wp.launch( output_select_kernel, dim=1, inputs=[outputs_pt_manual, i], outputs=[cmp_pt_manual], device=device ) wp.launch(output_select_kernel, dim=1, inputs=[outputs_vec, i], outputs=[cmp_vec], device=device) wp.launch( output_select_kernel, dim=1, inputs=[outputs_vec_manual, i], outputs=[cmp_vec_manual], device=device ) tape.backward(loss=cmp_pt) tgrads_pt = 1.0 * tape.gradients[t].numpy() vgrads_pt = 1.0 * tape.gradients[v].numpy() tape.zero() tape.backward(loss=cmp_pt_manual) tgrads_pt_manual = 1.0 * tape.gradients[t].numpy() vgrads_pt_manual = 1.0 * tape.gradients[v].numpy() tape.zero() tape.backward(loss=cmp_vec) tgrads_vec = 1.0 * tape.gradients[t].numpy() vgrads_vec = 1.0 * tape.gradients[v].numpy() tape.zero() tape.backward(loss=cmp_vec_manual) tgrads_vec_manual = 1.0 * tape.gradients[t].numpy() vgrads_vec_manual = 1.0 * tape.gradients[v].numpy() tape.zero() # check gradients against manual result: assert_np_equal(tgrads_pt, tgrads_pt_manual, tol=tol) assert_np_equal(vgrads_pt, vgrads_pt_manual, tol=tol) assert_np_equal(tgrads_vec, tgrads_vec_manual, tol=tol) assert_np_equal(vgrads_vec, vgrads_vec_manual, tol=tol) def test_spatial_matrix_constructors(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) def check_spatial_matrix_constructor( input: wp.array(dtype=wptype), out: wp.array(dtype=wptype), ): # multiply the output by 2 so we've got something to backpropagate: result0 = spatial_matrix( input[0], input[1], input[2], input[3], input[4], input[5], input[6], input[7], input[8], input[9], input[10], input[11], input[12], input[13], input[14], input[15], input[16], input[17], input[18], input[19], input[20], input[21], input[22], input[23], input[24], input[25], input[26], input[27], input[28], input[29], input[30], input[31], input[32], input[33], input[34], input[35], ) result1 = spatial_matrix() idx = 0 for i in range(6): for j in range(6): out[idx] = wptype(2) * result0[i, j] idx = idx + 1 for i in range(6): for j in range(6): out[idx] = result1[i, j] idx = idx + 1 kernel = getkernel(check_spatial_matrix_constructor, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return input = wp.array(rng.standard_normal(size=6 * 6).astype(dtype), requires_grad=True, device=device) output = wp.zeros(2 * 6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy()[: 6 * 6], 2 * input.numpy(), tol=tol) assert_np_equal(output.numpy()[6 * 6 :], np.zeros_like(input.numpy()), tol=tol) for i in range(len(input)): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(len(input)) expectedgrads[i] = 2 assert_np_equal(tape.gradients[input].numpy(), expectedgrads) tape.zero() break def test_spatial_matrix_indexing(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) def check_spatial_matrix_indexing( input: wp.array(dtype=spatial_matrix), out: wp.array(dtype=wptype), ): inpt = input[0] # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): for j in range(6): out[idx] = wptype(2) * inpt[i, j] idx = idx + 1 kernel = getkernel(check_spatial_matrix_indexing, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return input = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) outcmps = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device) assert_np_equal(outcmps.numpy(), 2 * input.numpy().ravel(), tol=tol) idx = 0 out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): for j in range(6): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outcmps, idx], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros((6, 6), dtype=dtype) expectedresult[i, j] = 2 assert_np_equal(tape.gradients[input].numpy()[0], expectedresult) tape.zero() idx = idx + 1 def test_spatial_matrix_scalar_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) def check_spatial_matrix_scalar_mul( s: wp.array(dtype=wptype), q: wp.array(dtype=spatial_matrix), outcmps_l: wp.array(dtype=wptype), outcmps_r: wp.array(dtype=wptype), ): lresult = s[0] * q[0] rresult = q[0] * s[0] # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): for j in range(6): outcmps_l[idx] = wptype(2) * lresult[i, j] outcmps_r[idx] = wptype(2) * rresult[i, j] idx = idx + 1 kernel = getkernel(check_spatial_matrix_scalar_mul, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return s = wp.array(rng.standard_normal(size=1).astype(dtype), requires_grad=True, device=device) q = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) outcmps_l = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) outcmps_r = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[s, q], outputs=[ outcmps_l, outcmps_r, ], device=device, ) assert_np_equal(outcmps_l.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol) assert_np_equal(outcmps_r.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) idx = 0 for i in range(6): for j in range(6): # test left/right mul gradients: for wrt in [outcmps_l, outcmps_r]: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[s, q], outputs=[outcmps_l, outcmps_r], device=device) wp.launch(output_select_kernel, dim=1, inputs=[wrt, idx], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros((6, 6), dtype=dtype) expectedresult[i, j] = 2 * s.numpy()[0] assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[s].numpy()[0], 2 * q.numpy()[0, i, j], tol=tol) tape.zero() idx = idx + 1 def test_spatial_matrix_add_sub(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) def check_spatial_matrix_add_sub( q: wp.array(dtype=spatial_matrix), v: wp.array(dtype=spatial_matrix), outputs_add: wp.array(dtype=wptype), outputs_sub: wp.array(dtype=wptype), ): addresult = q[0] + v[0] subresult = q[0] - v[0] idx = 0 for i in range(6): for j in range(6): outputs_add[idx] = wptype(2) * addresult[i, j] outputs_sub[idx] = wptype(2) * subresult[i, j] idx = idx + 1 kernel = getkernel(check_spatial_matrix_add_sub, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return q = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) v = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) outputs_add = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) outputs_sub = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ q, v, ], outputs=[outputs_add, outputs_sub], device=device, ) assert_np_equal(outputs_add.numpy(), 2 * (q.numpy() + v.numpy()), tol=tol) assert_np_equal(outputs_sub.numpy(), 2 * (q.numpy() - v.numpy()), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) idx = 0 for i in range(6): for j in range(6): # test add gradients: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_add, idx], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros((6, 6), dtype=dtype) expectedresult[i, j] = 2 assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=tol) tape.zero() # test subtraction gradients: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs_sub, idx], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros((6, 6), dtype=dtype) expectedresult[i, j] = 2 assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol) assert_np_equal(tape.gradients[v].numpy()[0], -expectedresult, tol=tol) tape.zero() idx = idx + 1 def test_spatial_matvec_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 2.0e-2, np.float32: 5.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) spatial_vector = wp.types.vector(length=6, dtype=wptype) output_select_kernel = get_select_kernel(wptype) def check_spatial_mat_vec_mul( v: wp.array(dtype=spatial_vector), m: wp.array(dtype=spatial_matrix), outcomponents: wp.array(dtype=wptype), ): result = m[0] * v[0] # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): outcomponents[idx] = wptype(2) * result[i] idx = idx + 1 kernel = getkernel(check_spatial_mat_vec_mul, suffix=dtype.__name__) if register_kernels: return v = wp.array( rng.standard_normal(size=(1, 6)).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device ) m = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) outcomponents = wp.zeros(6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device) assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m.numpy()[0], v.numpy()[0]), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, i], outputs=[out], device=device) tape.backward(loss=out) assert_np_equal(tape.gradients[v].numpy()[0], 2 * m.numpy()[0, i, :], tol=tol) expectedresult = np.zeros((6, 6), dtype=dtype) expectedresult[i, :] = 2 * v.numpy()[0] assert_np_equal(tape.gradients[m].numpy()[0], expectedresult, tol=tol) tape.zero() def test_spatial_matmat_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 2.0e-2, np.float32: 5.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) output_select_kernel = get_select_kernel(wptype) def check_mat_mat_mul( v: wp.array(dtype=spatial_matrix), m: wp.array(dtype=spatial_matrix), outcomponents: wp.array(dtype=wptype), ): result = m[0] * v[0] # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): for j in range(6): outcomponents[idx] = wptype(2) * result[i, j] idx = idx + 1 kernel = getkernel(check_mat_mat_mul, suffix=dtype.__name__) if register_kernels: return v = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) m = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device) assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m.numpy()[0], v.numpy()[0]), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) idx = 0 for i in range(6): for j in range(6): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros((6, 6), dtype=dtype) expected[:, j] = 2 * m.numpy()[0, i, :] assert_np_equal(tape.gradients[v].numpy()[0], expected, tol=10 * tol) expected = np.zeros((6, 6), dtype=dtype) expected[i, :] = 2 * v.numpy()[0, :, j] assert_np_equal(tape.gradients[m].numpy()[0], expected, tol=10 * tol) tape.zero() idx = idx + 1 def test_spatial_mat_transpose(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype) output_select_kernel = get_select_kernel(wptype) def check_spatial_mat_transpose( m: wp.array(dtype=spatial_matrix), outcomponents: wp.array(dtype=wptype), ): # multiply outputs by 2 so we've got something to backpropagate: mat = wptype(2) * wp.transpose(m[0]) idx = 0 for i in range(6): for j in range(6): outcomponents[idx] = mat[i, j] idx = idx + 1 kernel = getkernel(check_spatial_mat_transpose, suffix=dtype.__name__) if register_kernels: return m = wp.array( rng.standard_normal(size=(1, 6, 6)).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device ) outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[m], outputs=[outcomponents], device=device) assert_np_equal(outcomponents.numpy(), 2 * m.numpy()[0].T, tol=tol) idx = 0 out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): for j in range(6): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[m], outputs=[outcomponents], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device) tape.backward(loss=out) expectedresult = np.zeros((6, 6), dtype=dtype) expectedresult[j, i] = 2 assert_np_equal(tape.gradients[m].numpy()[0], expectedresult) tape.zero() idx = idx + 1 def test_spatial_outer_product(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] spatial_vector = wp.types.vector(length=6, dtype=wptype) output_select_kernel = get_select_kernel(wptype) def check_spatial_outer_product( s: wp.array(dtype=spatial_vector), v: wp.array(dtype=spatial_vector), outcomponents: wp.array(dtype=wptype), ): mresult = wptype(2) * wp.outer(s[0], v[0]) # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): for j in range(6): outcomponents[idx] = mresult[i, j] idx = idx + 1 kernel = getkernel(check_spatial_outer_product, suffix=dtype.__name__) if register_kernels: return s = wp.array( rng.standard_normal(size=(1, 6)).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device ) v = wp.array( rng.standard_normal(size=(1, 6)).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device ) outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[s, v], outputs=[outcomponents], device=device) assert_np_equal(outcomponents.numpy(), 2 * s.numpy()[0, :, None] * v.numpy()[0, None, :], tol=tol) idx = 0 out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): for j in range(6): tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, v, ], outputs=[outcomponents], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device) tape.backward(loss=out) # this component's gonna be s_i * v_j, so its s gradient is gonna be nozero # at the ith component and its v gradient will be nonzero at the jth component: expectedresult = np.zeros((6), dtype=dtype) expectedresult[i] = 2 * v.numpy()[0, j] assert_np_equal(tape.gradients[s].numpy()[0], expectedresult, tol=10 * tol) expectedresult = np.zeros((6), dtype=dtype) expectedresult[j] = 2 * s.numpy()[0, i] assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=10 * tol) tape.zero() idx = idx + 1 def test_spatial_adjoint(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] mat3 = wp.types.matrix(shape=(3, 3), dtype=wptype) output_select_kernel = get_select_kernel(wptype) def check_spatial_adjoint( R: wp.array(dtype=mat3), S: wp.array(dtype=mat3), outcomponents: wp.array(dtype=wptype), ): mresult = wptype(2) * wp.spatial_adjoint(R[0], S[0]) # multiply outputs by 2 so we've got something to backpropagate: idx = 0 for i in range(6): for j in range(6): outcomponents[idx] = mresult[i, j] idx = idx + 1 kernel = getkernel(check_spatial_adjoint, suffix=dtype.__name__) if register_kernels: return R = wp.array(rng.standard_normal(size=(1, 3, 3)).astype(dtype), dtype=mat3, requires_grad=True, device=device) S = wp.array(rng.standard_normal(size=(1, 3, 3)).astype(dtype), dtype=mat3, requires_grad=True, device=device) outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device) wp.launch(kernel, dim=1, inputs=[R, S], outputs=[outcomponents], device=device) result = outcomponents.numpy().reshape(6, 6) expected = np.zeros_like(result) expected[:3, :3] = R.numpy() expected[3:, 3:] = R.numpy() expected[3:, :3] = S.numpy() assert_np_equal(result, 2 * expected, tol=tol) idx = 0 out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(6): for j in range(6): tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ R, S, ], outputs=[outcomponents], device=device, ) wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device) tape.backward(loss=out) # this component's gonna be s_i * v_j, so its s gradient is gonna be nozero # at the ith component and its v gradient will be nonzero at the jth component: expectedresult = np.zeros((3, 3), dtype=dtype) if (i // 3 == 0 and j // 3 == 0) or (i // 3 == 1 and j // 3 == 1): expectedresult[i % 3, j % 3] = 2 assert_np_equal(tape.gradients[R].numpy()[0], expectedresult, tol=10 * tol) expectedresult = np.zeros((3, 3), dtype=dtype) if i // 3 == 1 and j // 3 == 0: expectedresult[i % 3, j % 3] = 2 assert_np_equal(tape.gradients[S].numpy()[0], expectedresult, tol=10 * tol) tape.zero() idx = idx + 1 def test_transform_identity(test, device, dtype, register_kernels=False): wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def transform_identity_test(output: wp.array(dtype=wptype)): t = wp.transform_identity(dtype=wptype) for i in range(7): output[i] = t[i] def transform_identity_test_default(output: wp.array(dtype=wp.float32)): t = wp.transform_identity() for i in range(7): output[i] = t[i] quat_identity_kernel = getkernel(transform_identity_test, suffix=dtype.__name__) quat_identity_default_kernel = getkernel(transform_identity_test_default, suffix=np.float32.__name__) if register_kernels: return output = wp.zeros(7, dtype=wptype, device=device) wp.launch(quat_identity_kernel, dim=1, inputs=[], outputs=[output], device=device) expected = np.zeros_like(output.numpy()) expected[-1] = 1 assert_np_equal(output.numpy(), expected) # let's just test that it defaults to float32: output = wp.zeros(7, dtype=wp.float32, device=device) wp.launch(quat_identity_default_kernel, dim=1, inputs=[], outputs=[output], device=device) expected = np.zeros_like(output.numpy()) expected[-1] = 1 assert_np_equal(output.numpy(), expected) def test_transform_anon_type_instance(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def transform_create_test(input: wp.array(dtype=wptype), output: wp.array(dtype=wptype)): t = wp.transformation( wp.vector(input[0], input[1], input[2]), wp.quaternion(input[3], input[4], input[5], input[6]) ) for i in range(7): output[i] = wptype(2) * t[i] transform_create_kernel = getkernel(transform_create_test, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return input = wp.array(rng.standard_normal(size=7).astype(dtype), requires_grad=True, device=device) output = wp.zeros(7, dtype=wptype, requires_grad=True, device=device) wp.launch(transform_create_kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy(), 2 * input.numpy()) for i in range(len(input)): cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch(transform_create_kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device) tape.backward(loss=cmp) expectedgrads = np.zeros(len(input)) expectedgrads[i] = 2 assert_np_equal(tape.gradients[input].numpy(), expectedgrads) tape.zero() devices = get_test_devices() class TestSpatial(unittest.TestCase): pass for dtype in np_float_types: add_function_test_register_kernel( TestSpatial, f"test_spatial_vector_constructors_{dtype.__name__}", test_spatial_vector_constructors, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_vector_indexing_{dtype.__name__}", test_spatial_vector_indexing, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_vector_scalar_multiplication_{dtype.__name__}", test_spatial_vector_scalar_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_vector_add_sub_{dtype.__name__}", test_spatial_vector_add_sub, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_dot_{dtype.__name__}", test_spatial_dot, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestSpatial, f"test_spatial_cross_{dtype.__name__}", test_spatial_cross, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestSpatial, f"test_spatial_top_bottom_{dtype.__name__}", test_spatial_top_bottom, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_constructors_{dtype.__name__}", test_transform_constructors, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_anon_type_instance_{dtype.__name__}", test_transform_anon_type_instance, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_identity_{dtype.__name__}", test_transform_identity, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_indexing_{dtype.__name__}", test_transform_indexing, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_get_trans_rot_{dtype.__name__}", test_transform_get_trans_rot, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_multiply_{dtype.__name__}", test_transform_multiply, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_inverse_{dtype.__name__}", test_transform_inverse, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_point_vector_{dtype.__name__}", test_transform_point_vector, devices=devices, dtype=dtype, ) # are these two valid? They don't seem to be doing things you'd want to do, # maybe they should be removed add_function_test_register_kernel( TestSpatial, f"test_transform_scalar_multiplication_{dtype.__name__}", test_transform_scalar_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_transform_add_sub_{dtype.__name__}", test_transform_add_sub, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_matrix_constructors_{dtype.__name__}", test_spatial_matrix_constructors, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_matrix_indexing_{dtype.__name__}", test_spatial_matrix_indexing, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_matrix_scalar_multiplication_{dtype.__name__}", test_spatial_matrix_scalar_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_matrix_add_sub_{dtype.__name__}", test_spatial_matrix_add_sub, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_matvec_multiplication_{dtype.__name__}", test_spatial_matvec_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_matmat_multiplication_{dtype.__name__}", test_spatial_matmat_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_outer_product_{dtype.__name__}", test_spatial_outer_product, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestSpatial, f"test_spatial_adjoint_{dtype.__name__}", test_spatial_adjoint, devices=devices, dtype=dtype ) # \TODO: test spatial_mass and spatial_jacobian if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
76,441
Python
34.604099
120
0.591502
NVIDIA/warp/warp/tests/test_arithmetic.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * np_signed_int_types = [ np.int8, np.int16, np.int32, np.int64, np.byte, ] np_unsigned_int_types = [ np.uint8, np.uint16, np.uint32, np.uint64, np.ubyte, ] np_int_types = np_signed_int_types + np_unsigned_int_types np_float_types = [np.float16, np.float32, np.float64] np_scalar_types = np_int_types + np_float_types def randvals(rng, shape, dtype): if dtype in np_float_types: return rng.standard_normal(size=shape).astype(dtype) elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]: return rng.integers(1, high=3, size=shape, dtype=dtype) return rng.integers(1, high=5, size=shape, dtype=dtype) kernel_cache = {} def getkernel(func, suffix=""): key = func.__name__ + "_" + suffix if key not in kernel_cache: kernel_cache[key] = wp.Kernel(func=func, key=key) return kernel_cache[key] def get_select_kernel(dtype): def output_select_kernel_fn( input: wp.array(dtype=dtype), index: int, out: wp.array(dtype=dtype), ): out[0] = input[index] return getkernel(output_select_kernel_fn, suffix=dtype.__name__) def get_select_kernel2(dtype): def output_select_kernel2_fn( input: wp.array(dtype=dtype, ndim=2), index0: int, index1: int, out: wp.array(dtype=dtype), ): out[0] = input[index0, index1] return getkernel(output_select_kernel2_fn, suffix=dtype.__name__) def test_arrays(test, device, dtype): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] arr_np = randvals(rng, (10, 5), dtype) arr = wp.array(arr_np, dtype=wptype, requires_grad=True, device=device) assert_np_equal(arr.numpy(), arr_np, tol=tol) def test_unary_ops(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_unary( inputs: wp.array(dtype=wptype, ndim=2), outputs: wp.array(dtype=wptype, ndim=2), ): for i in range(10): i0 = inputs[0, i] i1 = inputs[1, i] i2 = inputs[2, i] i3 = inputs[3, i] i4 = inputs[4, i] # multiply outputs by 2 so we've got something to backpropagate: outputs[0, i] = wptype(2.0) * (+i0) outputs[1, i] = wptype(2.0) * (-i1) outputs[2, i] = wptype(2.0) * wp.sign(i2) outputs[3, i] = wptype(2.0) * wp.abs(i3) outputs[4, i] = wptype(2.0) * wp.step(i4) kernel = getkernel(check_unary, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return if dtype in np_float_types: inputs = wp.array( rng.standard_normal(size=(5, 10)).astype(dtype), dtype=wptype, requires_grad=True, device=device ) else: inputs = wp.array( rng.integers(-2, high=3, size=(5, 10), dtype=dtype), dtype=wptype, requires_grad=True, device=device ) outputs = wp.zeros_like(inputs) wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) assert_np_equal(outputs.numpy()[0], 2 * inputs.numpy()[0], tol=tol) assert_np_equal(outputs.numpy()[1], -2 * inputs.numpy()[1], tol=tol) expected = 2 * np.sign(inputs.numpy()[2]) expected[expected == 0] = 2 assert_np_equal(outputs.numpy()[2], expected, tol=tol) assert_np_equal(outputs.numpy()[3], 2 * np.abs(inputs.numpy()[3]), tol=tol) assert_np_equal(outputs.numpy()[4], 2 * (1 - np.heaviside(inputs.numpy()[4], 1)), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): # grad of 2x: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device) tape.backward(loss=out) expected_grads = np.zeros_like(inputs.numpy()) expected_grads[0, i] = 2 assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol) tape.zero() # grad of -2x: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device) tape.backward(loss=out) expected_grads = np.zeros_like(inputs.numpy()) expected_grads[1, i] = -2 assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol) tape.zero() # grad of 2 * sign(x): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 2, i], outputs=[out], device=device) tape.backward(loss=out) expected_grads = np.zeros_like(inputs.numpy()) assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol) tape.zero() # grad of 2 * abs(x): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 3, i], outputs=[out], device=device) tape.backward(loss=out) expected_grads = np.zeros_like(inputs.numpy()) expected_grads[3, i] = 2 * np.sign(inputs.numpy()[3, i]) assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol) tape.zero() # grad of 2 * step(x): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 4, i], outputs=[out], device=device) tape.backward(loss=out) expected_grads = np.zeros_like(inputs.numpy()) assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol) tape.zero() def test_nonzero(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_nonzero( inputs: wp.array(dtype=wptype), outputs: wp.array(dtype=wptype), ): for i in range(10): i0 = inputs[i] outputs[i] = wp.nonzero(i0) kernel = getkernel(check_nonzero, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return inputs = wp.array(rng.integers(-2, high=3, size=10).astype(dtype), dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(inputs) wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) assert_np_equal(outputs.numpy(), (inputs.numpy() != 0)) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): # grad should just be zero: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[out], device=device) tape.backward(loss=out) expected_grads = np.zeros_like(inputs.numpy()) assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol) tape.zero() def test_binary_ops(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_binary_ops( in1: wp.array(dtype=wptype, ndim=2), in2: wp.array(dtype=wptype, ndim=2), outputs: wp.array(dtype=wptype, ndim=2), ): for i in range(10): i0 = in1[0, i] i1 = in1[1, i] i2 = in1[2, i] i3 = in1[3, i] i4 = in1[4, i] i5 = in1[5, i] i6 = in1[6, i] i7 = in1[7, i] j0 = in2[0, i] j1 = in2[1, i] j2 = in2[2, i] j3 = in2[3, i] j4 = in2[4, i] j5 = in2[5, i] j6 = in2[6, i] j7 = in2[7, i] outputs[0, i] = wptype(2) * wp.mul(i0, j0) outputs[1, i] = wptype(2) * wp.div(i1, j1) outputs[2, i] = wptype(2) * wp.add(i2, j2) outputs[3, i] = wptype(2) * wp.sub(i3, j3) outputs[4, i] = wptype(2) * wp.mod(i4, j4) outputs[5, i] = wptype(2) * wp.min(i5, j5) outputs[6, i] = wptype(2) * wp.max(i6, j6) outputs[7, i] = wptype(2) * wp.floordiv(i7, j7) kernel = getkernel(check_binary_ops, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return vals1 = randvals(rng, [8, 10], dtype) if dtype in [np_unsigned_int_types]: vals2 = vals1 + randvals(rng, [8, 10], dtype) else: vals2 = np.abs(randvals(rng, [8, 10], dtype)) in1 = wp.array(vals1, dtype=wptype, requires_grad=True, device=device) in2 = wp.array(vals2, dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(in1) wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) assert_np_equal(outputs.numpy()[0], 2 * in1.numpy()[0] * in2.numpy()[0], tol=tol) if dtype in np_float_types: assert_np_equal(outputs.numpy()[1], 2 * in1.numpy()[1] / (in2.numpy()[1]), tol=tol) else: assert_np_equal(outputs.numpy()[1], 2 * (in1.numpy()[1] // (in2.numpy()[1])), tol=tol) assert_np_equal(outputs.numpy()[2], 2 * (in1.numpy()[2] + (in2.numpy()[2])), tol=tol) assert_np_equal(outputs.numpy()[3], 2 * (in1.numpy()[3] - (in2.numpy()[3])), tol=tol) # ...so this is actually the desired behaviour right? Looks like wp.mod doesn't behave like # python's % operator or np.mod()... assert_np_equal( outputs.numpy()[4], 2 * ( (in1.numpy()[4]) - (in2.numpy()[4]) * np.sign(in1.numpy()[4]) * np.floor(np.abs(in1.numpy()[4]) / (in2.numpy()[4])) ), tol=tol, ) assert_np_equal(outputs.numpy()[5], 2 * np.minimum(in1.numpy()[5], in2.numpy()[5]), tol=tol) assert_np_equal(outputs.numpy()[6], 2 * np.maximum(in1.numpy()[6], in2.numpy()[6]), tol=tol) assert_np_equal(outputs.numpy()[7], 2 * np.floor_divide(in1.numpy()[7], in2.numpy()[7]), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): # multiplication: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[0, i] = 2.0 * in2.numpy()[0, i] assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[0, i] = 2.0 * in1.numpy()[0, i] assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # division: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[1, i] = 2.0 / (in2.numpy()[1, i]) assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) # y = x1/x2 # dy/dx2 = -x1/x2^2 expected[1, i] = (-2.0) * (in1.numpy()[1, i] / (in2.numpy()[1, i] ** 2)) assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # addition: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 2, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[2, i] = 2.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[2, i] = 2.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # subtraction: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 3, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[3, i] = 2.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[3, i] = -2.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # modulus. unless at discontinuities, # d/dx1( x1 % x2 ) == 1 # d/dx2( x1 % x2 ) == 0 tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 4, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[4, i] = 2.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[4, i] = 0.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # min tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 5, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[5, i] = 2.0 if (in1.numpy()[5, i] < in2.numpy()[5, i]) else 0.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[5, i] = 2.0 if (in2.numpy()[5, i] < in1.numpy()[5, i]) else 0.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # max tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 6, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[6, i] = 2.0 if (in1.numpy()[6, i] > in2.numpy()[6, i]) else 0.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[6, i] = 2.0 if (in2.numpy()[6, i] > in1.numpy()[6, i]) else 0.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # floor_divide. Returns integers so gradient is zero tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 7, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() def test_special_funcs(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_special_funcs( inputs: wp.array(dtype=wptype, ndim=2), outputs: wp.array(dtype=wptype, ndim=2), ): # multiply outputs by 2 so we've got something to backpropagate: for i in range(10): outputs[0, i] = wptype(2) * wp.log(inputs[0, i]) outputs[1, i] = wptype(2) * wp.log2(inputs[1, i]) outputs[2, i] = wptype(2) * wp.log10(inputs[2, i]) outputs[3, i] = wptype(2) * wp.exp(inputs[3, i]) outputs[4, i] = wptype(2) * wp.atan(inputs[4, i]) outputs[5, i] = wptype(2) * wp.sin(inputs[5, i]) outputs[6, i] = wptype(2) * wp.cos(inputs[6, i]) outputs[7, i] = wptype(2) * wp.sqrt(inputs[7, i]) outputs[8, i] = wptype(2) * wp.tan(inputs[8, i]) outputs[9, i] = wptype(2) * wp.sinh(inputs[9, i]) outputs[10, i] = wptype(2) * wp.cosh(inputs[10, i]) outputs[11, i] = wptype(2) * wp.tanh(inputs[11, i]) outputs[12, i] = wptype(2) * wp.acos(inputs[12, i]) outputs[13, i] = wptype(2) * wp.asin(inputs[13, i]) outputs[14, i] = wptype(2) * wp.cbrt(inputs[14, i]) kernel = getkernel(check_special_funcs, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return invals = rng.normal(size=(15, 10)).astype(dtype) invals[[0, 1, 2, 7, 14]] = 0.1 + np.abs(invals[[0, 1, 2, 7, 14]]) invals[12] = np.clip(invals[12], -0.9, 0.9) invals[13] = np.clip(invals[13], -0.9, 0.9) inputs = wp.array(invals, dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(inputs) wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) assert_np_equal(outputs.numpy()[0], 2 * np.log(inputs.numpy()[0]), tol=tol) assert_np_equal(outputs.numpy()[1], 2 * np.log2(inputs.numpy()[1]), tol=tol) assert_np_equal(outputs.numpy()[2], 2 * np.log10(inputs.numpy()[2]), tol=tol) assert_np_equal(outputs.numpy()[3], 2 * np.exp(inputs.numpy()[3]), tol=tol) assert_np_equal(outputs.numpy()[4], 2 * np.arctan(inputs.numpy()[4]), tol=tol) assert_np_equal(outputs.numpy()[5], 2 * np.sin(inputs.numpy()[5]), tol=tol) assert_np_equal(outputs.numpy()[6], 2 * np.cos(inputs.numpy()[6]), tol=tol) assert_np_equal(outputs.numpy()[7], 2 * np.sqrt(inputs.numpy()[7]), tol=tol) assert_np_equal(outputs.numpy()[8], 2 * np.tan(inputs.numpy()[8]), tol=tol) assert_np_equal(outputs.numpy()[9], 2 * np.sinh(inputs.numpy()[9]), tol=tol) assert_np_equal(outputs.numpy()[10], 2 * np.cosh(inputs.numpy()[10]), tol=tol) assert_np_equal(outputs.numpy()[11], 2 * np.tanh(inputs.numpy()[11]), tol=tol) assert_np_equal(outputs.numpy()[12], 2 * np.arccos(inputs.numpy()[12]), tol=tol) assert_np_equal(outputs.numpy()[13], 2 * np.arcsin(inputs.numpy()[13]), tol=tol) assert_np_equal(outputs.numpy()[14], 2 * np.cbrt(inputs.numpy()[14]), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): # log: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[0, i] = 2.0 / inputs.numpy()[0, i] assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # log2: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[1, i] = 2.0 / (inputs.numpy()[1, i] * np.log(2.0)) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # log10: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 2, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[2, i] = 2.0 / (inputs.numpy()[2, i] * np.log(10.0)) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # exp: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 3, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[3, i] = outputs.numpy()[3, i] assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # arctan: # looks like the autodiff formula in warp was wrong? Was (1 + x^2) rather than # 1/(1 + x^2) tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 4, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[4, i] = 2.0 / (inputs.numpy()[4, i] ** 2 + 1) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # sin: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 5, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[5, i] = np.cos(inputs.numpy()[5, i]) * 2 assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # cos: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 6, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[6, i] = -np.sin(inputs.numpy()[6, i]) * 2.0 assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # sqrt: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 7, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[7, i] = 1.0 / (np.sqrt(inputs.numpy()[7, i])) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # tan: # looks like there was a bug in autodiff formula here too - gradient was zero if cos(x) > 0 # (should have been "if(cosx != 0)") tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 8, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[8, i] = 2.0 / (np.cos(inputs.numpy()[8, i]) ** 2) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=200 * tol) tape.zero() # sinh: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 9, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[9, i] = 2.0 * np.cosh(inputs.numpy()[9, i]) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # cosh: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 10, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[10, i] = 2.0 * np.sinh(inputs.numpy()[10, i]) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # tanh: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 11, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[11, i] = 2.0 / (np.cosh(inputs.numpy()[11, i]) ** 2) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # arccos: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 12, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[12, i] = -2.0 / np.sqrt(1 - inputs.numpy()[12, i] ** 2) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() # arcsin: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 13, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) expected[13, i] = 2.0 / np.sqrt(1 - inputs.numpy()[13, i] ** 2) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=6 * tol) tape.zero() # cbrt: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 14, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(inputs.numpy()) cbrt = np.cbrt(inputs.numpy()[14, i], dtype=np.dtype(dtype)) expected[14, i] = (2.0 / 3.0) * (1.0 / (cbrt * cbrt)) assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol) tape.zero() def test_special_funcs_2arg(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_special_funcs_2arg( in1: wp.array(dtype=wptype, ndim=2), in2: wp.array(dtype=wptype, ndim=2), outputs: wp.array(dtype=wptype, ndim=2), ): # multiply outputs by 2 so we've got something to backpropagate: for i in range(10): outputs[0, i] = wptype(2) * wp.pow(in1[0, i], in2[0, i]) outputs[1, i] = wptype(2) * wp.atan2(in1[1, i], in2[1, i]) kernel = getkernel(check_special_funcs_2arg, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return in1 = wp.array(np.abs(randvals(rng, [2, 10], dtype)), dtype=wptype, requires_grad=True, device=device) in2 = wp.array(randvals(rng, [2, 10], dtype), dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(in1) wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) assert_np_equal(outputs.numpy()[0], 2.0 * np.power(in1.numpy()[0], in2.numpy()[0]), tol=tol) assert_np_equal(outputs.numpy()[1], 2.0 * np.arctan2(in1.numpy()[1], in2.numpy()[1]), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): # pow: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[0, i] = 2.0 * in2.numpy()[0, i] * np.power(in1.numpy()[0, i], in2.numpy()[0, i] - 1) assert_np_equal(tape.gradients[in1].numpy(), expected, tol=5 * tol) expected[0, i] = 2.0 * np.power(in1.numpy()[0, i], in2.numpy()[0, i]) * np.log(in1.numpy()[0, i]) assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() # atan2: tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(in1.numpy()) expected[1, i] = 2.0 * in2.numpy()[1, i] / (in1.numpy()[1, i] ** 2 + in2.numpy()[1, i] ** 2) assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[1, i] = -2.0 * in1.numpy()[1, i] / (in1.numpy()[1, i] ** 2 + in2.numpy()[1, i] ** 2) assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) tape.zero() def test_float_to_int(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_float_to_int( inputs: wp.array(dtype=wptype, ndim=2), outputs: wp.array(dtype=wptype, ndim=2), ): for i in range(10): outputs[0, i] = wp.round(inputs[0, i]) outputs[1, i] = wp.rint(inputs[1, i]) outputs[2, i] = wp.trunc(inputs[2, i]) outputs[3, i] = wp.floor(inputs[3, i]) outputs[4, i] = wp.ceil(inputs[4, i]) outputs[5, i] = wp.frac(inputs[5, i]) kernel = getkernel(check_float_to_int, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return inputs = wp.array(rng.standard_normal(size=(6, 10)).astype(dtype), dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(inputs) wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) assert_np_equal(outputs.numpy()[0], np.round(inputs.numpy()[0])) assert_np_equal(outputs.numpy()[1], np.rint(inputs.numpy()[1])) assert_np_equal(outputs.numpy()[2], np.trunc(inputs.numpy()[2])) assert_np_equal(outputs.numpy()[3], np.floor(inputs.numpy()[3])) assert_np_equal(outputs.numpy()[4], np.ceil(inputs.numpy()[4])) assert_np_equal(outputs.numpy()[5], np.modf(inputs.numpy()[5])[0]) # all the gradients should be zero as these functions are piecewise constant: out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(10): for j in range(5): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, j, i], outputs=[out], device=device) tape.backward(loss=out) assert_np_equal(tape.gradients[inputs].numpy(), np.zeros_like(inputs.numpy()), tol=tol) tape.zero() def test_interp(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 5.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_interp( in1: wp.array(dtype=wptype, ndim=2), in2: wp.array(dtype=wptype, ndim=2), in3: wp.array(dtype=wptype, ndim=2), outputs: wp.array(dtype=wptype, ndim=2), ): # multiply outputs by 2 so we've got something to backpropagate: for i in range(10): outputs[0, i] = wptype(2) * wp.smoothstep(in1[0, i], in2[0, i], in3[0, i]) outputs[1, i] = wptype(2) * wp.lerp(in1[1, i], in2[1, i], in3[1, i]) kernel = getkernel(check_interp, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return e0 = randvals(rng, [2, 10], dtype) e1 = e0 + randvals(rng, [2, 10], dtype) + 0.1 in1 = wp.array(e0, dtype=wptype, requires_grad=True, device=device) in2 = wp.array(e1, dtype=wptype, requires_grad=True, device=device) in3 = wp.array(randvals(rng, [2, 10], dtype), dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(in1) wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device) edge0 = in1.numpy()[0] edge1 = in2.numpy()[0] t_smoothstep = in3.numpy()[0] x = np.clip((t_smoothstep - edge0) / (edge1 - edge0), 0, 1) smoothstep_expected = 2.0 * x * x * (3 - 2 * x) assert_np_equal(outputs.numpy()[0], smoothstep_expected, tol=tol) a = in1.numpy()[1] b = in2.numpy()[1] t = in3.numpy()[1] assert_np_equal(outputs.numpy()[1], 2.0 * (a * (1 - t) + b * t), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device) tape.backward(loss=out) # e0 = in1 # e1 = in2 # t = in3 # x = clamp((t - e0) / (e1 - e0), 0,1) # dx/dt = 1 / (e1 - e0) if e0 < t < e1 else 0 # y = x * x * (3 - 2 * x) # y = 3 * x * x - 2 * x * x * x # dy/dx = 6 * ( x - x^2 ) dydx = 6 * x * (1 - x) # dy/in1 = dy/dx dx/de0 de0/din1 dxde0 = (t_smoothstep - edge1) / ((edge1 - edge0) ** 2) dxde0[x == 0] = 0 dxde0[x == 1] = 0 expected_grads = np.zeros_like(in1.numpy()) expected_grads[0, i] = 2.0 * dydx[i] * dxde0[i] assert_np_equal(tape.gradients[in1].numpy(), expected_grads, tol=tol) # dy/in2 = dy/dx dx/de1 de1/din2 dxde1 = (edge0 - t_smoothstep) / ((edge1 - edge0) ** 2) dxde1[x == 0] = 0 dxde1[x == 1] = 0 expected_grads = np.zeros_like(in1.numpy()) expected_grads[0, i] = 2.0 * dydx[i] * dxde1[i] assert_np_equal(tape.gradients[in2].numpy(), expected_grads, tol=tol) # dy/in3 = dy/dx dx/dt dt/din3 dxdt = 1.0 / (edge1 - edge0) dxdt[x == 0] = 0 dxdt[x == 1] = 0 expected_grads = np.zeros_like(in1.numpy()) expected_grads[0, i] = 2.0 * dydx[i] * dxdt[i] assert_np_equal(tape.gradients[in3].numpy(), expected_grads, tol=tol) tape.zero() tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device) tape.backward(loss=out) # y = a*(1-t) + b*t # a = in1 # b = in2 # t = in3 # y = in1*( 1 - in3 ) + in2*in3 # dy/din1 = (1-in3) expected_grads = np.zeros_like(in1.numpy()) expected_grads[1, i] = 2.0 * (1 - in3.numpy()[1, i]) assert_np_equal(tape.gradients[in1].numpy(), expected_grads, tol=tol) # dy/din2 = in3 expected_grads = np.zeros_like(in1.numpy()) expected_grads[1, i] = 2.0 * in3.numpy()[1, i] assert_np_equal(tape.gradients[in2].numpy(), expected_grads, tol=tol) # dy/din3 = 8*in2 - 1.5*4*in1 expected_grads = np.zeros_like(in1.numpy()) expected_grads[1, i] = 2.0 * (in2.numpy()[1, i] - in1.numpy()[1, i]) assert_np_equal(tape.gradients[in3].numpy(), expected_grads, tol=tol) tape.zero() def test_clamp(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-6, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_clamp( in1: wp.array(dtype=wptype), in2: wp.array(dtype=wptype), in3: wp.array(dtype=wptype), outputs: wp.array(dtype=wptype), ): for i in range(100): # multiply output by 2 so we've got something to backpropagate: outputs[i] = wptype(2) * wp.clamp(in1[i], in2[i], in3[i]) kernel = getkernel(check_clamp, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return in1 = wp.array(randvals(rng, [100], dtype), dtype=wptype, requires_grad=True, device=device) starts = randvals(rng, [100], dtype) diffs = np.abs(randvals(rng, [100], dtype)) in2 = wp.array(starts, dtype=wptype, requires_grad=True, device=device) in3 = wp.array(starts + diffs, dtype=wptype, requires_grad=True, device=device) outputs = wp.zeros_like(in1) wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device) assert_np_equal(2 * np.clip(in1.numpy(), in2.numpy(), in3.numpy()), outputs.numpy(), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(100): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[out], device=device) tape.backward(loss=out) t = in1.numpy()[i] lower = in2.numpy()[i] upper = in3.numpy()[i] expected = np.zeros_like(in1.numpy()) if t < lower: expected[i] = 2.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) expected[i] = 0.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) assert_np_equal(tape.gradients[in3].numpy(), expected, tol=tol) elif t > upper: expected[i] = 2.0 assert_np_equal(tape.gradients[in3].numpy(), expected, tol=tol) expected[i] = 0.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) else: expected[i] = 2.0 assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol) expected[i] = 0.0 assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol) assert_np_equal(tape.gradients[in3].numpy(), expected, tol=tol) tape.zero() devices = get_test_devices() class TestArithmetic(unittest.TestCase): pass # these unary ops only make sense for signed values: for dtype in np_signed_int_types + np_float_types: add_function_test_register_kernel( TestArithmetic, f"test_unary_ops_{dtype.__name__}", test_unary_ops, devices=devices, dtype=dtype ) for dtype in np_float_types: add_function_test_register_kernel( TestArithmetic, f"test_special_funcs_{dtype.__name__}", test_special_funcs, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestArithmetic, f"test_special_funcs_2arg_{dtype.__name__}", test_special_funcs_2arg, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestArithmetic, f"test_interp_{dtype.__name__}", test_interp, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestArithmetic, f"test_float_to_int_{dtype.__name__}", test_float_to_int, devices=devices, dtype=dtype ) for dtype in np_scalar_types: add_function_test_register_kernel( TestArithmetic, f"test_clamp_{dtype.__name__}", test_clamp, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestArithmetic, f"test_nonzero_{dtype.__name__}", test_nonzero, devices=devices, dtype=dtype ) add_function_test(TestArithmetic, f"test_arrays_{dtype.__name__}", test_arrays, devices=devices, dtype=dtype) add_function_test_register_kernel( TestArithmetic, f"test_binary_ops_{dtype.__name__}", test_binary_ops, devices=devices, dtype=dtype ) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
43,846
Python
39.263545
119
0.559504
NVIDIA/warp/warp/tests/aux_test_unresolved_symbol.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import warp as wp @wp.kernel def unresolved_symbol_kernel(): # this should trigger an exception due to unresolved symbol x = missing_symbol # noqa: F821
588
Python
38.266664
76
0.789116
NVIDIA/warp/warp/tests/test_builtins_resolution.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import contextlib import unittest import numpy as np from warp.tests.unittest_utils import * def nps(dtype, value): """Creates a NumPy scalar value based on the given data type.""" # Workaround to avoid deprecation warning messages for integer overflows. return np.array((value,)).astype(dtype)[0] def npv(dtype, values): """Creates a vector of NumPy scalar values based on the given data type.""" return tuple(nps(dtype, x) for x in values) def npm(dtype, dim, values): """Creates a matrix of NumPy scalar values based on the given data type.""" return tuple(npv(dtype, values[i * dim : (i + 1) * dim]) for i in range(dim)) def wpv(dtype, values): """Creates a vector of Warp scalar values based on the given data type.""" return tuple(dtype(x) for x in values) def wpm(dtype, dim, values): """Creates a matrix of Warp scalar values based on the given data type.""" return tuple(wpv(dtype, values[i * dim : (i + 1) * dim]) for i in range(dim)) def test_int_arg_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] value = -1234567890123456789 expected = wp.invert(dtype(value)) test.assertEqual(wp.invert(nps(np_type, value)), expected) def test_float_arg_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] value = 1.23 expected = wp.sin(dtype(value)) test.assertEqual(wp.sin(nps(np_type, value)), expected) def test_int_int_args_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] value = -1234567890 expected = wp.mul(dtype(value), dtype(value)) test.assertEqual(wp.mul(dtype(value), dtype(value)), expected) test.assertEqual(wp.mul(dtype(value), nps(np_type, value)), expected) test.assertEqual(wp.mul(nps(np_type, value), dtype(value)), expected) test.assertEqual(wp.mul(nps(np_type, value), nps(np_type, value)), expected) if dtype is wp.int32: test.assertEqual(wp.mul(dtype(value), value), expected) test.assertEqual(wp.mul(nps(np_type, value), value), expected) test.assertEqual(wp.mul(value, value), expected) test.assertEqual(wp.mul(value, dtype(value)), expected) test.assertEqual(wp.mul(value, nps(np_type, value)), expected) else: with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments '{dtype.__name__}, int'$", ): wp.mul(dtype(value), value) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments '{np_type.__name__}, int'$", ): wp.mul(nps(np_type, value), value) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments 'int, {dtype.__name__}'$", ): wp.mul(value, dtype(value)) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments 'int, {np_type.__name__}'$", ): wp.mul(value, nps(np_type, value)) def test_mat_arg_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] mat_cls = wp.types.matrix((3, 3), dtype) values = (1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01) expected = wp.trace(mat_cls(*values)) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): test.assertEqual(wp.trace(wpv(dtype, values)), expected) test.assertEqual(wp.trace(wpm(dtype, 3, values)), expected) test.assertEqual(wp.trace(npv(np_type, values)), expected) test.assertEqual(wp.trace(npm(np_type, 3, values)), expected) test.assertEqual(wp.trace(np.array(npv(np_type, values))), expected) def test_mat_mat_args_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] mat_cls = wp.types.matrix((3, 3), dtype) a_values = (0.12, 1.23, 2.34, 0.12, 1.23, 2.34, 0.12, 1.23, 2.34) b_values = (2.34, 1.23, 0.12, 2.34, 1.23, 0.12, 2.34, 1.23, 0.12) expected = wp.ddot(mat_cls(*a_values), mat_cls(*b_values)) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): test.assertEqual(wp.ddot(mat_cls(*a_values), mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(mat_cls(*a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(mat_cls(*a_values), wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(mat_cls(*a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(mat_cls(*a_values), npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(mat_cls(*a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), np.array(npv(np_type, b_values))), expected) if dtype is wp.float32: test.assertEqual(wp.ddot(mat_cls(*a_values), b_values), expected) test.assertEqual(wp.ddot(wpv(dtype, a_values), b_values), expected) test.assertEqual(wp.ddot(wpm(dtype, 3, a_values), b_values), expected) test.assertEqual(wp.ddot(npv(np_type, a_values), b_values), expected) test.assertEqual(wp.ddot(npm(np_type, 3, a_values), b_values), expected) test.assertEqual(wp.ddot(a_values, b_values), expected) test.assertEqual(wp.ddot(np.array(npv(np_type, a_values)), b_values), expected) test.assertEqual(wp.ddot(a_values, mat_cls(*b_values)), expected) test.assertEqual(wp.ddot(a_values, wpv(dtype, b_values)), expected) test.assertEqual(wp.ddot(a_values, wpm(dtype, 3, b_values)), expected) test.assertEqual(wp.ddot(a_values, npv(np_type, b_values)), expected) test.assertEqual(wp.ddot(a_values, npm(np_type, 3, b_values)), expected) test.assertEqual(wp.ddot(a_values, np.array(npv(np_type, b_values))), expected) else: with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'mat_t, tuple'$", ): wp.ddot(mat_cls(*a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(wpv(dtype, a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(wpm(dtype, 3, a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(npv(np_type, a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(npm(np_type, 3, a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'ndarray, tuple'$", ): wp.ddot(np.array(npv(np_type, a_values)), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, mat_t'$", ): wp.ddot(a_values, mat_cls(*b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(a_values, wpv(dtype, b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(a_values, wpm(dtype, 3, b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(a_values, npv(np_type, b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.ddot(a_values, npm(np_type, 3, b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'ddot' compatible with " r"the arguments 'tuple, ndarray'$", ): wp.ddot(a_values, np.array(npv(np_type, b_values))) def test_mat_float_args_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] mat_cls = wp.types.matrix((3, 3), dtype) a_values = (1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01) b_value = 0.12 expected = wp.mul(mat_cls(*a_values), dtype(b_value)) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): test.assertEqual(wp.mul(mat_cls(*a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(mat_cls(*a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(wpv(dtype, a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(wpv(dtype, a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(wpm(dtype, 3, a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(wpm(dtype, 3, a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(npv(np_type, a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(npv(np_type, a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(npm(np_type, 3, a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(npm(np_type, 3, a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(np.array(npv(np_type, a_values)), dtype(b_value)), expected) test.assertEqual(wp.mul(np.array(npv(np_type, a_values)), nps(np_type, b_value)), expected) if dtype is wp.float32: test.assertEqual(wp.mul(mat_cls(*a_values), b_value), expected) test.assertEqual(wp.mul(wpv(dtype, a_values), b_value), expected) test.assertEqual(wp.mul(wpm(dtype, 3, a_values), b_value), expected) test.assertEqual(wp.mul(npv(np_type, a_values), b_value), expected) test.assertEqual(wp.mul(npm(np_type, 3, a_values), b_value), expected) test.assertEqual(wp.mul(a_values, b_value), expected) test.assertEqual(wp.mul(np.array(npv(np_type, a_values)), b_value), expected) test.assertEqual(wp.mul(a_values, dtype(b_value)), expected) test.assertEqual(wp.mul(a_values, nps(np_type, b_value)), expected) else: with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'mat_t, float'$", ): wp.mul(mat_cls(*a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'tuple, float'$", ): wp.mul(wpv(dtype, a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'tuple, float'$", ): wp.mul(wpm(dtype, 3, a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'tuple, float'$", ): wp.mul(npv(np_type, a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'tuple, float'$", ): wp.mul(npm(np_type, 3, a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'ndarray, float'$", ): wp.mul(np.array(npv(np_type, a_values)), b_value) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments 'tuple, {dtype.__name__}'$", ): wp.mul(a_values, dtype(b_value)) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments 'tuple, {np_type.__name__}'$", ): wp.mul(a_values, nps(np_type, b_value)) def test_vec_arg_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] vec_cls = wp.types.vector(3, dtype) values = (1.23, 2.34, 3.45) expected = wp.length(vec_cls(*values)) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): test.assertAlmostEqual(wp.length(wpv(dtype, values)), expected) test.assertAlmostEqual(wp.length(npv(np_type, values)), expected) test.assertAlmostEqual(wp.length(np.array(npv(np_type, values))), expected) def test_vec_vec_args_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] vec_cls = wp.types.vector(3, dtype) a_values = (1.23, 2.34, 3.45) b_values = (4.56, 5.67, 6.78) expected = wp.dot(vec_cls(*a_values), vec_cls(*b_values)) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): test.assertEqual(wp.dot(vec_cls(*a_values), vec_cls(*b_values)), expected) test.assertEqual(wp.dot(vec_cls(*a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.dot(vec_cls(*a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.dot(vec_cls(*a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.dot(wpv(dtype, a_values), vec_cls(*b_values)), expected) test.assertEqual(wp.dot(wpv(dtype, a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.dot(wpv(dtype, a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.dot(wpv(dtype, a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.dot(npv(np_type, a_values), vec_cls(*b_values)), expected) test.assertEqual(wp.dot(npv(np_type, a_values), wpv(dtype, b_values)), expected) test.assertEqual(wp.dot(npv(np_type, a_values), npv(np_type, b_values)), expected) test.assertEqual(wp.dot(npv(np_type, a_values), np.array(npv(np_type, b_values))), expected) test.assertEqual(wp.dot(np.array(npv(np_type, a_values)), vec_cls(*b_values)), expected) test.assertEqual(wp.dot(np.array(npv(np_type, a_values)), wpv(dtype, b_values)), expected) test.assertEqual(wp.dot(np.array(npv(np_type, a_values)), npv(np_type, b_values)), expected) test.assertEqual(wp.dot(np.array(npv(np_type, a_values)), np.array(npv(np_type, b_values))), expected) if dtype is wp.float32: test.assertEqual(wp.dot(vec_cls(*a_values), b_values), expected) test.assertEqual(wp.dot(wpv(dtype, a_values), b_values), expected) test.assertEqual(wp.dot(npv(np_type, a_values), b_values), expected) test.assertEqual(wp.dot(a_values, b_values), expected) test.assertEqual(wp.dot(np.array(npv(np_type, a_values)), b_values), expected) test.assertEqual(wp.dot(a_values, vec_cls(*b_values)), expected) test.assertEqual(wp.dot(a_values, wpv(dtype, b_values)), expected) test.assertEqual(wp.dot(a_values, npv(np_type, b_values)), expected) test.assertEqual(wp.dot(a_values, np.array(npv(np_type, b_values))), expected) else: with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'vec_t, tuple'$", ): wp.dot(vec_cls(*a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.dot(wpv(dtype, a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.dot(npv(np_type, a_values), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'ndarray, tuple'$", ): wp.dot(np.array(npv(np_type, a_values)), b_values) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'tuple, vec_t'$", ): wp.dot(a_values, vec_cls(*b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.dot(a_values, wpv(dtype, b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'tuple, tuple'$", ): wp.dot(a_values, npv(np_type, b_values)) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'dot' compatible with " r"the arguments 'tuple, ndarray'$", ): wp.dot(a_values, np.array(npv(np_type, b_values))) def test_vec_float_args_support(test, device, dtype): np_type = wp.types.warp_type_to_np_dtype[dtype] vec_cls = wp.types.vector(3, dtype) a_values = (1.23, 2.34, 3.45) b_value = 4.56 expected = wp.mul(vec_cls(*a_values), dtype(b_value)) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): test.assertEqual(wp.mul(vec_cls(*a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(vec_cls(*a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(wpv(dtype, a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(wpv(dtype, a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(npv(np_type, a_values), dtype(b_value)), expected) test.assertEqual(wp.mul(npv(np_type, a_values), nps(np_type, b_value)), expected) test.assertEqual(wp.mul(np.array(npv(np_type, a_values)), dtype(b_value)), expected) test.assertEqual(wp.mul(np.array(npv(np_type, a_values)), nps(np_type, b_value)), expected) if dtype is wp.float32: test.assertEqual(wp.mul(vec_cls(*a_values), b_value), expected) test.assertEqual(wp.mul(wpv(dtype, a_values), b_value), expected) test.assertEqual(wp.mul(npv(np_type, a_values), b_value), expected) test.assertEqual(wp.mul(a_values, b_value), expected) test.assertEqual(wp.mul(np.array(npv(np_type, a_values)), b_value), expected) test.assertEqual(wp.mul(a_values, dtype(b_value)), expected) test.assertEqual(wp.mul(a_values, nps(np_type, b_value)), expected) else: with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'vec_t, float'$", ): wp.mul(vec_cls(*a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'tuple, float'$", ): wp.mul(wpv(dtype, a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'tuple, float'$", ): wp.mul(npv(np_type, a_values), b_value) with test.assertRaisesRegex( RuntimeError, r"Couldn't find a function 'mul' compatible with " r"the arguments 'ndarray, float'$", ): wp.mul(np.array(npv(np_type, a_values)), b_value) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments 'tuple, {dtype.__name__}'$", ): wp.mul(a_values, dtype(b_value)) with test.assertRaisesRegex( RuntimeError, rf"Couldn't find a function 'mul' compatible with " rf"the arguments 'tuple, {np_type.__name__}'$", ): wp.mul(a_values, nps(np_type, b_value)) class TestBuiltinsResolution(unittest.TestCase): def test_int_arg_overflow(self): value = -1234567890123456789 self.assertEqual(wp.invert(wp.int8(value)), 20) self.assertEqual(wp.invert(wp.int16(value)), -32492) self.assertEqual(wp.invert(wp.int32(value)), 2112454932) self.assertEqual(wp.invert(wp.int64(value)), 1234567890123456788) self.assertEqual(wp.invert(wp.uint8(value)), 20) self.assertEqual(wp.invert(wp.uint16(value)), 33044) self.assertEqual(wp.invert(wp.uint32(value)), 2112454932) self.assertEqual(wp.invert(wp.uint64(value)), 1234567890123456788) self.assertEqual(wp.invert(value), wp.invert(wp.int32(value))) def test_float_arg_precision(self): value = 1.23 expected = 0.94248880193169748409 result = wp.sin(wp.float64(value)) self.assertAlmostEqual(result, expected, places=12) result = wp.sin(wp.float32(value)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.sin(wp.float16(value)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) self.assertEqual(wp.sin(value), wp.sin(wp.float32(value))) def test_int_int_args_overflow(self): value = -1234567890 self.assertEqual(wp.mul(wp.int8(value), wp.int8(value)), 68) self.assertEqual(wp.mul(wp.int16(value), wp.int16(value)), -3004) self.assertEqual(wp.mul(wp.int32(value), wp.int32(value)), 304084036) self.assertEqual(wp.mul(wp.int64(value), wp.int64(value)), 1524157875019052100) self.assertEqual(wp.mul(wp.uint8(value), wp.uint8(value)), 68) self.assertEqual(wp.mul(wp.uint16(value), wp.uint16(value)), 62532) self.assertEqual(wp.mul(wp.uint32(value), wp.uint32(value)), 304084036) self.assertEqual(wp.mul(wp.uint64(value), wp.uint64(value)), 1524157875019052100) self.assertEqual(wp.mul(value, value), wp.mul(wp.int32(value), wp.int32(value))) def test_mat22_arg_precision(self): values = (1.23, 2.34, 3.45, 4.56) values_2d = (values[0:2], values[2:4]) expected = 5.78999999999999914735 result = wp.trace(wp.mat22d(*values)) self.assertAlmostEqual(result, expected, places=12) result = wp.trace(wp.mat22f(*values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.trace(wp.mat22h(*values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.trace(values), wp.trace(wp.mat22f(*values))) self.assertEqual(wp.trace(values_2d), wp.trace(wp.mat22f(*values))) def test_mat33_arg_precision(self): values = (1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01) values_2d = (values[0:3], values[3:6], values[6:9]) expected = 15.91000000000000014211 result = wp.trace(wp.mat33d(*values)) self.assertAlmostEqual(result, expected, places=12) result = wp.trace(wp.mat33f(*values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.trace(wp.mat33h(*values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.trace(values), wp.trace(wp.mat33f(*values))) self.assertEqual(wp.trace(values_2d), wp.trace(wp.mat33f(*values))) def test_mat44_arg_precision(self): values = (1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01, 10.12, 11.23, 12.34, 13.45, 14.56, 15.67, 16.78) values_2d = (values[0:4], values[4:8], values[8:12], values[12:16]) expected = 36.02000000000000312639 result = wp.trace(wp.mat44d(*values)) self.assertAlmostEqual(result, expected, places=12) result = wp.trace(wp.mat44f(*values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.trace(wp.mat44h(*values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.trace(values), wp.trace(wp.mat44f(*values))) self.assertEqual(wp.trace(values_2d), wp.trace(wp.mat44f(*values))) def test_mat22_mat22_args_precision(self): a_values = (0.12, 1.23, 0.12, 1.23) a_values_2d = (a_values[0:2], a_values[2:4]) b_values = (1.23, 0.12, 1.23, 0.12) b_values_2d = (b_values[0:2], b_values[2:4]) expected = 0.59039999999999992486 result = wp.ddot(wp.mat22d(*a_values), wp.mat22d(*b_values)) self.assertAlmostEqual(result, expected, places=12) result = wp.ddot(wp.mat22f(*a_values), wp.mat22f(*b_values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.ddot(wp.mat22h(*a_values), wp.mat22h(*b_values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.ddot(a_values, b_values), wp.ddot(wp.mat22f(*a_values), wp.mat22f(*b_values))) self.assertEqual(wp.ddot(a_values_2d, b_values_2d), wp.ddot(wp.mat22f(*a_values), wp.mat22f(*b_values))) self.assertEqual(wp.ddot(a_values, b_values_2d), wp.ddot(wp.mat22f(*a_values), wp.mat22f(*b_values))) self.assertEqual(wp.ddot(a_values_2d, b_values), wp.ddot(wp.mat22f(*a_values), wp.mat22f(*b_values))) def test_mat33_mat33_args_precision(self): a_values = (0.12, 1.23, 2.34, 0.12, 1.23, 2.34, 0.12, 1.23, 2.34) a_values_2d = (a_values[0:3], a_values[3:6], a_values[6:9]) b_values = (2.34, 1.23, 0.12, 2.34, 1.23, 0.12, 2.34, 1.23, 0.12) b_values_2d = (b_values[0:3], b_values[3:6], b_values[6:9]) expected = 6.22350000000000047606 result = wp.ddot(wp.mat33d(*a_values), wp.mat33d(*b_values)) self.assertAlmostEqual(result, expected, places=12) result = wp.ddot(wp.mat33f(*a_values), wp.mat33f(*b_values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.ddot(wp.mat33h(*a_values), wp.mat33h(*b_values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.ddot(a_values, b_values), wp.ddot(wp.mat33f(*a_values), wp.mat33f(*b_values))) self.assertEqual(wp.ddot(a_values_2d, b_values_2d), wp.ddot(wp.mat33f(*a_values), wp.mat33f(*b_values))) self.assertEqual(wp.ddot(a_values, b_values_2d), wp.ddot(wp.mat33f(*a_values), wp.mat33f(*b_values))) self.assertEqual(wp.ddot(a_values_2d, b_values), wp.ddot(wp.mat33f(*a_values), wp.mat33f(*b_values))) def test_mat44_mat44_args(self): a_values = (0.12, 1.23, 2.34, 3.45, 0.12, 1.23, 2.34, 3.45, 0.12, 1.23, 2.34, 3.45, 0.12, 1.23, 2.34, 3.45) a_values_2d = (a_values[0:4], a_values[4:8], a_values[8:12], a_values[12:16]) b_values = (3.45, 2.34, 1.23, 0.12, 3.45, 2.34, 1.23, 0.12, 3.45, 2.34, 1.23, 0.12, 3.45, 2.34, 1.23, 0.12) b_values_2d = (b_values[0:4], b_values[4:8], b_values[8:12], b_values[12:16]) expected = 26.33760000000000189857 result = wp.ddot(wp.mat44d(*a_values), wp.mat44d(*b_values)) self.assertAlmostEqual(result, expected, places=12) result = wp.ddot(wp.mat44f(*a_values), wp.mat44f(*b_values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.ddot(wp.mat44h(*a_values), wp.mat44h(*b_values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.ddot(a_values, b_values), wp.ddot(wp.mat44f(*a_values), wp.mat44f(*b_values))) self.assertEqual(wp.ddot(a_values_2d, b_values_2d), wp.ddot(wp.mat44f(*a_values), wp.mat44f(*b_values))) self.assertEqual(wp.ddot(a_values, b_values_2d), wp.ddot(wp.mat44f(*a_values), wp.mat44f(*b_values))) self.assertEqual(wp.ddot(a_values_2d, b_values), wp.ddot(wp.mat44f(*a_values), wp.mat44f(*b_values))) def test_mat22_float_args_precision(self): a_values = (1.23, 2.34, 3.45, 4.56) a_values_2d = (a_values[0:2], a_values[2:4]) b_value = 0.12 expected_00 = 0.14759999999999998122 expected_01 = 0.28079999999999999405 expected_10 = 0.41399999999999997913 expected_11 = 0.54719999999999990870 result = wp.mul(wp.mat22d(*a_values), wp.float64(b_value)) self.assertAlmostEqual(result[0][0], expected_00, places=12) self.assertAlmostEqual(result[0][1], expected_01, places=12) self.assertAlmostEqual(result[1][0], expected_10, places=12) self.assertAlmostEqual(result[1][1], expected_11, places=12) result = wp.mul(wp.mat22f(*a_values), wp.float32(b_value)) self.assertNotAlmostEqual(result[0][0], expected_00, places=12) self.assertNotAlmostEqual(result[0][1], expected_01, places=12) self.assertNotAlmostEqual(result[1][0], expected_10, places=12) self.assertNotAlmostEqual(result[1][1], expected_11, places=12) self.assertAlmostEqual(result[0][0], expected_00, places=5) self.assertAlmostEqual(result[0][1], expected_01, places=5) self.assertAlmostEqual(result[1][0], expected_10, places=5) self.assertAlmostEqual(result[1][1], expected_11, places=5) result = wp.mul(wp.mat22h(*a_values), wp.float16(b_value)) self.assertNotAlmostEqual(result[0][0], expected_00, places=5) self.assertNotAlmostEqual(result[0][1], expected_01, places=5) self.assertNotAlmostEqual(result[1][0], expected_10, places=5) self.assertNotAlmostEqual(result[1][1], expected_11, places=5) self.assertAlmostEqual(result[0][0], expected_00, places=1) self.assertAlmostEqual(result[0][1], expected_01, places=1) self.assertAlmostEqual(result[1][0], expected_10, places=1) self.assertAlmostEqual(result[1][1], expected_11, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): # Multiplying a 1-D tuple of length 4 is ambiguous because it could match # either the `vec4f` or `mat22f` overload. As a result, only the 2-D variant # of the tuple is expected to resolve correctly. self.assertEqual(wp.mul(a_values_2d, b_value), wp.mul(wp.mat22f(*a_values), wp.float32(b_value))) def test_mat33_float_args_precision(self): a_values = (1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01) a_values_2d = (a_values[0:3], a_values[3:6], a_values[6:9]) b_value = 0.12 expected_00 = 0.14759999999999998122 expected_01 = 0.28079999999999999405 expected_02 = 0.41399999999999997913 expected_10 = 0.54719999999999990870 expected_11 = 0.68040000000000000480 expected_12 = 0.81359999999999998987 expected_20 = 0.94679999999999997495 expected_21 = 1.06800000000000006040 expected_22 = 1.08119999999999993889 result = wp.mul(wp.mat33d(*a_values), wp.float64(b_value)) self.assertAlmostEqual(result[0][0], expected_00, places=12) self.assertAlmostEqual(result[0][1], expected_01, places=12) self.assertAlmostEqual(result[0][2], expected_02, places=12) self.assertAlmostEqual(result[1][0], expected_10, places=12) self.assertAlmostEqual(result[1][1], expected_11, places=12) self.assertAlmostEqual(result[1][2], expected_12, places=12) self.assertAlmostEqual(result[2][0], expected_20, places=12) self.assertAlmostEqual(result[2][1], expected_21, places=12) self.assertAlmostEqual(result[2][2], expected_22, places=12) result = wp.mul(wp.mat33f(*a_values), wp.float32(b_value)) self.assertNotAlmostEqual(result[0][0], expected_00, places=12) self.assertNotAlmostEqual(result[0][1], expected_01, places=12) self.assertNotAlmostEqual(result[0][2], expected_02, places=12) self.assertNotAlmostEqual(result[1][0], expected_10, places=12) self.assertNotAlmostEqual(result[1][1], expected_11, places=12) self.assertNotAlmostEqual(result[1][2], expected_12, places=12) self.assertNotAlmostEqual(result[2][0], expected_20, places=12) self.assertNotAlmostEqual(result[2][1], expected_21, places=12) self.assertNotAlmostEqual(result[2][2], expected_22, places=12) self.assertAlmostEqual(result[0][0], expected_00, places=5) self.assertAlmostEqual(result[0][1], expected_01, places=5) self.assertAlmostEqual(result[0][2], expected_02, places=5) self.assertAlmostEqual(result[1][0], expected_10, places=5) self.assertAlmostEqual(result[1][1], expected_11, places=5) self.assertAlmostEqual(result[1][2], expected_12, places=5) self.assertAlmostEqual(result[2][0], expected_20, places=5) self.assertAlmostEqual(result[2][1], expected_21, places=5) self.assertAlmostEqual(result[2][2], expected_22, places=5) result = wp.mul(wp.mat33h(*a_values), wp.float16(b_value)) self.assertNotAlmostEqual(result[0][0], expected_00, places=5) self.assertNotAlmostEqual(result[0][1], expected_01, places=5) self.assertNotAlmostEqual(result[0][2], expected_02, places=5) self.assertNotAlmostEqual(result[1][0], expected_10, places=5) self.assertNotAlmostEqual(result[1][1], expected_11, places=5) self.assertNotAlmostEqual(result[1][2], expected_12, places=5) self.assertNotAlmostEqual(result[2][0], expected_20, places=5) self.assertNotAlmostEqual(result[2][1], expected_21, places=5) self.assertNotAlmostEqual(result[2][2], expected_22, places=5) self.assertAlmostEqual(result[0][0], expected_00, places=1) self.assertAlmostEqual(result[0][1], expected_01, places=1) self.assertAlmostEqual(result[0][2], expected_02, places=1) self.assertAlmostEqual(result[1][0], expected_10, places=1) self.assertAlmostEqual(result[1][1], expected_11, places=1) self.assertAlmostEqual(result[1][2], expected_12, places=1) self.assertAlmostEqual(result[2][0], expected_20, places=1) self.assertAlmostEqual(result[2][1], expected_21, places=1) self.assertAlmostEqual(result[2][2], expected_22, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.mul(a_values, b_value), wp.mul(wp.mat33f(*a_values), wp.float32(b_value))) self.assertEqual(wp.mul(a_values_2d, b_value), wp.mul(wp.mat33f(*a_values), wp.float32(b_value))) def test_mat44_float_args_precision(self): a_values = ( 1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01, 10.12, 11.23, 12.34, 13.45, 14.56, 15.67, 16.78, ) a_values_2d = (a_values[0:4], a_values[4:8], a_values[8:12], a_values[12:16]) b_value = 0.12 expected_00 = 0.14759999999999998122 expected_01 = 0.28079999999999999405 expected_02 = 0.41399999999999997913 expected_03 = 0.54719999999999990870 expected_10 = 0.68040000000000000480 expected_11 = 0.81359999999999998987 expected_12 = 0.94679999999999997495 expected_13 = 1.06800000000000006040 expected_20 = 1.08119999999999993889 expected_21 = 1.21439999999999992397 expected_22 = 1.34759999999999990905 expected_23 = 1.48079999999999989413 expected_30 = 1.61399999999999987921 expected_31 = 1.74720000000000008633 expected_32 = 1.88039999999999984936 expected_33 = 2.01360000000000027853 result = wp.mul(wp.mat44d(*a_values), wp.float64(b_value)) self.assertAlmostEqual(result[0][0], expected_00, places=12) self.assertAlmostEqual(result[0][1], expected_01, places=12) self.assertAlmostEqual(result[0][2], expected_02, places=12) self.assertAlmostEqual(result[0][3], expected_03, places=12) self.assertAlmostEqual(result[1][0], expected_10, places=12) self.assertAlmostEqual(result[1][1], expected_11, places=12) self.assertAlmostEqual(result[1][2], expected_12, places=12) self.assertAlmostEqual(result[1][3], expected_13, places=12) self.assertAlmostEqual(result[2][0], expected_20, places=12) self.assertAlmostEqual(result[2][1], expected_21, places=12) self.assertAlmostEqual(result[2][2], expected_22, places=12) self.assertAlmostEqual(result[2][3], expected_23, places=12) self.assertAlmostEqual(result[3][0], expected_30, places=12) self.assertAlmostEqual(result[3][1], expected_31, places=12) self.assertAlmostEqual(result[3][2], expected_32, places=12) self.assertAlmostEqual(result[3][3], expected_33, places=12) result = wp.mul(wp.mat44f(*a_values), wp.float32(b_value)) self.assertNotAlmostEqual(result[0][0], expected_00, places=12) self.assertNotAlmostEqual(result[0][1], expected_01, places=12) self.assertNotAlmostEqual(result[0][2], expected_02, places=12) self.assertNotAlmostEqual(result[0][3], expected_03, places=12) self.assertNotAlmostEqual(result[1][0], expected_10, places=12) self.assertNotAlmostEqual(result[1][1], expected_11, places=12) self.assertNotAlmostEqual(result[1][2], expected_12, places=12) self.assertNotAlmostEqual(result[1][3], expected_13, places=12) self.assertNotAlmostEqual(result[2][0], expected_20, places=12) self.assertNotAlmostEqual(result[2][1], expected_21, places=12) self.assertNotAlmostEqual(result[2][2], expected_22, places=12) self.assertNotAlmostEqual(result[2][3], expected_23, places=12) self.assertNotAlmostEqual(result[3][0], expected_30, places=12) self.assertNotAlmostEqual(result[3][1], expected_31, places=12) self.assertNotAlmostEqual(result[3][2], expected_32, places=12) self.assertNotAlmostEqual(result[3][3], expected_33, places=12) self.assertAlmostEqual(result[0][0], expected_00, places=5) self.assertAlmostEqual(result[0][1], expected_01, places=5) self.assertAlmostEqual(result[0][2], expected_02, places=5) self.assertAlmostEqual(result[0][3], expected_03, places=5) self.assertAlmostEqual(result[1][0], expected_10, places=5) self.assertAlmostEqual(result[1][1], expected_11, places=5) self.assertAlmostEqual(result[1][2], expected_12, places=5) self.assertAlmostEqual(result[1][3], expected_13, places=5) self.assertAlmostEqual(result[2][0], expected_20, places=5) self.assertAlmostEqual(result[2][1], expected_21, places=5) self.assertAlmostEqual(result[2][2], expected_22, places=5) self.assertAlmostEqual(result[2][3], expected_23, places=5) self.assertAlmostEqual(result[3][0], expected_30, places=5) self.assertAlmostEqual(result[3][1], expected_31, places=5) self.assertAlmostEqual(result[3][2], expected_32, places=5) self.assertAlmostEqual(result[3][3], expected_33, places=5) result = wp.mul(wp.mat44h(*a_values), wp.float16(b_value)) self.assertNotAlmostEqual(result[0][0], expected_00, places=5) self.assertNotAlmostEqual(result[0][1], expected_01, places=5) self.assertNotAlmostEqual(result[0][2], expected_02, places=5) self.assertNotAlmostEqual(result[0][3], expected_03, places=5) self.assertNotAlmostEqual(result[1][0], expected_10, places=5) self.assertNotAlmostEqual(result[1][1], expected_11, places=5) self.assertNotAlmostEqual(result[1][2], expected_12, places=5) self.assertNotAlmostEqual(result[1][3], expected_13, places=5) self.assertNotAlmostEqual(result[2][0], expected_20, places=5) self.assertNotAlmostEqual(result[2][1], expected_21, places=5) self.assertNotAlmostEqual(result[2][2], expected_22, places=5) self.assertNotAlmostEqual(result[2][3], expected_23, places=5) self.assertNotAlmostEqual(result[3][0], expected_30, places=5) self.assertNotAlmostEqual(result[3][1], expected_31, places=5) self.assertNotAlmostEqual(result[3][2], expected_32, places=5) self.assertNotAlmostEqual(result[3][3], expected_33, places=5) self.assertAlmostEqual(result[0][0], expected_00, places=1) self.assertAlmostEqual(result[0][1], expected_01, places=1) self.assertAlmostEqual(result[0][2], expected_02, places=1) self.assertAlmostEqual(result[0][3], expected_03, places=1) self.assertAlmostEqual(result[1][0], expected_10, places=1) self.assertAlmostEqual(result[1][1], expected_11, places=1) self.assertAlmostEqual(result[1][2], expected_12, places=1) self.assertAlmostEqual(result[1][3], expected_13, places=1) self.assertAlmostEqual(result[2][0], expected_20, places=1) self.assertAlmostEqual(result[2][1], expected_21, places=1) self.assertAlmostEqual(result[2][2], expected_22, places=1) self.assertAlmostEqual(result[2][3], expected_23, places=1) self.assertAlmostEqual(result[3][0], expected_30, places=1) self.assertAlmostEqual(result[3][1], expected_31, places=1) self.assertAlmostEqual(result[3][2], expected_32, places=1) self.assertAlmostEqual(result[3][3], expected_33, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.mul(a_values, b_value), wp.mul(wp.mat44f(*a_values), wp.float32(b_value))) self.assertEqual(wp.mul(a_values_2d, b_value), wp.mul(wp.mat44f(*a_values), wp.float32(b_value))) def test_vec2_arg_precision(self): values = (1.23, 2.34) expected = 2.64357712200722438922 result = wp.length(wp.vec2d(*values)) self.assertAlmostEqual(result, expected, places=12) result = wp.length(wp.vec2f(*values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.length(wp.vec2h(*values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.length(values), wp.length(wp.vec2f(*values))) def test_vec2_arg_overflow(self): values = (-1234567890, -1234567890) self.assertEqual(wp.length_sq(wp.vec2b(*values)), -120) self.assertEqual(wp.length_sq(wp.vec2s(*values)), -6008) self.assertEqual(wp.length_sq(wp.vec2i(*values)), 608168072) self.assertEqual(wp.length_sq(wp.vec2l(*values)), 3048315750038104200) self.assertEqual(wp.length_sq(wp.vec2ub(*values)), 136) self.assertEqual(wp.length_sq(wp.vec2us(*values)), 59528) self.assertEqual(wp.length_sq(wp.vec2ui(*values)), 608168072) self.assertEqual(wp.length_sq(wp.vec2ul(*values)), 3048315750038104200) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.length_sq(values), wp.length_sq(wp.vec2i(*values))) def test_vec3_arg_precision(self): values = (1.23, 2.34, 3.45) expected = 4.34637780226247727455 result = wp.length(wp.vec3d(*values)) self.assertAlmostEqual(result, expected, places=12) result = wp.length(wp.vec3f(*values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.length(wp.vec3h(*values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.length(values), wp.length(wp.vec3f(*values))) def test_vec3_arg_overflow(self): values = (-1234567890, -1234567890, -1234567890) self.assertEqual(wp.length_sq(wp.vec3b(*values)), -52) self.assertEqual(wp.length_sq(wp.vec3s(*values)), -9012) self.assertEqual(wp.length_sq(wp.vec3i(*values)), 912252108) self.assertEqual(wp.length_sq(wp.vec3l(*values)), 4572473625057156300) self.assertEqual(wp.length_sq(wp.vec3ub(*values)), 204) self.assertEqual(wp.length_sq(wp.vec3us(*values)), 56524) self.assertEqual(wp.length_sq(wp.vec3ui(*values)), 912252108) self.assertEqual(wp.length_sq(wp.vec3ul(*values)), 4572473625057156300) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.length_sq(values), wp.length_sq(wp.vec3i(*values))) def test_vec4_arg_precision(self): values = (1.23, 2.34, 3.45, 4.56) expected = 6.29957141399317777086 result = wp.length(wp.vec4d(*values)) self.assertAlmostEqual(result, expected, places=12) result = wp.length(wp.vec4f(*values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.length(wp.vec4h(*values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.length(values), wp.length(wp.vec4f(*values))) def test_vec4_arg_overflow(self): values = (-1234567890, -1234567890, -1234567890, -1234567890) self.assertEqual(wp.length_sq(wp.vec4b(*values)), 16) self.assertEqual(wp.length_sq(wp.vec4s(*values)), -12016) self.assertEqual(wp.length_sq(wp.vec4i(*values)), 1216336144) self.assertEqual(wp.length_sq(wp.vec4l(*values)), 6096631500076208400) self.assertEqual(wp.length_sq(wp.vec4ub(*values)), 16) self.assertEqual(wp.length_sq(wp.vec4us(*values)), 53520) self.assertEqual(wp.length_sq(wp.vec4ui(*values)), 1216336144) self.assertEqual(wp.length_sq(wp.vec4ul(*values)), 6096631500076208400) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.length_sq(values), wp.length_sq(wp.vec4i(*values))) def test_vec2_vec2_args_precision(self): a_values = (1.23, 2.34) b_values = (3.45, 4.56) expected = 14.91389999999999815827 result = wp.dot(wp.vec2d(*a_values), wp.vec2d(*b_values)) self.assertAlmostEqual(result, expected, places=12) result = wp.dot(wp.vec2f(*a_values), wp.vec2f(*b_values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.dot(wp.vec2h(*a_values), wp.vec2h(*b_values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.dot(a_values, b_values), wp.dot(wp.vec2f(*a_values), wp.vec2f(*b_values))) def test_vec2_vec2_args_overflow(self): values = (-1234567890, -1234567890) self.assertEqual(wp.dot(wp.vec2b(*values), wp.vec2b(*values)), -120) self.assertEqual(wp.dot(wp.vec2s(*values), wp.vec2s(*values)), -6008) self.assertEqual(wp.dot(wp.vec2i(*values), wp.vec2i(*values)), 608168072) self.assertEqual(wp.dot(wp.vec2l(*values), wp.vec2l(*values)), 3048315750038104200) self.assertEqual(wp.dot(wp.vec2ub(*values), wp.vec2ub(*values)), 136) self.assertEqual(wp.dot(wp.vec2us(*values), wp.vec2us(*values)), 59528) self.assertEqual(wp.dot(wp.vec2ui(*values), wp.vec2ui(*values)), 608168072) self.assertEqual(wp.dot(wp.vec2ul(*values), wp.vec2ul(*values)), 3048315750038104200) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.dot(values, values), wp.dot(wp.vec2i(*values), wp.vec2i(*values))) def test_vec3_vec3_args_precision(self): a_values = (1.23, 2.34, 3.45) b_values = (4.56, 5.67, 6.78) expected = 42.26760000000000161435 result = wp.dot(wp.vec3d(*a_values), wp.vec3d(*b_values)) self.assertAlmostEqual(result, expected, places=12) result = wp.dot(wp.vec3f(*a_values), wp.vec3f(*b_values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.dot(wp.vec3h(*a_values), wp.vec3h(*b_values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.dot(a_values, b_values), wp.dot(wp.vec3f(*a_values), wp.vec3f(*b_values))) def test_vec3_vec3_args_overflow(self): values = (-1234567890, -1234567890, -1234567890) self.assertEqual(wp.dot(wp.vec3b(*values), wp.vec3b(*values)), -52) self.assertEqual(wp.dot(wp.vec3s(*values), wp.vec3s(*values)), -9012) self.assertEqual(wp.dot(wp.vec3i(*values), wp.vec3i(*values)), 912252108) self.assertEqual(wp.dot(wp.vec3l(*values), wp.vec3l(*values)), 4572473625057156300) self.assertEqual(wp.dot(wp.vec3ub(*values), wp.vec3ub(*values)), 204) self.assertEqual(wp.dot(wp.vec3us(*values), wp.vec3us(*values)), 56524) self.assertEqual(wp.dot(wp.vec3ui(*values), wp.vec3ui(*values)), 912252108) self.assertEqual(wp.dot(wp.vec3ul(*values), wp.vec3ul(*values)), 4572473625057156300) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.dot(values, values), wp.dot(wp.vec3i(*values), wp.vec3i(*values))) def test_vec4_vec4_args_precision(self): a_values = (1.23, 2.34, 3.45, 4.56) b_values = (5.67, 6.78, 7.89, 8.90) expected = 90.64379999999999881766 result = wp.dot(wp.vec4d(*a_values), wp.vec4d(*b_values)) self.assertAlmostEqual(result, expected, places=12) result = wp.dot(wp.vec4f(*a_values), wp.vec4f(*b_values)) self.assertNotAlmostEqual(result, expected, places=12) self.assertAlmostEqual(result, expected, places=5) result = wp.dot(wp.vec4h(*a_values), wp.vec4h(*b_values)) self.assertNotAlmostEqual(result, expected, places=5) self.assertAlmostEqual(result, expected, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.dot(a_values, b_values), wp.dot(wp.vec4f(*a_values), wp.vec4f(*b_values))) def test_vec4_vec4_args_overflow(self): values = (-1234567890, -1234567890, -1234567890, -1234567890) self.assertEqual(wp.dot(wp.vec4b(*values), wp.vec4b(*values)), 16) self.assertEqual(wp.dot(wp.vec4s(*values), wp.vec4s(*values)), -12016) self.assertEqual(wp.dot(wp.vec4i(*values), wp.vec4i(*values)), 1216336144) self.assertEqual(wp.dot(wp.vec4l(*values), wp.vec4l(*values)), 6096631500076208400) self.assertEqual(wp.dot(wp.vec4ub(*values), wp.vec4ub(*values)), 16) self.assertEqual(wp.dot(wp.vec4us(*values), wp.vec4us(*values)), 53520) self.assertEqual(wp.dot(wp.vec4ui(*values), wp.vec4ui(*values)), 1216336144) self.assertEqual(wp.dot(wp.vec4ul(*values), wp.vec4ul(*values)), 6096631500076208400) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.dot(values, values), wp.dot(wp.vec4i(*values), wp.vec4i(*values))) def test_vec2_float_args_precision(self): a_values = (1.23, 2.34) b_value = 3.45 expected_x = 4.24350000000000004974 expected_y = 8.07300000000000039790 result = wp.mul(wp.vec2d(*a_values), wp.float64(b_value)) self.assertAlmostEqual(result[0], expected_x, places=12) self.assertAlmostEqual(result[1], expected_y, places=12) result = wp.mul(wp.vec2f(*a_values), wp.float32(b_value)) self.assertNotAlmostEqual(result[0], expected_x, places=12) self.assertNotAlmostEqual(result[1], expected_y, places=12) self.assertAlmostEqual(result[0], expected_x, places=5) self.assertAlmostEqual(result[1], expected_y, places=5) result = wp.mul(wp.vec2h(*a_values), wp.float16(b_value)) self.assertNotAlmostEqual(result[0], expected_x, places=5) self.assertNotAlmostEqual(result[1], expected_y, places=5) self.assertAlmostEqual(result[0], expected_x, places=1) self.assertAlmostEqual(result[1], expected_y, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.mul(a_values, b_value), wp.mul(wp.vec2f(*a_values), wp.float32(b_value))) def test_vec3_float_args_precision(self): a_values = (1.23, 2.34, 3.45) b_value = 4.56 expected_x = 5.60879999999999956373 expected_y = 10.67039999999999899671 expected_z = 15.73199999999999931788 result = wp.mul(wp.vec3d(*a_values), wp.float64(b_value)) self.assertAlmostEqual(result[0], expected_x, places=12) self.assertAlmostEqual(result[1], expected_y, places=12) self.assertAlmostEqual(result[2], expected_z, places=12) result = wp.mul(wp.vec3f(*a_values), wp.float32(b_value)) self.assertNotAlmostEqual(result[0], expected_x, places=12) self.assertNotAlmostEqual(result[1], expected_y, places=12) self.assertNotAlmostEqual(result[2], expected_z, places=12) self.assertAlmostEqual(result[0], expected_x, places=5) self.assertAlmostEqual(result[1], expected_y, places=5) self.assertAlmostEqual(result[2], expected_z, places=5) result = wp.mul(wp.vec3h(*a_values), wp.float16(b_value)) self.assertNotAlmostEqual(result[0], expected_x, places=5) self.assertNotAlmostEqual(result[1], expected_y, places=5) self.assertNotAlmostEqual(result[2], expected_z, places=5) self.assertAlmostEqual(result[0], expected_x, places=1) self.assertAlmostEqual(result[1], expected_y, places=1) self.assertAlmostEqual(result[2], expected_z, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.mul(a_values, b_value), wp.mul(wp.vec3f(*a_values), wp.float32(b_value))) def test_vec4_float_args_precision(self): a_values = (1.23, 2.34, 3.45, 4.56) b_value = 5.67 expected_x = 6.97409999999999996589 expected_y = 13.26779999999999937188 expected_z = 19.56150000000000233058 expected_w = 25.85519999999999640750 result = wp.mul(wp.vec4d(*a_values), wp.float64(b_value)) self.assertAlmostEqual(result[0], expected_x, places=12) self.assertAlmostEqual(result[1], expected_y, places=12) self.assertAlmostEqual(result[2], expected_z, places=12) self.assertAlmostEqual(result[3], expected_w, places=12) result = wp.mul(wp.vec4f(*a_values), wp.float32(b_value)) self.assertNotAlmostEqual(result[0], expected_x, places=12) self.assertNotAlmostEqual(result[1], expected_y, places=12) self.assertNotAlmostEqual(result[2], expected_z, places=12) self.assertNotAlmostEqual(result[3], expected_w, places=12) self.assertAlmostEqual(result[0], expected_x, places=5) self.assertAlmostEqual(result[1], expected_y, places=5) self.assertAlmostEqual(result[2], expected_z, places=5) self.assertAlmostEqual(result[3], expected_w, places=5) result = wp.mul(wp.vec4h(*a_values), wp.float16(b_value)) self.assertNotAlmostEqual(result[0], expected_x, places=5) self.assertNotAlmostEqual(result[1], expected_y, places=5) self.assertNotAlmostEqual(result[2], expected_z, places=5) self.assertNotAlmostEqual(result[3], expected_w, places=5) self.assertAlmostEqual(result[0], expected_x, places=1) self.assertAlmostEqual(result[1], expected_y, places=1) self.assertAlmostEqual(result[2], expected_z, places=1) self.assertAlmostEqual(result[3], expected_w, places=1) with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): self.assertEqual(wp.mul(a_values, b_value), wp.mul(wp.vec4f(*a_values), wp.float32(b_value))) for dtype in wp.types.int_types: add_function_test( TestBuiltinsResolution, f"test_int_arg_support_{dtype.__name__}", test_int_arg_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_int_int_args_support_{dtype.__name__}", test_int_int_args_support, dtype=dtype, ) for dtype in wp.types.float_types: add_function_test( TestBuiltinsResolution, f"test_float_arg_support_{dtype.__name__}", test_float_arg_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_mat_arg_support_{dtype.__name__}", test_mat_arg_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_mat_mat_args_support_{dtype.__name__}", test_mat_mat_args_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_mat_float_args_support_{dtype.__name__}", test_mat_float_args_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_vec_arg_support_{dtype.__name__}", test_vec_arg_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_vec_vec_args_support_{dtype.__name__}", test_vec_vec_args_support, dtype=dtype, ) add_function_test( TestBuiltinsResolution, f"test_vec_float_args_support_{dtype.__name__}", test_vec_float_args_support, dtype=dtype, ) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
63,995
Python
48.570875
120
0.632503
NVIDIA/warp/warp/tests/test_hash_grid.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * num_points = 4096 dim_x = 128 dim_y = 128 dim_z = 128 scale = 150.0 cell_radius = 8.0 query_radius = 8.0 num_runs = 4 print_enabled = False @wp.kernel def count_neighbors(grid: wp.uint64, radius: float, points: wp.array(dtype=wp.vec3), counts: wp.array(dtype=int)): tid = wp.tid() # order threads by cell i = wp.hash_grid_point_id(grid, tid) # query point p = points[i] count = int(0) # construct query around point p for index in wp.hash_grid_query(grid, p, radius): # compute distance to point d = wp.length(p - points[index]) if d <= radius: count += 1 counts[i] = count @wp.kernel def count_neighbors_reference( radius: float, points: wp.array(dtype=wp.vec3), counts: wp.array(dtype=int), num_points: int ): tid = wp.tid() i = tid % num_points j = tid // num_points # query point p = points[i] q = points[j] # compute distance to point d = wp.length(p - q) if d <= radius: wp.atomic_add(counts, i, 1) def particle_grid(dim_x, dim_y, dim_z, lower, radius, jitter): rng = np.random.default_rng(123) points = np.meshgrid(np.linspace(0, dim_x, dim_x), np.linspace(0, dim_y, dim_y), np.linspace(0, dim_z, dim_z)) points_t = np.array((points[0], points[1], points[2])).T * radius * 2.0 + np.array(lower) points_t = points_t + rng.random(size=points_t.shape) * radius * jitter return points_t.reshape((-1, 3)) def test_hashgrid_query(test, device): wp.load_module(device=device) grid = wp.HashGrid(dim_x, dim_y, dim_z, device) for i in range(num_runs): if print_enabled: print(f"Run: {i+1}") print("---------") points = particle_grid(16, 32, 16, (0.0, 0.3, 0.0), cell_radius * 0.25, 0.1) points_arr = wp.array(points, dtype=wp.vec3, device=device) counts_arr = wp.zeros(len(points), dtype=int, device=device) counts_arr_ref = wp.zeros(len(points), dtype=int, device=device) profiler = {} with wp.ScopedTimer("grid operations", print=print_enabled, dict=profiler, synchronize=True): with wp.ScopedTimer("brute", print=print_enabled, dict=profiler, synchronize=True): wp.launch( kernel=count_neighbors_reference, dim=len(points) * len(points), inputs=[query_radius, points_arr, counts_arr_ref, len(points)], device=device, ) wp.synchronize_device(device) with wp.ScopedTimer("grid build", print=print_enabled, dict=profiler, synchronize=True): grid.build(points_arr, cell_radius) with wp.ScopedTimer("grid query", print=print_enabled, dict=profiler, synchronize=True): wp.launch( kernel=count_neighbors, dim=len(points), inputs=[grid.id, query_radius, points_arr, counts_arr], device=device, ) counts = counts_arr.numpy() counts_ref = counts_arr_ref.numpy() if print_enabled: print(f"Grid min: {np.min(counts)} max: {np.max(counts)} avg: {np.mean(counts)}") print(f"Ref min: {np.min(counts_ref)} max: {np.max(counts_ref)} avg: {np.mean(counts_ref)}") print(f"Passed: {np.array_equal(counts, counts_ref)}") assert_np_equal(counts, counts_ref) def test_hashgrid_inputs(test, device): points = particle_grid(16, 32, 16, (0.0, 0.3, 0.0), cell_radius * 0.25, 0.1) points_ref = wp.array(points, dtype=wp.vec3, device=device) counts_ref = wp.zeros(len(points), dtype=int, device=device) grid = wp.HashGrid(dim_x, dim_y, dim_z, device) grid.build(points_ref, cell_radius) # get reference counts wp.launch( kernel=count_neighbors, dim=len(points), inputs=[grid.id, query_radius, points_ref, counts_ref], device=device ) # test with strided 1d input arrays for stride in [2, 3]: with test.subTest(msg=f"stride_{stride}"): points_buffer = wp.zeros(len(points) * stride, dtype=wp.vec3, device=device) points_strided = points_buffer[::stride] wp.copy(points_strided, points_ref) counts_strided = wp.zeros(len(points), dtype=int, device=device) grid = wp.HashGrid(dim_x, dim_y, dim_z, device) grid.build(points_strided, cell_radius) wp.launch( kernel=count_neighbors, dim=len(points), inputs=[grid.id, query_radius, points_ref, counts_strided], device=device, ) assert_array_equal(counts_strided, counts_ref) # test with multidimensional input arrays for ndim in [2, 3, 4]: with test.subTest(msg=f"ndim_{ndim}"): shape = (len(points) // (2 ** (ndim - 1)), *((ndim - 1) * (2,))) points_ndim = wp.zeros(shape, dtype=wp.vec3, device=device) wp.copy(points_ndim, points_ref) counts_ndim = wp.zeros(len(points), dtype=int, device=device) grid = wp.HashGrid(dim_x, dim_y, dim_z, device) grid.build(points_ndim, cell_radius) wp.launch( kernel=count_neighbors, dim=len(points), inputs=[grid.id, query_radius, points_ref, counts_ndim], device=device, ) assert_array_equal(counts_ndim, counts_ref) devices = get_test_devices() class TestHashGrid(unittest.TestCase): def test_hashgrid_codegen_adjoints_with_select(self): def kernel_fn(grid: wp.uint64): v = wp.vec3(0.0, 0.0, 0.0) if True: query = wp.hash_grid_query(grid, v, 0.0) else: query = wp.hash_grid_query(grid, v, 0.0) wp.Kernel(func=kernel_fn) add_function_test(TestHashGrid, "test_hashgrid_query", test_hashgrid_query, devices=devices) add_function_test(TestHashGrid, "test_hashgrid_inputs", test_hashgrid_inputs, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
6,741
Python
31.258373
118
0.598873
NVIDIA/warp/warp/tests/test_peer.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp from warp.tests.unittest_utils import * def get_device_pair_with_peer_access_support(): devices = wp.get_cuda_devices() for target_device in devices: for peer_device in devices: if target_device != peer_device: if wp.is_peer_access_supported(target_device, peer_device): return (target_device, peer_device) return None def get_device_pair_without_peer_access_support(): devices = wp.get_cuda_devices() for target_device in devices: for peer_device in devices: if target_device != peer_device: if not wp.is_peer_access_supported(target_device, peer_device): return (target_device, peer_device) return None def test_peer_access_self(test, device): device = wp.get_device(device) assert device.is_cuda # device can access self can_access = wp.is_peer_access_supported(device, device) test.assertTrue(can_access) # setting peer access to self is a no-op wp.set_peer_access_enabled(device, device, True) wp.set_peer_access_enabled(device, device, False) # should always be enabled enabled = wp.is_peer_access_enabled(device, device) test.assertTrue(enabled) @unittest.skipUnless(get_device_pair_with_peer_access_support(), "Requires devices with peer access support") def test_peer_access(test, _): target_device, peer_device = get_device_pair_with_peer_access_support() was_enabled = wp.is_peer_access_enabled(target_device, peer_device) if was_enabled: # try disabling wp.set_peer_access_enabled(target_device, peer_device, False) is_enabled = wp.is_peer_access_enabled(target_device, peer_device) test.assertFalse(is_enabled) # try re-enabling wp.set_peer_access_enabled(target_device, peer_device, True) is_enabled = wp.is_peer_access_enabled(target_device, peer_device) test.assertTrue(is_enabled) else: # try enabling wp.set_peer_access_enabled(target_device, peer_device, True) is_enabled = wp.is_peer_access_enabled(target_device, peer_device) test.assertTrue(is_enabled) # try re-disabling wp.set_peer_access_enabled(target_device, peer_device, False) is_enabled = wp.is_peer_access_enabled(target_device, peer_device) test.assertFalse(is_enabled) @unittest.skipUnless(get_device_pair_without_peer_access_support(), "Requires devices without peer access support") def test_peer_access_exceptions_unsupported(test, _): # get a CUDA device pair without peer access support target_device, peer_device = get_device_pair_without_peer_access_support() # querying is ok, but must return False test.assertFalse(wp.is_peer_access_enabled(target_device, peer_device)) # enabling should raise RuntimeError with test.assertRaises(RuntimeError): wp.set_peer_access_enabled(target_device, peer_device, True) # disabling should not raise an error wp.set_peer_access_enabled(target_device, peer_device, False) @unittest.skipUnless(wp.is_cpu_available() and wp.is_cuda_available(), "Requires both CUDA and CPU devices") def test_peer_access_exceptions_cpu(test, _): # querying is ok, but must return False test.assertFalse(wp.is_peer_access_enabled("cuda:0", "cpu")) test.assertFalse(wp.is_peer_access_enabled("cpu", "cuda:0")) # enabling should raise ValueError with test.assertRaises(ValueError): wp.set_peer_access_enabled("cpu", "cuda:0", True) with test.assertRaises(ValueError): wp.set_peer_access_enabled("cuda:0", "cpu", True) # disabling should not raise an error wp.set_peer_access_enabled("cpu", "cuda:0", False) wp.set_peer_access_enabled("cuda:0", "cpu", False) class TestPeer(unittest.TestCase): pass cuda_test_devices = get_cuda_test_devices() add_function_test(TestPeer, "test_peer_access_self", test_peer_access_self, devices=cuda_test_devices) # peer access tests add_function_test(TestPeer, "test_peer_access", test_peer_access) # peer access exceptions add_function_test(TestPeer, "test_peer_access_exceptions_unsupported", test_peer_access_exceptions_unsupported) add_function_test(TestPeer, "test_peer_access_exceptions_cpu", test_peer_access_exceptions_cpu) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
4,873
Python
35.924242
115
0.704699
NVIDIA/warp/warp/tests/test_fem.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import math import unittest import numpy as np import warp as wp import warp.fem as fem from warp.fem import Coords, D, Domain, Field, Sample, curl, div, grad, integrand, normal from warp.fem.cache import dynamic_kernel from warp.fem.geometry import DeformedGeometry from warp.fem.geometry.closest_point import project_on_tet_at_origin, project_on_tri_at_origin from warp.fem.space import shape from warp.fem.types import make_free_sample from warp.fem.utils import grid_to_hexes, grid_to_quads, grid_to_tets, grid_to_tris from warp.tests.unittest_utils import * @integrand def linear_form(s: Sample, u: Field): return u(s) def test_integrate_gradient(test, device): with wp.ScopedDevice(device): # Grid geometry geo = fem.Grid2D(res=wp.vec2i(5)) # Domain and function spaces domain = fem.Cells(geometry=geo) quadrature = fem.RegularQuadrature(domain=domain, order=3) scalar_space = fem.make_polynomial_space(geo, degree=3) u = scalar_space.make_field() u.dof_values = wp.zeros_like(u.dof_values, requires_grad=True) result = wp.empty(dtype=wp.float64, shape=(1), requires_grad=True) tape = wp.Tape() # forward pass with tape: fem.integrate(linear_form, quadrature=quadrature, fields={"u": u}, output=result) tape.backward(result) test_field = fem.make_test(space=scalar_space, domain=domain) rhs = fem.integrate(linear_form, quadrature=quadrature, fields={"u": test_field}) err = np.linalg.norm(rhs.numpy() - u.dof_values.grad.numpy()) test.assertLess(err, 1.0e-8) @fem.integrand def bilinear_field(s: fem.Sample, domain: fem.Domain): x = domain(s) return x[0] * x[1] @fem.integrand def grad_field(s: fem.Sample, p: fem.Field): return fem.grad(p, s) def test_interpolate_gradient(test, device): with wp.ScopedDevice(device): # Quad mesh with single element # so we can test gradient with respect to vertex positions positions = wp.array([[0.0, 0.0], [0.0, 2.0], [2.0, 0.0], [2.0, 2.0]], dtype=wp.vec2, requires_grad=True) quads = wp.array([[0, 2, 3, 1]], dtype=int) geo = fem.Quadmesh2D(quads, positions) # Quadratic scalar space scalar_space = fem.make_polynomial_space(geo, degree=2) # Point-based vector space # So we can test gradient with respect to inteprolation point position point_coords = wp.array([[[0.5, 0.5, 0.0]]], dtype=fem.Coords, requires_grad=True) interpolation_nodes = fem.PointBasisSpace( fem.ExplicitQuadrature(domain=fem.Cells(geo), points=point_coords, weights=wp.array([[1.0]], dtype=float)) ) vector_space = fem.make_collocated_function_space(interpolation_nodes, dtype=wp.vec2) # Initialize scalar field with known function scalar_field = scalar_space.make_field() scalar_field.dof_values.requires_grad = True fem.interpolate(bilinear_field, dest=scalar_field) # Interpolate gradient at center point vector_field = vector_space.make_field() vector_field.dof_values.requires_grad = True vector_field_restriction = fem.make_restriction(vector_field) tape = wp.Tape() with tape: fem.interpolate( grad_field, dest=vector_field_restriction, fields={"p": scalar_field}, kernel_options={"enable_backward": True}, ) assert_np_equal(vector_field.dof_values.numpy(), np.array([[1.0, 1.0]])) vector_field.dof_values.grad.assign([1.0, 0.0]) tape.backward() assert_np_equal(scalar_field.dof_values.grad.numpy(), np.array([0.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.5, 0.0])) assert_np_equal( geo.positions.grad.numpy(), np.array( [ [0.25, 0.25], [0.25, 0.25], [-0.25, -0.25], [-0.25, -0.25], ] ), ) assert_np_equal(point_coords.grad.numpy(), np.array([[[0.0, 2.0, 0.0]]])) tape.zero() scalar_field.dof_values.grad.zero_() geo.positions.grad.zero_() point_coords.grad.zero_() vector_field.dof_values.grad.assign([0.0, 1.0]) tape.backward() assert_np_equal(scalar_field.dof_values.grad.numpy(), np.array([0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.5, 0.0, 0.0])) assert_np_equal( geo.positions.grad.numpy(), np.array( [ [0.25, 0.25], [-0.25, -0.25], [0.25, 0.25], [-0.25, -0.25], ] ), ) assert_np_equal(point_coords.grad.numpy(), np.array([[[2.0, 0.0, 0.0]]])) @integrand def vector_divergence_form(s: Sample, u: Field, q: Field): return div(u, s) * q(s) @integrand def vector_grad_form(s: Sample, u: Field, q: Field): return wp.dot(u(s), grad(q, s)) @integrand def vector_boundary_form(domain: Domain, s: Sample, u: Field, q: Field): return wp.dot(u(s) * q(s), normal(domain, s)) def test_vector_divergence_theorem(test, device): rng = np.random.default_rng(123) with wp.ScopedDevice(device): # Grid geometry geo = fem.Grid2D(res=wp.vec2i(5)) # Domain and function spaces interior = fem.Cells(geometry=geo) boundary = fem.BoundarySides(geometry=geo) vector_space = fem.make_polynomial_space(geo, degree=2, dtype=wp.vec2) scalar_space = fem.make_polynomial_space(geo, degree=1, dtype=float) u = vector_space.make_field() u.dof_values = rng.random(size=(u.dof_values.shape[0], 2)) # Divergence theorem constant_one = scalar_space.make_field() constant_one.dof_values.fill_(1.0) interior_quadrature = fem.RegularQuadrature(domain=interior, order=vector_space.degree) boundary_quadrature = fem.RegularQuadrature(domain=boundary, order=vector_space.degree) div_int = fem.integrate( vector_divergence_form, quadrature=interior_quadrature, fields={"u": u, "q": constant_one}, kernel_options={"enable_backward": False}, ) boundary_int = fem.integrate( vector_boundary_form, quadrature=boundary_quadrature, fields={"u": u.trace(), "q": constant_one.trace()}, kernel_options={"enable_backward": False}, ) test.assertAlmostEqual(div_int, boundary_int, places=5) # Integration by parts q = scalar_space.make_field() q.dof_values = rng.random(size=q.dof_values.shape[0]) interior_quadrature = fem.RegularQuadrature(domain=interior, order=vector_space.degree + scalar_space.degree) boundary_quadrature = fem.RegularQuadrature(domain=boundary, order=vector_space.degree + scalar_space.degree) div_int = fem.integrate( vector_divergence_form, quadrature=interior_quadrature, fields={"u": u, "q": q}, kernel_options={"enable_backward": False}, ) grad_int = fem.integrate( vector_grad_form, quadrature=interior_quadrature, fields={"u": u, "q": q}, kernel_options={"enable_backward": False}, ) boundary_int = fem.integrate( vector_boundary_form, quadrature=boundary_quadrature, fields={"u": u.trace(), "q": q.trace()}, kernel_options={"enable_backward": False}, ) test.assertAlmostEqual(div_int + grad_int, boundary_int, places=5) @integrand def tensor_divergence_form(s: Sample, tau: Field, v: Field): return wp.dot(div(tau, s), v(s)) @integrand def tensor_grad_form(s: Sample, tau: Field, v: Field): return wp.ddot(wp.transpose(tau(s)), grad(v, s)) @integrand def tensor_boundary_form(domain: Domain, s: Sample, tau: Field, v: Field): return wp.dot(tau(s) * v(s), normal(domain, s)) def test_tensor_divergence_theorem(test, device): rng = np.random.default_rng(123) with wp.ScopedDevice(device): # Grid geometry geo = fem.Grid2D(res=wp.vec2i(5)) # Domain and function spaces interior = fem.Cells(geometry=geo) boundary = fem.BoundarySides(geometry=geo) tensor_space = fem.make_polynomial_space(geo, degree=2, dtype=wp.mat22) vector_space = fem.make_polynomial_space(geo, degree=1, dtype=wp.vec2) tau = tensor_space.make_field() tau.dof_values = rng.random(size=(tau.dof_values.shape[0], 2, 2)) # Divergence theorem constant_vec = vector_space.make_field() constant_vec.dof_values.fill_(wp.vec2(0.5, 2.0)) interior_quadrature = fem.RegularQuadrature(domain=interior, order=tensor_space.degree) boundary_quadrature = fem.RegularQuadrature(domain=boundary, order=tensor_space.degree) div_int = fem.integrate( tensor_divergence_form, quadrature=interior_quadrature, fields={"tau": tau, "v": constant_vec}, kernel_options={"enable_backward": False}, ) boundary_int = fem.integrate( tensor_boundary_form, quadrature=boundary_quadrature, fields={"tau": tau.trace(), "v": constant_vec.trace()}, kernel_options={"enable_backward": False}, ) test.assertAlmostEqual(div_int, boundary_int, places=5) # Integration by parts v = vector_space.make_field() v.dof_values = rng.random(size=(v.dof_values.shape[0], 2)) interior_quadrature = fem.RegularQuadrature(domain=interior, order=tensor_space.degree + vector_space.degree) boundary_quadrature = fem.RegularQuadrature(domain=boundary, order=tensor_space.degree + vector_space.degree) div_int = fem.integrate( tensor_divergence_form, quadrature=interior_quadrature, fields={"tau": tau, "v": v}, kernel_options={"enable_backward": False}, ) grad_int = fem.integrate( tensor_grad_form, quadrature=interior_quadrature, fields={"tau": tau, "v": v}, kernel_options={"enable_backward": False}, ) boundary_int = fem.integrate( tensor_boundary_form, quadrature=boundary_quadrature, fields={"tau": tau.trace(), "v": v.trace()}, kernel_options={"enable_backward": False}, ) test.assertAlmostEqual(div_int + grad_int, boundary_int, places=5) @integrand def grad_decomposition(s: Sample, u: Field, v: Field): return wp.length_sq(grad(u, s) * v(s) - D(u, s) * v(s) - wp.cross(curl(u, s), v(s))) def test_grad_decomposition(test, device): rng = np.random.default_rng(123) with wp.ScopedDevice(device): # Grid geometry geo = fem.Grid3D(res=wp.vec3i(5)) # Domain and function spaces domain = fem.Cells(geometry=geo) quadrature = fem.RegularQuadrature(domain=domain, order=4) vector_space = fem.make_polynomial_space(geo, degree=2, dtype=wp.vec3) u = vector_space.make_field() u.dof_values = rng.random(size=(u.dof_values.shape[0], 3)) err = fem.integrate(grad_decomposition, quadrature=quadrature, fields={"u": u, "v": u}) test.assertLess(err, 1.0e-8) def _gen_trimesh(N): x = np.linspace(0.0, 1.0, N + 1) y = np.linspace(0.0, 1.0, N + 1) positions = np.transpose(np.meshgrid(x, y, indexing="ij")).reshape(-1, 2) vidx = grid_to_tris(N, N) return wp.array(positions, dtype=wp.vec2), wp.array(vidx, dtype=int) def _gen_quadmesh(N): x = np.linspace(0.0, 1.0, N + 1) y = np.linspace(0.0, 1.0, N + 1) positions = np.transpose(np.meshgrid(x, y, indexing="ij")).reshape(-1, 2) vidx = grid_to_quads(N, N) return wp.array(positions, dtype=wp.vec2), wp.array(vidx, dtype=int) def _gen_tetmesh(N): x = np.linspace(0.0, 1.0, N + 1) y = np.linspace(0.0, 1.0, N + 1) z = np.linspace(0.0, 1.0, N + 1) positions = np.transpose(np.meshgrid(x, y, z, indexing="ij")).reshape(-1, 3) vidx = grid_to_tets(N, N, N) return wp.array(positions, dtype=wp.vec3), wp.array(vidx, dtype=int) def _gen_hexmesh(N): x = np.linspace(0.0, 1.0, N + 1) y = np.linspace(0.0, 1.0, N + 1) z = np.linspace(0.0, 1.0, N + 1) positions = np.transpose(np.meshgrid(x, y, z, indexing="ij")).reshape(-1, 3) vidx = grid_to_hexes(N, N, N) return wp.array(positions, dtype=wp.vec3), wp.array(vidx, dtype=int) def _launch_test_geometry_kernel(geo: fem.Geometry, device): @dynamic_kernel(suffix=geo.name, kernel_options={"enable_backward": False}) def test_geo_cells_kernel( cell_arg: geo.CellArg, qps: wp.array(dtype=Coords), qp_weights: wp.array(dtype=float), cell_measures: wp.array(dtype=float), ): cell_index, q = wp.tid() coords = qps[q] s = make_free_sample(cell_index, coords) wp.atomic_add(cell_measures, cell_index, geo.cell_measure(cell_arg, s) * qp_weights[q]) REF_MEASURE = geo.reference_side().measure() @dynamic_kernel(suffix=geo.name, kernel_options={"enable_backward": False, "max_unroll": 1}) def test_geo_sides_kernel( side_arg: geo.SideArg, qps: wp.array(dtype=Coords), qp_weights: wp.array(dtype=float), side_measures: wp.array(dtype=float), ): side_index, q = wp.tid() coords = qps[q] s = make_free_sample(side_index, coords) cell_arg = geo.side_to_cell_arg(side_arg) inner_cell_index = geo.side_inner_cell_index(side_arg, side_index) outer_cell_index = geo.side_outer_cell_index(side_arg, side_index) inner_cell_coords = geo.side_inner_cell_coords(side_arg, side_index, coords) outer_cell_coords = geo.side_outer_cell_coords(side_arg, side_index, coords) inner_s = make_free_sample(inner_cell_index, inner_cell_coords) outer_s = make_free_sample(outer_cell_index, outer_cell_coords) pos_side = geo.side_position(side_arg, s) pos_inner = geo.cell_position(cell_arg, inner_s) pos_outer = geo.cell_position(cell_arg, outer_s) for k in range(type(pos_side).length): wp.expect_near(pos_side[k], pos_inner[k], 0.0001) wp.expect_near(pos_side[k], pos_outer[k], 0.0001) inner_side_coords = geo.side_from_cell_coords(side_arg, side_index, inner_cell_index, inner_cell_coords) outer_side_coords = geo.side_from_cell_coords(side_arg, side_index, outer_cell_index, outer_cell_coords) wp.expect_near(coords, inner_side_coords, 0.0001) wp.expect_near(coords, outer_side_coords, 0.0001) area = geo.side_measure(side_arg, s) wp.atomic_add(side_measures, side_index, area * qp_weights[q]) # test consistency of side normal, measure, and deformation gradient F = geo.side_deformation_gradient(side_arg, s) F_det = DeformedGeometry._side_measure(F) wp.expect_near(F_det * REF_MEASURE, area) nor = geo.side_normal(side_arg, s) F_cross = DeformedGeometry._side_normal(F) for k in range(type(pos_side).length): wp.expect_near(F_cross[k], nor[k], 0.0001) cell_measures = wp.zeros(dtype=float, device=device, shape=geo.cell_count()) cell_quadrature = fem.RegularQuadrature(fem.Cells(geo), order=2) cell_qps = wp.array(cell_quadrature.points, dtype=Coords, device=device) cell_qp_weights = wp.array(cell_quadrature.weights, dtype=float, device=device) wp.launch( kernel=test_geo_cells_kernel, dim=(geo.cell_count(), cell_qps.shape[0]), inputs=[geo.cell_arg_value(device), cell_qps, cell_qp_weights, cell_measures], device=device, ) side_measures = wp.zeros(dtype=float, device=device, shape=geo.side_count()) side_quadrature = fem.RegularQuadrature(fem.Sides(geo), order=2) side_qps = wp.array(side_quadrature.points, dtype=Coords, device=device) side_qp_weights = wp.array(side_quadrature.weights, dtype=float, device=device) wp.launch( kernel=test_geo_sides_kernel, dim=(geo.side_count(), side_qps.shape[0]), inputs=[geo.side_arg_value(device), side_qps, side_qp_weights, side_measures], device=device, ) return side_measures, cell_measures def test_grid_2d(test, device): N = 3 geo = fem.Grid2D(res=wp.vec2i(N)) test.assertEqual(geo.cell_count(), N**2) test.assertEqual(geo.vertex_count(), (N + 1) ** 2) test.assertEqual(geo.side_count(), 2 * (N + 1) * N) test.assertEqual(geo.boundary_side_count(), 4 * N) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) assert_np_equal(side_measures.numpy(), np.full(side_measures.shape, 1.0 / (N)), tol=1.0e-4) assert_np_equal(cell_measures.numpy(), np.full(cell_measures.shape, 1.0 / (N**2)), tol=1.0e-4) def test_triangle_mesh(test, device): N = 3 with wp.ScopedDevice(device): positions, tri_vidx = _gen_trimesh(N) geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions) test.assertEqual(geo.cell_count(), 2 * (N) ** 2) test.assertEqual(geo.vertex_count(), (N + 1) ** 2) test.assertEqual(geo.side_count(), 2 * (N + 1) * N + (N**2)) test.assertEqual(geo.boundary_side_count(), 4 * N) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) assert_np_equal(cell_measures.numpy(), np.full(cell_measures.shape, 0.5 / (N**2)), tol=1.0e-4) test.assertAlmostEqual(np.sum(side_measures.numpy()), 2 * (N + 1) + N * math.sqrt(2.0), places=4) def test_quad_mesh(test, device): N = 3 with wp.ScopedDevice(device): positions, quad_vidx = _gen_quadmesh(N) geo = fem.Quadmesh2D(quad_vertex_indices=quad_vidx, positions=positions) test.assertEqual(geo.cell_count(), N**2) test.assertEqual(geo.vertex_count(), (N + 1) ** 2) test.assertEqual(geo.side_count(), 2 * (N + 1) * N) test.assertEqual(geo.boundary_side_count(), 4 * N) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) assert_np_equal(side_measures.numpy(), np.full(side_measures.shape, 1.0 / (N)), tol=1.0e-4) assert_np_equal(cell_measures.numpy(), np.full(cell_measures.shape, 1.0 / (N**2)), tol=1.0e-4) def test_grid_3d(test, device): N = 3 geo = fem.Grid3D(res=wp.vec3i(N)) test.assertEqual(geo.cell_count(), (N) ** 3) test.assertEqual(geo.vertex_count(), (N + 1) ** 3) test.assertEqual(geo.side_count(), 3 * (N + 1) * N**2) test.assertEqual(geo.boundary_side_count(), 6 * N * N) test.assertEqual(geo.edge_count(), 3 * N * (N + 1) ** 2) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) assert_np_equal(side_measures.numpy(), np.full(side_measures.shape, 1.0 / (N**2)), tol=1.0e-4) assert_np_equal(cell_measures.numpy(), np.full(cell_measures.shape, 1.0 / (N**3)), tol=1.0e-4) def test_tet_mesh(test, device): N = 3 with wp.ScopedDevice(device): positions, tet_vidx = _gen_tetmesh(N) geo = fem.Tetmesh(tet_vertex_indices=tet_vidx, positions=positions) test.assertEqual(geo.cell_count(), 5 * (N) ** 3) test.assertEqual(geo.vertex_count(), (N + 1) ** 3) test.assertEqual(geo.side_count(), 6 * (N + 1) * N**2 + (N**3) * 4) test.assertEqual(geo.boundary_side_count(), 12 * N * N) test.assertEqual(geo.edge_count(), 3 * N * (N + 1) * (2 * N + 1)) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) test.assertAlmostEqual(np.sum(cell_measures.numpy()), 1.0, places=4) test.assertAlmostEqual(np.sum(side_measures.numpy()), 0.5 * 6 * (N + 1) + N * 2 * math.sqrt(3.0), places=4) def test_hex_mesh(test, device): N = 3 with wp.ScopedDevice(device): positions, tet_vidx = _gen_hexmesh(N) geo = fem.Hexmesh(hex_vertex_indices=tet_vidx, positions=positions) test.assertEqual(geo.cell_count(), (N) ** 3) test.assertEqual(geo.vertex_count(), (N + 1) ** 3) test.assertEqual(geo.side_count(), 3 * (N + 1) * N**2) test.assertEqual(geo.boundary_side_count(), 6 * N * N) test.assertEqual(geo.edge_count(), 3 * N * (N + 1) ** 2) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) assert_np_equal(side_measures.numpy(), np.full(side_measures.shape, 1.0 / (N**2)), tol=1.0e-4) assert_np_equal(cell_measures.numpy(), np.full(cell_measures.shape, 1.0 / (N**3)), tol=1.0e-4) def test_nanogrid(test, device): N = 8 points = wp.array([[0.5, 0.5, 0.5]], dtype=float, device=device) volume = wp.Volume.allocate_by_tiles( tile_points=points, voxel_size=1.0 / N, translation=(0.0, 0.0, 0.0), bg_value=None, device=device ) geo = fem.Nanogrid(volume) test.assertEqual(geo.cell_count(), (N) ** 3) test.assertEqual(geo.vertex_count(), (N + 1) ** 3) test.assertEqual(geo.side_count(), 3 * (N + 1) * N**2) test.assertEqual(geo.boundary_side_count(), 6 * N * N) test.assertEqual(geo.edge_count(), 3 * N * (N + 1) ** 2) side_measures, cell_measures = _launch_test_geometry_kernel(geo, device) assert_np_equal(side_measures.numpy(), np.full(side_measures.shape, 1.0 / (N**2)), tol=1.0e-4) assert_np_equal(cell_measures.numpy(), np.full(cell_measures.shape, 1.0 / (N**3)), tol=1.0e-4) @integrand def _rigid_deformation_field(s: Sample, domain: Domain, translation: wp.vec3, rotation: wp.vec3, scale: float): q = wp.quat_from_axis_angle(wp.normalize(rotation), wp.length(rotation)) return translation + scale * wp.quat_rotate(q, domain(s)) - domain(s) def test_deformed_geometry(test, device): N = 3 with wp.ScopedDevice(device): positions, tet_vidx = _gen_tetmesh(N) geo = fem.Tetmesh(tet_vertex_indices=tet_vidx, positions=positions) translation = [1.0, 2.0, 3.0] rotation = [0.0, math.pi / 4.0, 0.0] scale = 2.0 vector_space = fem.make_polynomial_space(geo, dtype=wp.vec3, degree=2) pos_field = vector_space.make_field() fem.interpolate( _rigid_deformation_field, dest=pos_field, values={"translation": translation, "rotation": rotation, "scale": scale}, ) deformed_geo = pos_field.make_deformed_geometry() # rigidly-deformed geometry test.assertEqual(geo.cell_count(), 5 * (N) ** 3) test.assertEqual(geo.vertex_count(), (N + 1) ** 3) test.assertEqual(geo.side_count(), 6 * (N + 1) * N**2 + (N**3) * 4) test.assertEqual(geo.boundary_side_count(), 12 * N * N) side_measures, cell_measures = _launch_test_geometry_kernel(deformed_geo, wp.get_device()) test.assertAlmostEqual( np.sum(cell_measures.numpy()), scale**3, places=4, msg=f"cell_measures = {cell_measures.numpy()}" ) test.assertAlmostEqual( np.sum(side_measures.numpy()), scale**2 * (0.5 * 6 * (N + 1) + N * 2 * math.sqrt(3.0)), places=4 ) @wp.kernel def _test_deformed_geometry_normal( geo_index_arg: geo.SideIndexArg, geo_arg: geo.SideArg, def_arg: deformed_geo.SideArg, rotation: wp.vec3 ): i = wp.tid() side_index = deformed_geo.boundary_side_index(geo_index_arg, i) s = make_free_sample(side_index, Coords(0.5, 0.5, 0.0)) geo_n = geo.side_normal(geo_arg, s) def_n = deformed_geo.side_normal(def_arg, s) q = wp.quat_from_axis_angle(wp.normalize(rotation), wp.length(rotation)) wp.expect_near(wp.quat_rotate(q, geo_n), def_n, 0.001) wp.launch( _test_deformed_geometry_normal, dim=geo.boundary_side_count(), inputs=[ geo.side_index_arg_value(wp.get_device()), geo.side_arg_value(wp.get_device()), deformed_geo.side_arg_value(wp.get_device()), rotation, ], ) wp.synchronize() @wp.kernel def _test_closest_point_on_tri_kernel( e0: wp.vec2, e1: wp.vec2, points: wp.array(dtype=wp.vec2), sq_dist: wp.array(dtype=float), coords: wp.array(dtype=Coords), ): i = wp.tid() d2, c = project_on_tri_at_origin(points[i], e0, e1) sq_dist[i] = d2 coords[i] = c @wp.kernel def _test_closest_point_on_tet_kernel( e0: wp.vec3, e1: wp.vec3, e2: wp.vec3, points: wp.array(dtype=wp.vec3), sq_dist: wp.array(dtype=float), coords: wp.array(dtype=Coords), ): i = wp.tid() d2, c = project_on_tet_at_origin(points[i], e0, e1, e2) sq_dist[i] = d2 coords[i] = c def test_closest_point_queries(test, device): # Test some simple lookup queries e0 = wp.vec2(2.0, 0.0) e1 = wp.vec2(0.0, 2.0) points = wp.array( ( [-1.0, -1.0], [0.5, 0.5], [1.0, 1.0], [2.0, 2.0], ), dtype=wp.vec2, device=device, ) expected_sq_dist = np.array([2.0, 0.0, 0.0, 2.0]) expected_coords = np.array([[1.0, 0.0, 0.0], [0.5, 0.25, 0.25], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5]]) sq_dist = wp.empty(shape=points.shape, dtype=float, device=device) coords = wp.empty(shape=points.shape, dtype=Coords, device=device) wp.launch( _test_closest_point_on_tri_kernel, dim=points.shape, device=device, inputs=[e0, e1, points, sq_dist, coords] ) assert_np_equal(coords.numpy(), expected_coords) assert_np_equal(sq_dist.numpy(), expected_sq_dist) # Tet e0 = wp.vec3(3.0, 0.0, 0.0) e1 = wp.vec3(0.0, 3.0, 0.0) e2 = wp.vec3(0.0, 0.0, 3.0) points = wp.array( ( [-1.0, -1.0, -1.0], [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0], ), dtype=wp.vec3, device=device, ) expected_sq_dist = np.array([3.0, 0.0, 0.0, 3.0]) expected_coords = np.array( [ [0.0, 0.0, 0.0], [1.0 / 6.0, 1.0 / 6.0, 1.0 / 6.0], [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0], [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0], ] ) sq_dist = wp.empty(shape=points.shape, dtype=float, device=device) coords = wp.empty(shape=points.shape, dtype=Coords, device=device) wp.launch( _test_closest_point_on_tet_kernel, dim=points.shape, device=device, inputs=[e0, e1, e2, points, sq_dist, coords] ) assert_np_equal(coords.numpy(), expected_coords, tol=1.0e-4) assert_np_equal(sq_dist.numpy(), expected_sq_dist, tol=1.0e-4) def test_regular_quadrature(test, device): from warp.fem.geometry.element import LinearEdge, Polynomial, Triangle for family in Polynomial: # test integrating monomials for degree in range(8): coords, weights = LinearEdge().instantiate_quadrature(degree, family=family) res = sum(w * pow(c[0], degree) for w, c in zip(weights, coords)) ref = 1.0 / (degree + 1) test.assertAlmostEqual(ref, res, places=4) # test integrating y^k1 (1 - x)^k2 on triangle using transformation to square for x_degree in range(4): for y_degree in range(4): coords, weights = Triangle().instantiate_quadrature(x_degree + y_degree, family=family) res = 0.5 * sum(w * pow(1.0 - c[1], x_degree) * pow(c[2], y_degree) for w, c in zip(weights, coords)) ref = 1.0 / ((x_degree + y_degree + 2) * (y_degree + 1)) # print(x_degree, y_degree, family, len(coords), res, ref) test.assertAlmostEqual(ref, res, places=4) # test integrating y^k1 (1 - x)^k2 on triangle using direct formulas for x_degree in range(5): for y_degree in range(5): coords, weights = Triangle().instantiate_quadrature(x_degree + y_degree, family=None) res = 0.5 * sum(w * pow(1.0 - c[1], x_degree) * pow(c[2], y_degree) for w, c in zip(weights, coords)) ref = 1.0 / ((x_degree + y_degree + 2) * (y_degree + 1)) test.assertAlmostEqual(ref, res, places=4) def test_dof_mapper(test, device): matrix_types = [wp.mat22, wp.mat33] # Symmetric mapper for mapping in fem.SymmetricTensorMapper.Mapping: for dtype in matrix_types: mapper = fem.SymmetricTensorMapper(dtype, mapping=mapping) dof_dtype = mapper.dof_dtype for k in range(dof_dtype._length_): elem = np.array(dof_dtype(0.0)) elem[k] = 1.0 dof_vec = dof_dtype(elem) mat = mapper.dof_to_value(dof_vec) dof_round_trip = mapper.value_to_dof(mat) # Check that value_to_dof(dof_to_value) is idempotent assert_np_equal(np.array(dof_round_trip), np.array(dof_vec)) # Check that value is unitary for Frobenius norm 0.5 * |tau:tau| frob_norm2 = 0.5 * wp.ddot(mat, mat) test.assertAlmostEqual(frob_norm2, 1.0, places=6) # Skew-symmetric mapper for dtype in matrix_types: mapper = fem.SkewSymmetricTensorMapper(dtype) dof_dtype = mapper.dof_dtype if hasattr(dof_dtype, "_length_"): for k in range(dof_dtype._length_): elem = np.array(dof_dtype(0.0)) elem[k] = 1.0 dof_vec = dof_dtype(elem) mat = mapper.dof_to_value(dof_vec) dof_round_trip = mapper.value_to_dof(mat) # Check that value_to_dof(dof_to_value) is idempotent assert_np_equal(np.array(dof_round_trip), np.array(dof_vec)) # Check that value is unitary for Frobenius norm 0.5 * |tau:tau| frob_norm2 = 0.5 * wp.ddot(mat, mat) test.assertAlmostEqual(frob_norm2, 1.0, places=6) else: dof_val = 1.0 mat = mapper.dof_to_value(dof_val) dof_round_trip = mapper.value_to_dof(mat) test.assertAlmostEqual(dof_round_trip, dof_val) # Check that value is unitary for Frobenius norm 0.5 * |tau:tau| frob_norm2 = 0.5 * wp.ddot(mat, mat) test.assertAlmostEqual(frob_norm2, 1.0, places=6) def test_shape_function_weight(test, shape: shape.ShapeFunction, coord_sampler, CENTER_COORDS): NODE_COUNT = shape.NODES_PER_ELEMENT weight_fn = shape.make_element_inner_weight() node_coords_fn = shape.make_node_coords_in_element() # Weight at node should be 1 @dynamic_kernel(suffix=shape.name, kernel_options={"enable_backward": False}) def node_unity_test(): n = wp.tid() node_w = weight_fn(node_coords_fn(n), n) wp.expect_near(node_w, 1.0, places=5) wp.launch(node_unity_test, dim=NODE_COUNT, inputs=[]) # Sum of node quadrature weights should be one (order 0) # Sum of weighted quadrature coords should be element center (order 1) node_quadrature_weight_fn = shape.make_node_quadrature_weight() @dynamic_kernel(suffix=shape.name, kernel_options={"enable_backward": False}) def node_quadrature_unity_test(): sum_node_qp = float(0.0) sum_node_qp_coords = Coords(0.0) for n in range(NODE_COUNT): w = node_quadrature_weight_fn(n) sum_node_qp += w sum_node_qp_coords += w * node_coords_fn(n) wp.expect_near(sum_node_qp, 1.0, 0.0001) wp.expect_near(sum_node_qp_coords, CENTER_COORDS, 0.0001) wp.launch(node_quadrature_unity_test, dim=1, inputs=[]) @dynamic_kernel(suffix=shape.name, kernel_options={"enable_backward": False}) def partition_of_unity_test(): rng_state = wp.rand_init(4321, wp.tid()) coords = coord_sampler(rng_state) # sum of node weights anywhere should be 1.0 w_sum = float(0.0) for n in range(NODE_COUNT): w_sum += weight_fn(coords, n) wp.expect_near(w_sum, 1.0, 0.0001) n_samples = 100 wp.launch(partition_of_unity_test, dim=n_samples, inputs=[]) def test_shape_function_trace(test, shape: shape.ShapeFunction, CENTER_COORDS): NODE_COUNT = shape.NODES_PER_ELEMENT node_coords_fn = shape.make_node_coords_in_element() # Sum of node quadrature weights should be one (order 0) # Sum of weighted quadrature coords should be element center (order 1) trace_node_quadrature_weight_fn = shape.make_trace_node_quadrature_weight() @dynamic_kernel(suffix=shape.name, kernel_options={"enable_backward": False}) def trace_node_quadrature_unity_test(): sum_node_qp = float(0.0) sum_node_qp_coords = Coords(0.0) for n in range(NODE_COUNT): coords = node_coords_fn(n) if wp.abs(coords[0]) < 1.0e-6: w = trace_node_quadrature_weight_fn(n) sum_node_qp += w sum_node_qp_coords += w * node_coords_fn(n) wp.expect_near(sum_node_qp, 1.0, 0.0001) wp.expect_near(sum_node_qp_coords, CENTER_COORDS, 0.0001) wp.launch(trace_node_quadrature_unity_test, dim=1, inputs=[]) def test_shape_function_gradient(test, shape: shape.ShapeFunction, coord_sampler, coord_delta_sampler): weight_fn = shape.make_element_inner_weight() weight_gradient_fn = shape.make_element_inner_weight_gradient() @dynamic_kernel(suffix=shape.name, kernel_options={"enable_backward": False}) def finite_difference_test(): i, n = wp.tid() rng_state = wp.rand_init(1234, i) coords = coord_sampler(rng_state) epsilon = 0.003 param_delta, coords_delta = coord_delta_sampler(epsilon, rng_state) w_p = weight_fn(coords + coords_delta, n) w_m = weight_fn(coords - coords_delta, n) gp = weight_gradient_fn(coords + coords_delta, n) gm = weight_gradient_fn(coords - coords_delta, n) # 2nd-order finite-difference test # See Schroeder 2019, Practical course on computing derivatives in code delta_ref = w_p - w_m delta_est = wp.dot(gp + gm, param_delta) # wp.printf("%d %f %f \n", n, delta_ref, delta_est) wp.expect_near(delta_ref, delta_est, 0.0001) n_samples = 100 wp.launch(finite_difference_test, dim=(n_samples, shape.NODES_PER_ELEMENT), inputs=[]) def test_square_shape_functions(test, device): SQUARE_CENTER_COORDS = wp.constant(Coords(0.5, 0.5, 0.0)) SQUARE_SIDE_CENTER_COORDS = wp.constant(Coords(0.0, 0.5, 0.0)) @wp.func def square_coord_sampler(state: wp.uint32): return Coords(wp.randf(state), wp.randf(state), 0.0) @wp.func def square_coord_delta_sampler(epsilon: float, state: wp.uint32): param_delta = wp.normalize(wp.vec2(wp.randf(state), wp.randf(state))) * epsilon return param_delta, Coords(param_delta[0], param_delta[1], 0.0) Q_1 = shape.SquareBipolynomialShapeFunctions(degree=1, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) Q_2 = shape.SquareBipolynomialShapeFunctions(degree=2, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) Q_3 = shape.SquareBipolynomialShapeFunctions(degree=3, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) test_shape_function_weight(test, Q_1, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, Q_2, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, Q_3, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_trace(test, Q_1, SQUARE_SIDE_CENTER_COORDS) test_shape_function_trace(test, Q_2, SQUARE_SIDE_CENTER_COORDS) test_shape_function_trace(test, Q_3, SQUARE_SIDE_CENTER_COORDS) test_shape_function_gradient(test, Q_1, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, Q_2, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, Q_3, square_coord_sampler, square_coord_delta_sampler) Q_1 = shape.SquareBipolynomialShapeFunctions(degree=1, family=fem.Polynomial.GAUSS_LEGENDRE) Q_2 = shape.SquareBipolynomialShapeFunctions(degree=2, family=fem.Polynomial.GAUSS_LEGENDRE) Q_3 = shape.SquareBipolynomialShapeFunctions(degree=3, family=fem.Polynomial.GAUSS_LEGENDRE) test_shape_function_weight(test, Q_1, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, Q_2, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, Q_3, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_gradient(test, Q_1, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, Q_2, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, Q_3, square_coord_sampler, square_coord_delta_sampler) S_2 = shape.SquareSerendipityShapeFunctions(degree=2, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) S_3 = shape.SquareSerendipityShapeFunctions(degree=3, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) test_shape_function_weight(test, S_2, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, S_3, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_trace(test, S_2, SQUARE_SIDE_CENTER_COORDS) test_shape_function_trace(test, S_3, SQUARE_SIDE_CENTER_COORDS) test_shape_function_gradient(test, S_2, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, S_3, square_coord_sampler, square_coord_delta_sampler) P_c1 = shape.SquareNonConformingPolynomialShapeFunctions(degree=1) P_c2 = shape.SquareNonConformingPolynomialShapeFunctions(degree=2) P_c3 = shape.SquareNonConformingPolynomialShapeFunctions(degree=3) test_shape_function_weight(test, P_c1, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, P_c2, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_weight(test, P_c3, square_coord_sampler, SQUARE_CENTER_COORDS) test_shape_function_gradient(test, P_c1, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, P_c2, square_coord_sampler, square_coord_delta_sampler) test_shape_function_gradient(test, P_c3, square_coord_sampler, square_coord_delta_sampler) wp.synchronize() def test_cube_shape_functions(test, device): CUBE_CENTER_COORDS = wp.constant(Coords(0.5, 0.5, 0.5)) CUBE_SIDE_CENTER_COORDS = wp.constant(Coords(0.0, 0.5, 0.5)) @wp.func def cube_coord_sampler(state: wp.uint32): return Coords(wp.randf(state), wp.randf(state), wp.randf(state)) @wp.func def cube_coord_delta_sampler(epsilon: float, state: wp.uint32): param_delta = wp.normalize(wp.vec3(wp.randf(state), wp.randf(state), wp.randf(state))) * epsilon return param_delta, param_delta Q_1 = shape.CubeTripolynomialShapeFunctions(degree=1, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) Q_2 = shape.CubeTripolynomialShapeFunctions(degree=2, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) Q_3 = shape.CubeTripolynomialShapeFunctions(degree=3, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) test_shape_function_weight(test, Q_1, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, Q_2, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, Q_3, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_trace(test, Q_1, CUBE_SIDE_CENTER_COORDS) test_shape_function_trace(test, Q_2, CUBE_SIDE_CENTER_COORDS) test_shape_function_trace(test, Q_3, CUBE_SIDE_CENTER_COORDS) test_shape_function_gradient(test, Q_1, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, Q_2, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, Q_3, cube_coord_sampler, cube_coord_delta_sampler) Q_1 = shape.CubeTripolynomialShapeFunctions(degree=1, family=fem.Polynomial.GAUSS_LEGENDRE) Q_2 = shape.CubeTripolynomialShapeFunctions(degree=2, family=fem.Polynomial.GAUSS_LEGENDRE) Q_3 = shape.CubeTripolynomialShapeFunctions(degree=3, family=fem.Polynomial.GAUSS_LEGENDRE) test_shape_function_weight(test, Q_1, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, Q_2, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, Q_3, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_gradient(test, Q_1, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, Q_2, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, Q_3, cube_coord_sampler, cube_coord_delta_sampler) S_2 = shape.CubeSerendipityShapeFunctions(degree=2, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) S_3 = shape.CubeSerendipityShapeFunctions(degree=3, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) test_shape_function_weight(test, S_2, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, S_3, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_trace(test, S_2, CUBE_SIDE_CENTER_COORDS) test_shape_function_trace(test, S_3, CUBE_SIDE_CENTER_COORDS) test_shape_function_gradient(test, S_2, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, S_3, cube_coord_sampler, cube_coord_delta_sampler) P_c1 = shape.CubeNonConformingPolynomialShapeFunctions(degree=1) P_c2 = shape.CubeNonConformingPolynomialShapeFunctions(degree=2) P_c3 = shape.CubeNonConformingPolynomialShapeFunctions(degree=3) test_shape_function_weight(test, P_c1, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, P_c2, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_weight(test, P_c3, cube_coord_sampler, CUBE_CENTER_COORDS) test_shape_function_gradient(test, P_c1, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, P_c2, cube_coord_sampler, cube_coord_delta_sampler) test_shape_function_gradient(test, P_c3, cube_coord_sampler, cube_coord_delta_sampler) wp.synchronize() def test_tri_shape_functions(test, device): TRI_CENTER_COORDS = wp.constant(Coords(1 / 3.0, 1 / 3.0, 1 / 3.0)) TRI_SIDE_CENTER_COORDS = wp.constant(Coords(0.0, 0.5, 0.5)) @wp.func def tri_coord_sampler(state: wp.uint32): a = wp.randf(state) b = wp.randf(state) return Coords(1.0 - a - b, a, b) @wp.func def tri_coord_delta_sampler(epsilon: float, state: wp.uint32): param_delta = wp.normalize(wp.vec2(wp.randf(state), wp.randf(state))) * epsilon a = param_delta[0] b = param_delta[1] return param_delta, Coords(-a - b, a, b) P_1 = shape.Triangle2DPolynomialShapeFunctions(degree=1) P_2 = shape.Triangle2DPolynomialShapeFunctions(degree=2) P_3 = shape.Triangle2DPolynomialShapeFunctions(degree=3) test_shape_function_weight(test, P_1, tri_coord_sampler, TRI_CENTER_COORDS) test_shape_function_weight(test, P_2, tri_coord_sampler, TRI_CENTER_COORDS) test_shape_function_weight(test, P_3, tri_coord_sampler, TRI_CENTER_COORDS) test_shape_function_trace(test, P_1, TRI_SIDE_CENTER_COORDS) test_shape_function_trace(test, P_2, TRI_SIDE_CENTER_COORDS) test_shape_function_trace(test, P_3, TRI_SIDE_CENTER_COORDS) test_shape_function_gradient(test, P_1, tri_coord_sampler, tri_coord_delta_sampler) test_shape_function_gradient(test, P_2, tri_coord_sampler, tri_coord_delta_sampler) test_shape_function_gradient(test, P_3, tri_coord_sampler, tri_coord_delta_sampler) P_1d = shape.Triangle2DNonConformingPolynomialShapeFunctions(degree=1) P_2d = shape.Triangle2DNonConformingPolynomialShapeFunctions(degree=2) P_3d = shape.Triangle2DNonConformingPolynomialShapeFunctions(degree=3) test_shape_function_weight(test, P_1d, tri_coord_sampler, TRI_CENTER_COORDS) test_shape_function_weight(test, P_2d, tri_coord_sampler, TRI_CENTER_COORDS) test_shape_function_weight(test, P_3d, tri_coord_sampler, TRI_CENTER_COORDS) test_shape_function_gradient(test, P_1d, tri_coord_sampler, tri_coord_delta_sampler) test_shape_function_gradient(test, P_2d, tri_coord_sampler, tri_coord_delta_sampler) test_shape_function_gradient(test, P_3d, tri_coord_sampler, tri_coord_delta_sampler) wp.synchronize() def test_tet_shape_functions(test, device): TET_CENTER_COORDS = wp.constant(Coords(1 / 4.0, 1 / 4.0, 1 / 4.0)) TET_SIDE_CENTER_COORDS = wp.constant(Coords(0.0, 1.0 / 3.0, 1.0 / 3.0)) @wp.func def tet_coord_sampler(state: wp.uint32): return Coords(wp.randf(state), wp.randf(state), wp.randf(state)) @wp.func def tet_coord_delta_sampler(epsilon: float, state: wp.uint32): param_delta = wp.normalize(wp.vec3(wp.randf(state), wp.randf(state), wp.randf(state))) * epsilon return param_delta, param_delta P_1 = shape.TetrahedronPolynomialShapeFunctions(degree=1) P_2 = shape.TetrahedronPolynomialShapeFunctions(degree=2) P_3 = shape.TetrahedronPolynomialShapeFunctions(degree=3) test_shape_function_weight(test, P_1, tet_coord_sampler, TET_CENTER_COORDS) test_shape_function_weight(test, P_2, tet_coord_sampler, TET_CENTER_COORDS) test_shape_function_weight(test, P_3, tet_coord_sampler, TET_CENTER_COORDS) test_shape_function_trace(test, P_1, TET_SIDE_CENTER_COORDS) test_shape_function_trace(test, P_2, TET_SIDE_CENTER_COORDS) test_shape_function_trace(test, P_3, TET_SIDE_CENTER_COORDS) test_shape_function_gradient(test, P_1, tet_coord_sampler, tet_coord_delta_sampler) test_shape_function_gradient(test, P_2, tet_coord_sampler, tet_coord_delta_sampler) test_shape_function_gradient(test, P_3, tet_coord_sampler, tet_coord_delta_sampler) P_1d = shape.TetrahedronNonConformingPolynomialShapeFunctions(degree=1) P_2d = shape.TetrahedronNonConformingPolynomialShapeFunctions(degree=2) P_3d = shape.TetrahedronNonConformingPolynomialShapeFunctions(degree=3) test_shape_function_weight(test, P_1d, tet_coord_sampler, TET_CENTER_COORDS) test_shape_function_weight(test, P_2d, tet_coord_sampler, TET_CENTER_COORDS) test_shape_function_weight(test, P_3d, tet_coord_sampler, TET_CENTER_COORDS) test_shape_function_gradient(test, P_1d, tet_coord_sampler, tet_coord_delta_sampler) test_shape_function_gradient(test, P_2d, tet_coord_sampler, tet_coord_delta_sampler) test_shape_function_gradient(test, P_3d, tet_coord_sampler, tet_coord_delta_sampler) wp.synchronize() def test_point_basis(test, device): geo = fem.Grid2D(res=wp.vec2i(2)) domain = fem.Cells(geo) quadrature = fem.RegularQuadrature(domain, order=2, family=fem.Polynomial.GAUSS_LEGENDRE) point_basis = fem.PointBasisSpace(quadrature) point_space = fem.make_collocated_function_space(point_basis) point_test = fem.make_test(point_space, domain=domain) # Sample at particle positions ones = fem.integrate(linear_form, fields={"u": point_test}, nodal=True) test.assertAlmostEqual(np.sum(ones.numpy()), 1.0, places=5) # Sampling outside of particle positions other_quadrature = fem.RegularQuadrature(domain, order=2, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE) zeros = fem.integrate(linear_form, quadrature=other_quadrature, fields={"u": point_test}) test.assertAlmostEqual(np.sum(zeros.numpy()), 0.0, places=5) @fem.integrand def _bicubic(s: Sample, domain: Domain): x = domain(s) return wp.pow(x[0], 3.0) * wp.pow(x[1], 3.0) @fem.integrand def _piecewise_constant(s: Sample): return float(s.element_index) def test_particle_quadratures(test, device): geo = fem.Grid2D(res=wp.vec2i(2)) domain = fem.Cells(geo) points, weights = domain.reference_element().instantiate_quadrature(order=4, family=fem.Polynomial.GAUSS_LEGENDRE) points_per_cell = len(points) points = points * domain.element_count() weights = weights * domain.element_count() points = wp.array(points, shape=(domain.element_count(), points_per_cell), dtype=Coords, device=device) weights = wp.array(weights, shape=(domain.element_count(), points_per_cell), dtype=float, device=device) explicit_quadrature = fem.ExplicitQuadrature(domain, points, weights) test.assertEqual(explicit_quadrature.points_per_element(), points_per_cell) test.assertEqual(explicit_quadrature.total_point_count(), points_per_cell * geo.cell_count()) val = fem.integrate(_bicubic, quadrature=explicit_quadrature) test.assertAlmostEqual(val, 1.0 / 16, places=5) element_indices = wp.array([3, 3, 2], dtype=int, device=device) element_coords = wp.array( [ [0.25, 0.5, 0.0], [0.5, 0.25, 0.0], [0.5, 0.5, 0.0], ], dtype=Coords, device=device, ) pic_quadrature = fem.PicQuadrature(domain, positions=(element_indices, element_coords)) test.assertIsNone(pic_quadrature.points_per_element()) test.assertEqual(pic_quadrature.total_point_count(), 3) test.assertEqual(pic_quadrature.active_cell_count(), 2) val = fem.integrate(_piecewise_constant, quadrature=pic_quadrature) test.assertAlmostEqual(val, 1.25, places=5) devices = get_test_devices() cuda_devices = get_selected_cuda_test_devices() class TestFem(unittest.TestCase): pass add_function_test(TestFem, "test_regular_quadrature", test_regular_quadrature) add_function_test(TestFem, "test_closest_point_queries", test_closest_point_queries) add_function_test(TestFem, "test_grad_decomposition", test_grad_decomposition, devices=devices) add_function_test(TestFem, "test_integrate_gradient", test_integrate_gradient, devices=devices) add_function_test(TestFem, "test_interpolate_gradient", test_interpolate_gradient, devices=devices) add_function_test(TestFem, "test_vector_divergence_theorem", test_vector_divergence_theorem, devices=devices) add_function_test(TestFem, "test_tensor_divergence_theorem", test_tensor_divergence_theorem, devices=devices) add_function_test(TestFem, "test_grid_2d", test_grid_2d, devices=devices) add_function_test(TestFem, "test_triangle_mesh", test_triangle_mesh, devices=devices) add_function_test(TestFem, "test_quad_mesh", test_quad_mesh, devices=devices) add_function_test(TestFem, "test_grid_3d", test_grid_3d, devices=devices) add_function_test(TestFem, "test_tet_mesh", test_tet_mesh, devices=devices) add_function_test(TestFem, "test_hex_mesh", test_hex_mesh, devices=devices) add_function_test(TestFem, "test_nanogrid", test_nanogrid, devices=cuda_devices) add_function_test(TestFem, "test_deformed_geometry", test_deformed_geometry, devices=devices) add_function_test(TestFem, "test_dof_mapper", test_dof_mapper) add_function_test(TestFem, "test_point_basis", test_point_basis) add_function_test(TestFem, "test_particle_quadratures", test_particle_quadratures) class TestFemShapeFunctions(unittest.TestCase): pass add_function_test(TestFemShapeFunctions, "test_square_shape_functions", test_square_shape_functions) add_function_test(TestFemShapeFunctions, "test_cube_shape_functions", test_cube_shape_functions) add_function_test(TestFemShapeFunctions, "test_tri_shape_functions", test_tri_shape_functions) add_function_test(TestFemShapeFunctions, "test_tet_shape_functions", test_tet_shape_functions) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
52,028
Python
39.053118
120
0.648439
NVIDIA/warp/warp/tests/test_sparse.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.sparse import ( bsr_axpy, bsr_axpy_work_arrays, bsr_copy, bsr_diag, bsr_get_diag, bsr_identity, bsr_mm, bsr_mm_work_arrays, bsr_mv, bsr_scale, bsr_set_from_triplets, bsr_set_transpose, bsr_transposed, bsr_zeros, ) from warp.tests.unittest_utils import * def _get_block(mat, row, col, block_shape): return mat[row * block_shape[0] : (row + 1) * block_shape[0], col * block_shape[1] : (col + 1) * block_shape[1]] def _triplets_to_dense(shape, rows, cols, values): mat = np.zeros(shape) rows = rows.numpy() cols = cols.numpy() values = values.numpy() block_shape = values.shape[1:] if values.ndim == 3 else (1, 1) for row, col, val in zip(rows, cols, values): mat_block = _get_block(mat, row, col, block_shape) mat_block += val return mat def _bsr_to_dense(bsr): mat = np.zeros(bsr.shape) offsets = bsr.offsets.numpy() columns = bsr.columns.numpy() values = bsr.values.numpy() for row in range(bsr.nrow): beg = offsets[row] end = offsets[row + 1] for block in range(beg, end): mat_block = _get_block(mat, row, columns[block], bsr.block_shape) mat_block += values[block] return mat def test_csr_from_triplets(test, device): rng = np.random.default_rng(123) shape = (8, 6) n = 100 rows = wp.array(rng.integers(0, high=shape[0], size=n, dtype=int), dtype=int, device=device) cols = wp.array(rng.integers(0, high=shape[1], size=n, dtype=int), dtype=int, device=device) vals = wp.array(rng.random(size=n), dtype=float, device=device) ref = _triplets_to_dense(shape, rows, cols, vals) csr = bsr_zeros(shape[0], shape[1], float, device=device) bsr_set_from_triplets(csr, rows, cols, vals) test.assertEqual(csr.block_size, 1) res = _bsr_to_dense(csr) assert_np_equal(res, ref, 0.0001) def test_bsr_from_triplets(test, device): rng = np.random.default_rng(123) block_shape = (3, 2) nrow = 4 ncol = 9 shape = (block_shape[0] * nrow, block_shape[1] * ncol) n = 50 rows = wp.array(rng.integers(0, high=nrow, size=n, dtype=int), dtype=int, device=device) cols = wp.array(rng.integers(0, high=ncol, size=n, dtype=int), dtype=int, device=device) vals = wp.array(rng.random(size=(n, block_shape[0], block_shape[1])), dtype=float, device=device) ref = _triplets_to_dense(shape, rows, cols, vals) bsr = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=float), device=device) bsr_set_from_triplets(bsr, rows, cols, vals) test.assertEqual(bsr.block_size, block_shape[0] * block_shape[1]) res = _bsr_to_dense(bsr) assert_np_equal(res, ref, 0.0001) # test zero-length inputs bsr_set_from_triplets( bsr, wp.array([], dtype=int, device=device), wp.array([], dtype=int, device=device), wp.array([], shape=(0, block_shape[0], block_shape[1]), dtype=float, device=device), ) test.assertEqual(bsr.nnz, 0) def test_bsr_get_set_diag(test, device): rng = np.random.default_rng(123) block_shape = (3, 3) nrow = 4 ncol = 4 nnz = 6 rows = wp.array([0, 1, 2, 3, 2, 1], dtype=int, device=device) cols = wp.array([1, 1, 1, 3, 2, 2], dtype=int, device=device) vals_np = rng.random(size=(nnz, block_shape[0], block_shape[1])) vals = wp.array(vals_np, dtype=float, device=device) bsr = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=float), device=device) bsr_set_from_triplets(bsr, rows, cols, vals) diag = bsr_get_diag(bsr) diag_np = diag.numpy() assert_np_equal(diag_np[0], np.zeros(block_shape)) assert_np_equal(diag_np[1], vals_np[1], tol=0.00001) assert_np_equal(diag_np[2], vals_np[4], tol=0.00001) assert_np_equal(diag_np[3], vals_np[3], tol=0.00001) # Test set_diag/get_diag round-trips with various block types # Array of blocks diag_bsr = bsr_diag(diag) bsr_get_diag(diag_bsr, out=diag) assert_np_equal(diag_np, diag.numpy()) diag_scalar_np = rng.random(size=nrow) diag_scalar = wp.array(diag_scalar_np, device=device) diag_bsr = bsr_diag(diag_scalar) diag = bsr_get_diag(diag_bsr) assert_np_equal(diag_scalar_np, diag.numpy(), tol=0.000001) # Uniform block diagonal with test.assertRaisesRegex(ValueError, "BsrMatrix block type must be either warp matrix or scalar"): # 1d block type -- invalid diag_bsr = bsr_diag(diag=vals_np[0, 0], rows_of_blocks=nrow, cols_of_blocks=nrow + 1) diag_bsr = bsr_diag(diag=vals_np[0], rows_of_blocks=nrow, cols_of_blocks=nrow + 1) assert diag_bsr.values.shape[0] == nrow assert_np_equal(diag_bsr.values.numpy(), np.broadcast_to(vals_np[0], shape=(nrow, *block_shape)), tol=0.000001) diag_bsr = bsr_diag(diag=float(diag_scalar_np[0]), rows_of_blocks=nrow, cols_of_blocks=nrow + 1) assert diag_bsr.values.shape[0] == nrow assert_np_equal(diag_bsr.values.numpy(), np.full(nrow, diag_scalar_np[0]), tol=0.000001) # Identity matrix diag_bsr = bsr_identity(nrow, block_type=wp.mat44, device=device) assert diag_bsr.values.shape[0] == nrow assert_np_equal(diag_bsr.values.numpy(), np.broadcast_to(np.eye(4), shape=(nrow, 4, 4)), tol=0.000001) diag_csr = bsr_identity(nrow, block_type=wp.float64, device=device) assert np.all(diag_csr.values.numpy() == np.ones(nrow, dtype=float)) def make_test_bsr_transpose(block_shape, scalar_type): def test_bsr_transpose(test, device): rng = np.random.default_rng(123) nrow = 4 ncol = 5 nnz = 6 rows = wp.array([0, 1, 2, 3, 2, 1], dtype=int, device=device) cols = wp.array([1, 4, 1, 3, 0, 2], dtype=int, device=device) vals_np = rng.random(size=(nnz, block_shape[0], block_shape[1])) vals = wp.array(vals_np, dtype=scalar_type, device=device).reshape((nnz, block_shape[0], block_shape[1])) bsr = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(bsr, rows, cols, vals) ref = np.transpose(_bsr_to_dense(bsr)) bsr_transposed = bsr_zeros( ncol, nrow, wp.types.matrix(shape=block_shape[::-1], dtype=scalar_type), device=device ) bsr_set_transpose(dest=bsr_transposed, src=bsr) res = _bsr_to_dense(bsr_transposed) assert_np_equal(res, ref, 0.0001) if block_shape[0] != block_shape[-1]: # test incompatible block shape with test.assertRaisesRegex(ValueError, "Destination block shape must be"): bsr_set_transpose(dest=bsr, src=bsr) return test_bsr_transpose def make_test_bsr_axpy(block_shape, scalar_type): def test_bsr_axpy(test, device): rng = np.random.default_rng(123) nrow = 2 ncol = 3 nnz = 6 alphas = [-1.0, 0.0, 1.0] betas = [2.0, -1.0, 0.0] x_rows = wp.array(rng.integers(0, high=nrow, size=nnz, dtype=int), dtype=int, device=device) x_cols = wp.array(rng.integers(0, high=ncol, size=nnz, dtype=int), dtype=int, device=device) x_vals = wp.array(rng.random(size=(nnz, block_shape[0], block_shape[1])), dtype=scalar_type, device=device) x_vals = x_vals.reshape((nnz, block_shape[0], block_shape[1])) x = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(x, x_rows, x_cols, x_vals) y_rows = wp.array(rng.integers(0, high=nrow, size=nnz, dtype=int), dtype=int, device=device) y_cols = wp.array(rng.integers(0, high=ncol, size=nnz, dtype=int), dtype=int, device=device) y_vals = wp.array(rng.random(size=(nnz, block_shape[0], block_shape[1])), dtype=scalar_type, device=device) y_vals = y_vals.reshape((nnz, block_shape[0], block_shape[1])) y = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(y, y_rows, y_cols, y_vals) work_arrays = bsr_axpy_work_arrays() for alpha, beta in zip(alphas, betas): ref = alpha * _bsr_to_dense(x) + beta * _bsr_to_dense(y) if beta == 0.0: y = bsr_axpy(x, alpha=alpha, beta=beta, work_arrays=work_arrays) else: bsr_axpy(x, y, alpha, beta, work_arrays=work_arrays) res = _bsr_to_dense(y) assert_np_equal(res, ref, 0.0001) # test aliasing ref = 3.0 * _bsr_to_dense(y) bsr_axpy(y, y, alpha=1.0, beta=2.0) res = _bsr_to_dense(y) assert_np_equal(res, ref, 0.0001) # test incompatible shapes y.ncol = y.ncol + 1 with test.assertRaisesRegex(ValueError, "Matrices must have the same number of rows and columns"): bsr_axpy(x, y) return test_bsr_axpy def make_test_bsr_mm(block_shape, scalar_type): def test_bsr_mm(test, device): rng = np.random.default_rng(123) x_nrow = 3 x_ncol = 2 x_block_shape = block_shape y_nrow = 2 y_ncol = 3 y_block_shape = block_shape[::-1] z_nrow = x_nrow z_ncol = y_ncol z_block_shape = (x_block_shape[0], y_block_shape[1]) nnz = 6 alphas = [-1.0, 0.0, 1.0] betas = [2.0, -1.0, 0.0] x_rows = wp.array(rng.integers(0, high=x_nrow, size=nnz, dtype=int), dtype=int, device=device) x_cols = wp.array(rng.integers(0, high=x_ncol, size=nnz, dtype=int), dtype=int, device=device) x_vals = wp.array(rng.random(size=(nnz, x_block_shape[0], x_block_shape[1])), dtype=scalar_type, device=device) x_vals = x_vals.reshape((nnz, x_block_shape[0], x_block_shape[1])) x = bsr_zeros(x_nrow, x_ncol, wp.types.matrix(shape=x_block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(x, x_rows, x_cols, x_vals) y_rows = wp.array(rng.integers(0, high=y_nrow, size=nnz, dtype=int), dtype=int, device=device) y_cols = wp.array(rng.integers(0, high=y_ncol, size=nnz, dtype=int), dtype=int, device=device) y_vals = wp.array(rng.random(size=(nnz, y_block_shape[0], y_block_shape[1])), dtype=scalar_type, device=device) y_vals = y_vals.reshape((nnz, y_block_shape[0], y_block_shape[1])) y = bsr_zeros(y_nrow, y_ncol, wp.types.matrix(shape=y_block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(y, y_rows, y_cols, y_vals) z_rows = wp.array(rng.integers(0, high=z_nrow, size=nnz, dtype=int), dtype=int, device=device) z_cols = wp.array(rng.integers(0, high=z_ncol, size=nnz, dtype=int), dtype=int, device=device) z_vals = wp.array(rng.random(size=(nnz, z_block_shape[0], z_block_shape[1])), dtype=scalar_type, device=device) z_vals = z_vals.reshape((nnz, z_block_shape[0], z_block_shape[1])) z = bsr_zeros(z_nrow, z_ncol, wp.types.matrix(shape=z_block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(z, z_rows, z_cols, z_vals) work_arrays = bsr_mm_work_arrays() for alpha, beta in zip(alphas, betas): ref = alpha * (_bsr_to_dense(x) @ _bsr_to_dense(y)) + beta * _bsr_to_dense(z) bsr_mm(x, y, z, alpha, beta, work_arrays=work_arrays) res = _bsr_to_dense(z) assert_np_equal(res, ref, 0.0001) # test aliasing of matrix arguments # x = alpha * z * x + beta * x alpha, beta = alphas[0], betas[0] ref = alpha * (_bsr_to_dense(z) @ _bsr_to_dense(x)) + beta * _bsr_to_dense(x) bsr_mm(z, x, x, alpha, beta) res = _bsr_to_dense(x) assert_np_equal(res, ref, 0.0001) # z = alpha * z * z + beta * z ref = alpha * (_bsr_to_dense(z) @ _bsr_to_dense(z)) + beta * _bsr_to_dense(z) bsr_mm(z, z, z, alpha, beta) res = _bsr_to_dense(z) assert_np_equal(res, ref, 0.0001) # test incompatible shapes if block_shape[0] != block_shape[-1]: with test.assertRaisesRegex(ValueError, "Incompatible block sizes"): bsr_mm(z, y) y.ncol = y.ncol * 2 with test.assertRaisesRegex(ValueError, "Incompatible number of rows/columns"): bsr_mm(y, z) return test_bsr_mm def make_test_bsr_mv(block_shape, scalar_type): def test_bsr_mv(test, device): rng = np.random.default_rng(123) nrow = 2 ncol = 3 nnz = 6 alphas = [-1.0, 0.0, 1.0] betas = [2.0, -1.0, 0.0] A_rows = wp.array(rng.integers(0, high=nrow, size=nnz, dtype=int), dtype=int, device=device) A_cols = wp.array(rng.integers(0, high=ncol, size=nnz, dtype=int), dtype=int, device=device) A_vals = wp.array(rng.random(size=(nnz, block_shape[0], block_shape[1])), dtype=scalar_type, device=device) A_vals = A_vals.reshape((nnz, block_shape[0], block_shape[1])) A = bsr_zeros(nrow, ncol, wp.types.matrix(shape=block_shape, dtype=scalar_type), device=device) bsr_set_from_triplets(A, A_rows, A_cols, A_vals) if block_shape[1] == 1: x = wp.array(rng.random(size=ncol), dtype=scalar_type, device=device) else: x = wp.array( rng.random(size=(ncol, block_shape[1])), dtype=wp.vec(length=block_shape[1], dtype=scalar_type), device=device, ) if block_shape[0] == 1: y = wp.array(rng.random(size=nrow), dtype=scalar_type, device=device) else: y = wp.array( rng.random(size=(nrow, block_shape[0])), dtype=wp.vec(length=block_shape[0], dtype=scalar_type), device=device, ) work_buffer = wp.empty_like(y) for alpha, beta in zip(alphas, betas): ref = alpha * _bsr_to_dense(A) @ x.numpy().flatten() + beta * y.numpy().flatten() if beta == 0.0: y = bsr_mv(A, x, alpha=alpha, beta=beta, work_buffer=work_buffer) else: bsr_mv(A, x, y, alpha, beta, work_buffer=work_buffer) res = y.numpy().flatten() assert_np_equal(res, ref, 0.0001) # test aliasing alpha, beta = alphas[0], betas[0] AAt = bsr_mm(A, bsr_transposed(A)) ref = alpha * _bsr_to_dense(AAt) @ y.numpy().flatten() + beta * y.numpy().flatten() bsr_mv(AAt, y, y, alpha, beta) res = y.numpy().flatten() assert_np_equal(res, ref, 0.0001) A.ncol = A.ncol + 1 with test.assertRaisesRegex(ValueError, "Number of columns"): bsr_mv(A, x, y) A.ncol = A.ncol - 1 A.nrow = A.nrow - 1 with test.assertRaisesRegex(ValueError, "Number of rows"): bsr_mv(A, x, y) return test_bsr_mv devices = get_test_devices() class TestSparse(unittest.TestCase): def test_bsr_copy_scale(self): nrow = 6 bsize = 2 diag_bsr = bsr_diag(diag=np.eye(bsize, dtype=float) * 2.0, rows_of_blocks=nrow) diag_copy = bsr_copy(diag_bsr, scalar_type=wp.float64) self.assertTrue(wp.types.types_equal(diag_copy.values.dtype, wp.mat(shape=(bsize, bsize), dtype=wp.float64))) bsr_scale(x=diag_copy, alpha=0.5) res = _bsr_to_dense(diag_copy) ref = np.eye(nrow * bsize) assert_np_equal(res, ref, 0.0001) bsr_scale(x=diag_copy, alpha=0.0) self.assertEqual(diag_copy.nrow, nrow) self.assertEqual(diag_copy.ncol, nrow) self.assertEqual(diag_copy.nnz, 0) add_function_test(TestSparse, "test_csr_from_triplets", test_csr_from_triplets, devices=devices) add_function_test(TestSparse, "test_bsr_from_triplets", test_bsr_from_triplets, devices=devices) add_function_test(TestSparse, "test_bsr_get_diag", test_bsr_get_set_diag, devices=devices) add_function_test(TestSparse, "test_csr_transpose", make_test_bsr_transpose((1, 1), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_transpose_1_3", make_test_bsr_transpose((1, 3), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_transpose_3_3", make_test_bsr_transpose((3, 3), wp.float64), devices=devices) add_function_test(TestSparse, "test_csr_axpy", make_test_bsr_axpy((1, 1), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_axpy_1_3", make_test_bsr_axpy((1, 3), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_axpy_3_3", make_test_bsr_axpy((3, 3), wp.float64), devices=devices) add_function_test(TestSparse, "test_csr_mm", make_test_bsr_mm((1, 1), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_mm_1_3", make_test_bsr_mm((1, 3), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_mm_3_3", make_test_bsr_mm((3, 3), wp.float64), devices=devices) add_function_test(TestSparse, "test_csr_mv", make_test_bsr_mv((1, 1), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_mv_1_3", make_test_bsr_mv((1, 3), wp.float32), devices=devices) add_function_test(TestSparse, "test_bsr_mv_3_3", make_test_bsr_mv((3, 3), wp.float64), devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
17,822
Python
37.164882
119
0.615026
NVIDIA/warp/warp/tests/test_grad.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest from typing import Any import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def scalar_grad(x: wp.array(dtype=float), y: wp.array(dtype=float)): y[0] = x[0] ** 2.0 def test_scalar_grad(test, device): x = wp.array([3.0], dtype=float, device=device, requires_grad=True) y = wp.zeros_like(x) tape = wp.Tape() with tape: wp.launch(scalar_grad, dim=1, inputs=[x, y], device=device) tape.backward(y) assert_np_equal(tape.gradients[x].numpy(), np.array(6.0)) @wp.kernel def for_loop_grad(n: int, x: wp.array(dtype=float), s: wp.array(dtype=float)): sum = float(0.0) for i in range(n): sum = sum + x[i] * 2.0 s[0] = sum def test_for_loop_grad(test, device): n = 32 val = np.ones(n, dtype=np.float32) x = wp.array(val, device=device, requires_grad=True) sum = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) tape = wp.Tape() with tape: wp.launch(for_loop_grad, dim=1, inputs=[n, x, sum], device=device) # ensure forward pass outputs correct assert_np_equal(sum.numpy(), 2.0 * np.sum(x.numpy())) tape.backward(loss=sum) # ensure forward pass outputs persist assert_np_equal(sum.numpy(), 2.0 * np.sum(x.numpy())) # ensure gradients correct assert_np_equal(tape.gradients[x].numpy(), 2.0 * val) def test_for_loop_graph_grad(test, device): wp.load_module(device=device) n = 32 val = np.ones(n, dtype=np.float32) x = wp.array(val, device=device, requires_grad=True) sum = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) wp.capture_begin(device, force_module_load=False) try: tape = wp.Tape() with tape: wp.launch(for_loop_grad, dim=1, inputs=[n, x, sum], device=device) tape.backward(loss=sum) finally: graph = wp.capture_end(device) wp.capture_launch(graph) wp.synchronize_device(device) # ensure forward pass outputs persist assert_np_equal(sum.numpy(), 2.0 * np.sum(x.numpy())) # ensure gradients correct assert_np_equal(x.grad.numpy(), 2.0 * val) wp.capture_launch(graph) wp.synchronize_device(device) @wp.kernel def for_loop_nested_if_grad(n: int, x: wp.array(dtype=float), s: wp.array(dtype=float)): sum = float(0.0) for i in range(n): if i < 16: if i < 8: sum = sum + x[i] * 2.0 else: sum = sum + x[i] * 4.0 else: if i < 24: sum = sum + x[i] * 6.0 else: sum = sum + x[i] * 8.0 s[0] = sum def test_for_loop_nested_if_grad(test, device): n = 32 val = np.ones(n, dtype=np.float32) # fmt: off expected_val = [ 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, ] expected_grad = [ 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, ] # fmt: on x = wp.array(val, device=device, requires_grad=True) sum = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) tape = wp.Tape() with tape: wp.launch(for_loop_nested_if_grad, dim=1, inputs=[n, x, sum], device=device) assert_np_equal(sum.numpy(), np.sum(expected_val)) tape.backward(loss=sum) assert_np_equal(sum.numpy(), np.sum(expected_val)) assert_np_equal(tape.gradients[x].numpy(), np.array(expected_grad)) @wp.kernel def for_loop_grad_nested(n: int, x: wp.array(dtype=float), s: wp.array(dtype=float)): sum = float(0.0) for i in range(n): for j in range(n): sum = sum + x[i * n + j] * float(i * n + j) + 1.0 s[0] = sum def test_for_loop_nested_for_grad(test, device): x = wp.zeros(9, dtype=float, device=device, requires_grad=True) s = wp.zeros(1, dtype=float, device=device, requires_grad=True) tape = wp.Tape() with tape: wp.launch(for_loop_grad_nested, dim=1, inputs=[3, x, s], device=device) tape.backward(s) assert_np_equal(s.numpy(), np.array([9.0])) assert_np_equal(tape.gradients[x].numpy(), np.arange(0.0, 9.0, 1.0)) # differentiating thought most while loops is not supported # since doing things like i = i + 1 breaks adjointing # @wp.kernel # def while_loop_grad(n: int, # x: wp.array(dtype=float), # c: wp.array(dtype=int), # s: wp.array(dtype=float)): # tid = wp.tid() # while i < n: # s[0] = s[0] + x[i]*2.0 # i = i + 1 # def test_while_loop_grad(test, device): # n = 32 # x = wp.array(np.ones(n, dtype=np.float32), device=device, requires_grad=True) # c = wp.zeros(1, dtype=int, device=device) # sum = wp.zeros(1, dtype=wp.float32, device=device) # tape = wp.Tape() # with tape: # wp.launch(while_loop_grad, dim=1, inputs=[n, x, c, sum], device=device) # tape.backward(loss=sum) # assert_np_equal(sum.numpy(), 2.0*np.sum(x.numpy())) # assert_np_equal(tape.gradients[x].numpy(), 2.0*np.ones_like(x.numpy())) @wp.kernel def preserve_outputs( n: int, x: wp.array(dtype=float), c: wp.array(dtype=float), s1: wp.array(dtype=float), s2: wp.array(dtype=float) ): tid = wp.tid() # plain store c[tid] = x[tid] * 2.0 # atomic stores wp.atomic_add(s1, 0, x[tid] * 3.0) wp.atomic_sub(s2, 0, x[tid] * 2.0) # tests that outputs from the forward pass are # preserved by the backward pass, i.e.: stores # are omitted during the forward reply def test_preserve_outputs_grad(test, device): n = 32 val = np.ones(n, dtype=np.float32) x = wp.array(val, device=device, requires_grad=True) c = wp.zeros_like(x) s1 = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) s2 = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) tape = wp.Tape() with tape: wp.launch(preserve_outputs, dim=n, inputs=[n, x, c, s1, s2], device=device) # ensure forward pass results are correct assert_np_equal(x.numpy(), val) assert_np_equal(c.numpy(), val * 2.0) assert_np_equal(s1.numpy(), np.array(3.0 * n)) assert_np_equal(s2.numpy(), np.array(-2.0 * n)) # run backward on first loss tape.backward(loss=s1) # ensure inputs, copy and sum are unchanged by backwards pass assert_np_equal(x.numpy(), val) assert_np_equal(c.numpy(), val * 2.0) assert_np_equal(s1.numpy(), np.array(3.0 * n)) assert_np_equal(s2.numpy(), np.array(-2.0 * n)) # ensure gradients are correct assert_np_equal(tape.gradients[x].numpy(), 3.0 * val) # run backward on second loss tape.zero() tape.backward(loss=s2) assert_np_equal(x.numpy(), val) assert_np_equal(c.numpy(), val * 2.0) assert_np_equal(s1.numpy(), np.array(3.0 * n)) assert_np_equal(s2.numpy(), np.array(-2.0 * n)) # ensure gradients are correct assert_np_equal(tape.gradients[x].numpy(), -2.0 * val) def gradcheck(func, func_name, inputs, device, eps=1e-4, tol=1e-2): """ Checks that the gradient of the Warp kernel is correct by comparing it to the numerical gradient computed using finite differences. """ kernel = wp.Kernel(func=func, key=func_name) def f(xs): # call the kernel without taping for finite differences wp_xs = [wp.array(xs[i], ndim=1, dtype=inputs[i].dtype, device=device) for i in range(len(inputs))] output = wp.zeros(1, dtype=wp.float32, device=device) wp.launch(kernel, dim=1, inputs=wp_xs, outputs=[output], device=device) return output.numpy()[0] # compute numerical gradient numerical_grad = [] np_xs = [] for i in range(len(inputs)): np_xs.append(inputs[i].numpy().flatten().copy()) numerical_grad.append(np.zeros_like(np_xs[-1])) inputs[i].requires_grad = True for i in range(len(np_xs)): for j in range(len(np_xs[i])): np_xs[i][j] += eps y1 = f(np_xs) np_xs[i][j] -= 2 * eps y2 = f(np_xs) np_xs[i][j] += eps numerical_grad[i][j] = (y1 - y2) / (2 * eps) # compute analytical gradient tape = wp.Tape() output = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) with tape: wp.launch(kernel, dim=1, inputs=inputs, outputs=[output], device=device) tape.backward(loss=output) # compare gradients for i in range(len(inputs)): grad = tape.gradients[inputs[i]] assert_np_equal(grad.numpy(), numerical_grad[i], tol=tol) tape.zero() def test_vector_math_grad(test, device): rng = np.random.default_rng(123) # test unary operations for dim, vec_type in [(2, wp.vec2), (3, wp.vec3), (4, wp.vec4), (4, wp.quat)]: def check_length(vs: wp.array(dtype=vec_type), out: wp.array(dtype=float)): out[0] = wp.length(vs[0]) def check_length_sq(vs: wp.array(dtype=vec_type), out: wp.array(dtype=float)): out[0] = wp.length_sq(vs[0]) def check_normalize(vs: wp.array(dtype=vec_type), out: wp.array(dtype=float)): out[0] = wp.length_sq(wp.normalize(vs[0])) # compress to scalar output # run the tests with 5 different random inputs for _ in range(5): x = wp.array(rng.random(size=(1, dim), dtype=np.float32), dtype=vec_type, device=device) gradcheck(check_length, f"check_length_{vec_type.__name__}", [x], device) gradcheck(check_length_sq, f"check_length_sq_{vec_type.__name__}", [x], device) gradcheck(check_normalize, f"check_normalize_{vec_type.__name__}", [x], device) def test_matrix_math_grad(test, device): rng = np.random.default_rng(123) # test unary operations for dim, mat_type in [(2, wp.mat22), (3, wp.mat33), (4, wp.mat44)]: def check_determinant(vs: wp.array(dtype=mat_type), out: wp.array(dtype=float)): out[0] = wp.determinant(vs[0]) def check_trace(vs: wp.array(dtype=mat_type), out: wp.array(dtype=float)): out[0] = wp.trace(vs[0]) # run the tests with 5 different random inputs for _ in range(5): x = wp.array(rng.random(size=(1, dim, dim), dtype=np.float32), ndim=1, dtype=mat_type, device=device) gradcheck(check_determinant, f"check_length_{mat_type.__name__}", [x], device) gradcheck(check_trace, f"check_length_sq_{mat_type.__name__}", [x], device) def test_3d_math_grad(test, device): rng = np.random.default_rng(123) # test binary operations def check_cross(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): out[0] = wp.length(wp.cross(vs[0], vs[1])) def check_dot(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): out[0] = wp.dot(vs[0], vs[1]) def check_mat33(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): a = vs[0] b = vs[1] c = wp.cross(a, b) m = wp.mat33(a[0], b[0], c[0], a[1], b[1], c[1], a[2], b[2], c[2]) out[0] = wp.determinant(m) def check_trace_diagonal(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): a = vs[0] b = vs[1] c = wp.cross(a, b) m = wp.mat33( 1.0 / (a[0] + 10.0), 0.0, 0.0, 0.0, 1.0 / (b[1] + 10.0), 0.0, 0.0, 0.0, 1.0 / (c[2] + 10.0), ) out[0] = wp.trace(m) def check_rot_rpy(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): v = vs[0] q = wp.quat_rpy(v[0], v[1], v[2]) out[0] = wp.length(wp.quat_rotate(q, vs[1])) def check_rot_axis_angle(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): v = wp.normalize(vs[0]) q = wp.quat_from_axis_angle(v, 0.5) out[0] = wp.length(wp.quat_rotate(q, vs[1])) def check_rot_quat_inv(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): v = vs[0] q = wp.normalize(wp.quat(v[0], v[1], v[2], 1.0)) out[0] = wp.length(wp.quat_rotate_inv(q, vs[1])) # run the tests with 5 different random inputs for _ in range(5): x = wp.array( rng.standard_normal(size=(2, 3), dtype=np.float32), dtype=wp.vec3, device=device, requires_grad=True ) gradcheck(check_cross, "check_cross_3d", [x], device) gradcheck(check_dot, "check_dot_3d", [x], device) gradcheck(check_mat33, "check_mat33_3d", [x], device, eps=2e-2) gradcheck(check_trace_diagonal, "check_trace_diagonal_3d", [x], device) gradcheck(check_rot_rpy, "check_rot_rpy_3d", [x], device) gradcheck(check_rot_axis_angle, "check_rot_axis_angle_3d", [x], device) gradcheck(check_rot_quat_inv, "check_rot_quat_inv_3d", [x], device) def test_multi_valued_function_grad(test, device): rng = np.random.default_rng(123) @wp.func def multi_valued(x: float, y: float, z: float): return wp.sin(x), wp.cos(y) * z, wp.sqrt(wp.abs(z)) / wp.abs(x) # test multi-valued functions def check_multi_valued(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)): tid = wp.tid() v = vs[tid] a, b, c = multi_valued(v[0], v[1], v[2]) out[tid] = a + b + c # run the tests with 5 different random inputs for _ in range(5): x = wp.array( rng.standard_normal(size=(2, 3), dtype=np.float32), dtype=wp.vec3, device=device, requires_grad=True ) gradcheck(check_multi_valued, "check_multi_valued_3d", [x], device) def test_mesh_grad(test, device): pos = wp.array( [ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ], dtype=wp.vec3, device=device, requires_grad=True, ) indices = wp.array( [0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2], dtype=wp.int32, device=device, ) mesh = wp.Mesh(points=pos, indices=indices) @wp.func def compute_triangle_area(mesh_id: wp.uint64, tri_id: int): mesh = wp.mesh_get(mesh_id) i, j, k = mesh.indices[tri_id * 3 + 0], mesh.indices[tri_id * 3 + 1], mesh.indices[tri_id * 3 + 2] a = mesh.points[i] b = mesh.points[j] c = mesh.points[k] return wp.length(wp.cross(b - a, c - a)) * 0.5 @wp.kernel def compute_area(mesh_id: wp.uint64, out: wp.array(dtype=wp.float32)): wp.atomic_add(out, 0, compute_triangle_area(mesh_id, wp.tid())) num_tris = int(len(indices) / 3) # compute analytical gradient tape = wp.Tape() output = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True) with tape: wp.launch(compute_area, dim=num_tris, inputs=[mesh.id], outputs=[output], device=device) tape.backward(loss=output) ad_grad = mesh.points.grad.numpy() # compute finite differences eps = 1e-3 pos_np = pos.numpy() fd_grad = np.zeros_like(ad_grad) for i in range(len(pos)): for j in range(3): pos_np[i, j] += eps pos = wp.array(pos_np, dtype=wp.vec3, device=device) mesh = wp.Mesh(points=pos, indices=indices) output.zero_() wp.launch(compute_area, dim=num_tris, inputs=[mesh.id], outputs=[output], device=device) f1 = output.numpy()[0] pos_np[i, j] -= 2 * eps pos = wp.array(pos_np, dtype=wp.vec3, device=device) mesh = wp.Mesh(points=pos, indices=indices) output.zero_() wp.launch(compute_area, dim=num_tris, inputs=[mesh.id], outputs=[output], device=device) f2 = output.numpy()[0] pos_np[i, j] += eps fd_grad[i, j] = (f1 - f2) / (2 * eps) assert np.allclose(ad_grad, fd_grad, atol=1e-3) @wp.func def name_clash(a: float, b: float) -> float: return a + b @wp.func_grad(name_clash) def adj_name_clash(a: float, b: float, adj_ret: float): # names `adj_a` and `adj_b` must not clash with function args of generated function adj_a = 0.0 adj_b = 0.0 if a < 0.0: adj_a = adj_ret if b > 0.0: adj_b = adj_ret wp.adjoint[a] += adj_a wp.adjoint[b] += adj_b @wp.kernel def name_clash_kernel( input_a: wp.array(dtype=float), input_b: wp.array(dtype=float), output: wp.array(dtype=float), ): tid = wp.tid() output[tid] = name_clash(input_a[tid], input_b[tid]) def test_name_clash(test, device): # tests that no name clashes occur when variable names such as `adj_a` are used in custom gradient code with wp.ScopedDevice(device): input_a = wp.array([1.0, -2.0, 3.0], dtype=wp.float32, requires_grad=True) input_b = wp.array([4.0, 5.0, -6.0], dtype=wp.float32, requires_grad=True) output = wp.zeros(3, dtype=wp.float32, requires_grad=True) tape = wp.Tape() with tape: wp.launch(name_clash_kernel, dim=len(input_a), inputs=[input_a, input_b], outputs=[output]) tape.backward(grads={output: wp.array(np.ones(len(input_a), dtype=np.float32))}) assert_np_equal(input_a.grad.numpy(), np.array([0.0, 1.0, 0.0])) assert_np_equal(input_b.grad.numpy(), np.array([1.0, 1.0, 0.0])) @wp.struct class NestedStruct: v: wp.vec2 @wp.struct class ParentStruct: a: float n: NestedStruct @wp.func def noop(a: Any): pass @wp.func def sum2(v: wp.vec2): return v[0] + v[1] @wp.kernel def test_struct_attribute_gradient_kernel(src: wp.array(dtype=float), res: wp.array(dtype=float)): tid = wp.tid() p = ParentStruct(src[tid], NestedStruct(wp.vec2(2.0 * src[tid]))) # test that we are not losing gradients when accessing attributes noop(p.a) noop(p.n) noop(p.n.v) res[tid] = p.a + sum2(p.n.v) def test_struct_attribute_gradient(test, device): with wp.ScopedDevice(device): src = wp.array([1], dtype=float, requires_grad=True) res = wp.empty_like(src) tape = wp.Tape() with tape: wp.launch(test_struct_attribute_gradient_kernel, dim=1, inputs=[src, res]) res.grad.fill_(1.0) tape.backward() test.assertEqual(src.grad.numpy()[0], 5.0) @wp.kernel def copy_kernel(a: wp.array(dtype=wp.float32), b: wp.array(dtype=wp.float32)): tid = wp.tid() ai = a[tid] bi = ai b[tid] = bi def test_copy(test, device): with wp.ScopedDevice(device): a = wp.array([-1.0, 2.0, 3.0], dtype=wp.float32, requires_grad=True) b = wp.array([0.0, 0.0, 0.0], dtype=wp.float32, requires_grad=True) wp.launch(copy_kernel, 1, inputs=[a, b]) b.grad = wp.array([1.0, 1.0, 1.0], dtype=wp.float32) wp.launch(copy_kernel, a.shape[0], inputs=[a, b], adjoint=True, adj_inputs=[None, None]) assert_np_equal(a.grad.numpy(), np.array([1.0, 1.0, 1.0])) @wp.kernel def aliasing_kernel(a: wp.array(dtype=wp.float32), b: wp.array(dtype=wp.float32)): tid = wp.tid() x = a[tid] y = x if y > 0.0: y = x * x else: y = x * x * x b[tid] = y def test_aliasing(test, device): with wp.ScopedDevice(device): a = wp.array([-1.0, 2.0, 3.0], dtype=wp.float32, requires_grad=True) b = wp.array([0.0, 0.0, 0.0], dtype=wp.float32, requires_grad=True) wp.launch(aliasing_kernel, 1, inputs=[a, b]) b.grad = wp.array([1.0, 1.0, 1.0], dtype=wp.float32) wp.launch(aliasing_kernel, a.shape[0], inputs=[a, b], adjoint=True, adj_inputs=[None, None]) assert_np_equal(a.grad.numpy(), np.array([3.0, 4.0, 6.0])) @wp.kernel def square_kernel(x: wp.array(dtype=float), y: wp.array(dtype=float)): tid = wp.tid() y[tid] = x[tid] ** 2.0 def test_gradient_internal(test, device): with wp.ScopedDevice(device): a = wp.array([1.0, 2.0, 3.0], dtype=float, requires_grad=True) b = wp.array([0.0, 0.0, 0.0], dtype=float, requires_grad=True) wp.launch(square_kernel, a.size, inputs=[a, b]) # use internal gradients (.grad), adj_inputs are None b.grad = wp.array([1.0, 1.0, 1.0], dtype=float) wp.launch(square_kernel, a.shape[0], inputs=[a, b], adjoint=True, adj_inputs=[None, None]) assert_np_equal(a.grad.numpy(), np.array([2.0, 4.0, 6.0])) def test_gradient_external(test, device): with wp.ScopedDevice(device): a = wp.array([1.0, 2.0, 3.0], dtype=float, requires_grad=False) b = wp.array([0.0, 0.0, 0.0], dtype=float, requires_grad=False) wp.launch(square_kernel, a.size, inputs=[a, b]) # use external gradients passed in adj_inputs a_grad = wp.array([0.0, 0.0, 0.0], dtype=float) b_grad = wp.array([1.0, 1.0, 1.0], dtype=float) wp.launch(square_kernel, a.shape[0], inputs=[a, b], adjoint=True, adj_inputs=[a_grad, b_grad]) assert_np_equal(a_grad.numpy(), np.array([2.0, 4.0, 6.0])) def test_gradient_precedence(test, device): with wp.ScopedDevice(device): a = wp.array([1.0, 2.0, 3.0], dtype=float, requires_grad=True) b = wp.array([0.0, 0.0, 0.0], dtype=float, requires_grad=True) wp.launch(square_kernel, a.size, inputs=[a, b]) # if both internal and external gradients are present, the external one takes precedence, # because it's explicitly passed by the user in adj_inputs a_grad = wp.array([0.0, 0.0, 0.0], dtype=float) b_grad = wp.array([1.0, 1.0, 1.0], dtype=float) wp.launch(square_kernel, a.shape[0], inputs=[a, b], adjoint=True, adj_inputs=[a_grad, b_grad]) assert_np_equal(a_grad.numpy(), np.array([2.0, 4.0, 6.0])) # used assert_np_equal(a.grad.numpy(), np.array([0.0, 0.0, 0.0])) # unused devices = get_test_devices() class TestGrad(unittest.TestCase): pass # add_function_test(TestGrad, "test_while_loop_grad", test_while_loop_grad, devices=devices) add_function_test(TestGrad, "test_for_loop_nested_for_grad", test_for_loop_nested_for_grad, devices=devices) add_function_test(TestGrad, "test_scalar_grad", test_scalar_grad, devices=devices) add_function_test(TestGrad, "test_for_loop_grad", test_for_loop_grad, devices=devices) add_function_test( TestGrad, "test_for_loop_graph_grad", test_for_loop_graph_grad, devices=get_selected_cuda_test_devices() ) add_function_test(TestGrad, "test_for_loop_nested_if_grad", test_for_loop_nested_if_grad, devices=devices) add_function_test(TestGrad, "test_preserve_outputs_grad", test_preserve_outputs_grad, devices=devices) add_function_test(TestGrad, "test_vector_math_grad", test_vector_math_grad, devices=devices) add_function_test(TestGrad, "test_matrix_math_grad", test_matrix_math_grad, devices=devices) add_function_test(TestGrad, "test_3d_math_grad", test_3d_math_grad, devices=devices) add_function_test(TestGrad, "test_multi_valued_function_grad", test_multi_valued_function_grad, devices=devices) add_function_test(TestGrad, "test_mesh_grad", test_mesh_grad, devices=devices) add_function_test(TestGrad, "test_name_clash", test_name_clash, devices=devices) add_function_test(TestGrad, "test_struct_attribute_gradient", test_struct_attribute_gradient, devices=devices) add_function_test(TestGrad, "test_copy", test_copy, devices=devices) add_function_test(TestGrad, "test_aliasing", test_aliasing, devices=devices) add_function_test(TestGrad, "test_gradient_internal", test_gradient_internal, devices=devices) add_function_test(TestGrad, "test_gradient_external", test_gradient_external, devices=devices) add_function_test(TestGrad, "test_gradient_precedence", test_gradient_precedence, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
24,431
Python
31.794631
116
0.599157
NVIDIA/warp/warp/tests/test_mesh_query_point.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import math import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def sample_mesh_query( mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_faces: wp.array(dtype=int), query_signs: wp.array(dtype=float), query_dist: wp.array(dtype=float), ): tid = wp.tid() face_index = int(0) face_u = float(0.0) face_v = float(0.0) sign = float(0.0) max_dist = 10012.0 p = query_points[tid] wp.mesh_query_point(mesh, p, max_dist, sign, face_index, face_u, face_v) cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v) query_signs[tid] = sign query_faces[tid] = face_index query_dist[tid] = wp.length(cp - p) query = wp.mesh_query_point(mesh, p, max_dist) wp.expect_eq(query.sign, sign) wp.expect_eq(query.face, face_index) wp.expect_eq(query.u, face_u) wp.expect_eq(query.v, face_v) @wp.kernel def sample_mesh_query_no_sign( mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_faces: wp.array(dtype=int), query_dist: wp.array(dtype=float), ): tid = wp.tid() face_index = int(0) face_u = float(0.0) face_v = float(0.0) max_dist = 10012.0 p = query_points[tid] wp.mesh_query_point_no_sign(mesh, p, max_dist, face_index, face_u, face_v) cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v) query_faces[tid] = face_index query_dist[tid] = wp.length(cp - p) query = wp.mesh_query_point_no_sign(mesh, p, max_dist) wp.expect_eq(query.face, face_index) wp.expect_eq(query.u, face_u) wp.expect_eq(query.v, face_v) @wp.kernel def sample_mesh_query_sign_normal( mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_faces: wp.array(dtype=int), query_signs: wp.array(dtype=float), query_dist: wp.array(dtype=float), ): tid = wp.tid() face_index = int(0) face_u = float(0.0) face_v = float(0.0) sign = float(0.0) max_dist = 10012.0 p = query_points[tid] wp.mesh_query_point_sign_normal(mesh, p, max_dist, sign, face_index, face_u, face_v) cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v) query_signs[tid] = sign query_faces[tid] = face_index query_dist[tid] = wp.length(cp - p) query = wp.mesh_query_point_sign_normal(mesh, p, max_dist) wp.expect_eq(query.sign, sign) wp.expect_eq(query.face, face_index) wp.expect_eq(query.u, face_u) wp.expect_eq(query.v, face_v) @wp.kernel def sample_mesh_query_sign_winding_number( mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_faces: wp.array(dtype=int), query_signs: wp.array(dtype=float), query_dist: wp.array(dtype=float), ): tid = wp.tid() face_index = int(0) face_u = float(0.0) face_v = float(0.0) sign = float(0.0) max_dist = 10012.0 p = query_points[tid] wp.mesh_query_point_sign_winding_number(mesh, p, max_dist, sign, face_index, face_u, face_v) cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v) query_signs[tid] = sign query_faces[tid] = face_index query_dist[tid] = wp.length(cp - p) query = wp.mesh_query_point_sign_winding_number(mesh, p, max_dist) wp.expect_eq(query.sign, sign) wp.expect_eq(query.face, face_index) wp.expect_eq(query.u, face_u) wp.expect_eq(query.v, face_v) @wp.func def triangle_closest_point(a: wp.vec3, b: wp.vec3, c: wp.vec3, p: wp.vec3): ab = b - a ac = c - a ap = p - a d1 = wp.dot(ab, ap) d2 = wp.dot(ac, ap) if d1 <= 0.0 and d2 <= 0.0: return wp.vec2(1.0, 0.0) bp = p - b d3 = wp.dot(ab, bp) d4 = wp.dot(ac, bp) if d3 >= 0.0 and d4 <= d3: return wp.vec2(0.0, 1.0) vc = d1 * d4 - d3 * d2 v = d1 / (d1 - d3) if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0: return wp.vec2(1.0 - v, v) cp = p - c d5 = wp.dot(ab, cp) d6 = wp.dot(ac, cp) if d6 >= 0.0 and d5 <= d6: return wp.vec2(0.0, 0.0) vb = d5 * d2 - d1 * d6 w = d2 / (d2 - d6) if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0: return wp.vec2(1.0 - w, 0.0) va = d3 * d6 - d5 * d4 w = (d4 - d3) / ((d4 - d3) + (d5 - d6)) if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0: return wp.vec2(0.0, 1.0 - w) denom = 1.0 / (va + vb + vc) v = vb * denom w = vc * denom u = 1.0 - v - w return wp.vec2(u, v) @wp.func def solid_angle(v0: wp.vec3, v1: wp.vec3, v2: wp.vec3, p: wp.vec3): a = v0 - p b = v1 - p c = v2 - p a_len = wp.length(a) b_len = wp.length(b) c_len = wp.length(c) det = wp.dot(a, wp.cross(b, c)) den = a_len * b_len * c_len + wp.dot(a, b) * c_len + wp.dot(b, c) * a_len + wp.dot(c, a) * b_len return 2.0 * wp.atan2(det, den) @wp.kernel def sample_mesh_brute( tri_points: wp.array(dtype=wp.vec3), tri_indices: wp.array(dtype=int), tri_count: int, query_points: wp.array(dtype=wp.vec3), query_faces: wp.array(dtype=int), query_signs: wp.array(dtype=float), query_dist: wp.array(dtype=float), ): tid = wp.tid() min_face = int(0) min_dist = float(1.0e6) sum_solid_angle = float(0.0) p = query_points[tid] for i in range(0, tri_count): a = tri_points[tri_indices[i * 3 + 0]] b = tri_points[tri_indices[i * 3 + 1]] c = tri_points[tri_indices[i * 3 + 2]] sum_solid_angle += solid_angle(a, b, c, p) bary = triangle_closest_point(a, b, c, p) u = bary[0] v = bary[1] cp = u * a + v * b + (1.0 - u - v) * c cp_dist = wp.length(cp - p) if cp_dist < min_dist: min_dist = cp_dist min_face = i # for an inside point, the sum of the solid angle should be 4PI # for an outside point, the sum should be 0 query_faces[tid] = min_face query_signs[tid] = sum_solid_angle query_dist[tid] = min_dist # constructs a grid of evenly spaced particles def particle_grid(dim_x, dim_y, dim_z, lower, radius, jitter): rng = np.random.default_rng(123) points = np.meshgrid(np.linspace(0, dim_x, dim_x), np.linspace(0, dim_y, dim_y), np.linspace(0, dim_z, dim_z)) points_t = np.array((points[0], points[1], points[2])).T * radius * 2.0 + np.array(lower) points_t = points_t + rng.random(points_t.shape) * radius * jitter return points_t.reshape((-1, 3)) # triangulate a list of polygon face indices def triangulate(face_counts, face_indices): num_tris = np.sum(np.subtract(face_counts, 2)) num_tri_vtx = num_tris * 3 tri_indices = np.zeros(num_tri_vtx, dtype=int) ctr = 0 wedgeIdx = 0 for nb in face_counts: for i in range(nb - 2): tri_indices[ctr] = face_indices[wedgeIdx] tri_indices[ctr + 1] = face_indices[wedgeIdx + i + 1] tri_indices[ctr + 2] = face_indices[wedgeIdx + i + 2] ctr += 3 wedgeIdx += nb return tri_indices @unittest.skipUnless(USD_AVAILABLE, "Requires usd-core") def test_mesh_query_point(test, device): from pxr import Usd, UsdGeom mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/spiky.usd"))) mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/Cube/Cube")) mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get() mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get() tri_indices = triangulate(mesh_counts, mesh_indices) mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device) mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device) # create mesh mesh = wp.Mesh(points=mesh_points, velocities=None, indices=mesh_indices, support_winding_number=True) p = particle_grid(32, 32, 32, np.array([-1.1, -1.1, -1.1]), 0.05, 0.0) query_count = len(p) query_points = wp.array(p, dtype=wp.vec3, device=device) signs_query = wp.zeros(query_count, dtype=float, device=device) faces_query = wp.zeros(query_count, dtype=int, device=device) dist_query = wp.zeros(query_count, dtype=float, device=device) faces_query_no_sign = wp.zeros(query_count, dtype=int, device=device) dist_query_no_sign = wp.zeros(query_count, dtype=float, device=device) signs_query_normal = wp.zeros(query_count, dtype=float, device=device) faces_query_normal = wp.zeros(query_count, dtype=int, device=device) dist_query_normal = wp.zeros(query_count, dtype=float, device=device) signs_query_winding_number = wp.zeros(query_count, dtype=float, device=device) faces_query_winding_number = wp.zeros(query_count, dtype=int, device=device) dist_query_winding_number = wp.zeros(query_count, dtype=float, device=device) signs_brute = wp.zeros(query_count, dtype=float, device=device) faces_brute = wp.zeros(query_count, dtype=int, device=device) dist_brute = wp.zeros(query_count, dtype=float, device=device) wp.launch( kernel=sample_mesh_query, dim=query_count, inputs=[mesh.id, query_points, faces_query, signs_query, dist_query], device=device, ) wp.launch( kernel=sample_mesh_query_no_sign, dim=query_count, inputs=[mesh.id, query_points, faces_query_no_sign, dist_query_no_sign], device=device, ) wp.launch( kernel=sample_mesh_query_sign_normal, dim=query_count, inputs=[mesh.id, query_points, faces_query_normal, signs_query_normal, dist_query_normal], device=device, ) wp.launch( kernel=sample_mesh_query_sign_winding_number, dim=query_count, inputs=[ mesh.id, query_points, faces_query_winding_number, signs_query_winding_number, dist_query_winding_number, ], device=device, ) wp.launch( kernel=sample_mesh_brute, dim=query_count, inputs=[ mesh_points, mesh_indices, int(len(mesh_indices) / 3), query_points, faces_brute, signs_brute, dist_brute, ], device=device, ) signs_query = signs_query.numpy() faces_query = faces_query.numpy() dist_query = dist_query.numpy() faces_query_no_sign = faces_query_no_sign.numpy() dist_query_no_sign = dist_query_no_sign.numpy() signs_query_normal = signs_query_normal.numpy() faces_query_normal = faces_query_normal.numpy() dist_query_normal = dist_query_normal.numpy() signs_query_winding_number = signs_query_winding_number.numpy() faces_query_winding_number = faces_query_winding_number.numpy() dist_query_winding_number = dist_query_winding_number.numpy() signs_brute = signs_brute.numpy() faces_brute = faces_brute.numpy() dist_brute = dist_brute.numpy() query_points = query_points.numpy() inside_query = [[0.0, 0.0, 0.0]] inside_query_normal = [[0.0, 0.0, 0.0]] inside_query_winding_number = [[0.0, 0.0, 0.0]] inside_brute = [[0.0, 0.0, 0.0]] for i in range(query_count): if signs_query[i] < 0.0: inside_query.append(query_points[i].tolist()) if signs_query_normal[i] < 0.0: inside_query_normal.append(query_points[i].tolist()) if signs_query_winding_number[i] < 0.0: inside_query_winding_number.append(query_points[i].tolist()) if signs_brute[i] > math.pi * 2.0: inside_brute.append(query_points[i].tolist()) inside_query = np.array(inside_query) inside_query_normal = np.array(inside_query_normal) inside_query_winding_number = np.array(inside_query_winding_number) inside_brute = np.array(inside_brute) # import warp.render # stage = warp.render.UsdRenderer("tests/outputs/test_mesh_query_point.usd") # radius = 0.1 # stage.begin_frame(0.0) # stage.render_mesh(points=mesh_points.numpy(), indices=mesh_indices.numpy(), name="mesh") # stage.render_points(points=inside_query, radius=radius, name="query") # stage.render_points(points=inside_brute, radius=radius, name="brute") # stage.render_points(points=query_points, radius=radius, name="all") # stage.end_frame() # stage.save() test.assertTrue(len(inside_query) == len(inside_brute)) test.assertTrue(len(inside_query_normal) == len(inside_brute)) test.assertTrue(len(inside_query_winding_number) == len(inside_brute)) tolerance = 1.5e-4 dist_error = np.max(np.abs(dist_query - dist_brute)) sign_error = np.max(np.abs(inside_query - inside_brute)) test.assertTrue(dist_error < tolerance, f"mesh_query_point dist_error is {dist_error} which is >= {tolerance}") test.assertTrue(sign_error < tolerance, f"mesh_query_point sign_error is {sign_error} which is >= {tolerance}") dist_error = np.max(np.abs(dist_query_no_sign - dist_brute)) test.assertTrue( dist_error < tolerance, f"mesh_query_point_no_sign dist_error is {dist_error} which is >= {tolerance}" ) dist_error = np.max(np.abs(dist_query_normal - dist_brute)) sign_error = np.max(np.abs(inside_query_normal - inside_brute)) test.assertTrue( dist_error < tolerance, f"mesh_query_point_sign_normal dist_error is {dist_error} which is >= {tolerance}" ) test.assertTrue( sign_error < tolerance, f"mesh_query_point_sign_normal sign_error is {sign_error} which is >= {tolerance}" ) dist_error = np.max(np.abs(dist_query_winding_number - dist_brute)) sign_error = np.max(np.abs(inside_query_winding_number - inside_brute)) test.assertTrue( dist_error < tolerance, f"mesh_query_point_sign_winding_number dist_error is {dist_error} which is >= {tolerance}", ) test.assertTrue( sign_error < tolerance, f"mesh_query_point_sign_winding_number sign_error is {sign_error} which is >= {tolerance}", ) @wp.kernel def mesh_query_point_loss( mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), projected_points: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float), ): tid = wp.tid() face_index = int(0) face_u = float(0.0) face_v = float(0.0) sign = float(0.0) max_dist = 10012.0 p = query_points[tid] wp.mesh_query_point(mesh, p, max_dist, sign, face_index, face_u, face_v) q = wp.mesh_eval_position(mesh, face_index, face_u, face_v) projected_points[tid] = q dist = wp.length(wp.sub(p, q)) loss[tid] = dist @unittest.skipUnless(USD_AVAILABLE, "Requires usd-core") def test_adj_mesh_query_point(test, device): from pxr import Usd, UsdGeom mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/torus.usda"))) mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/World/Torus")) mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get() mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get() tri_indices = triangulate(mesh_counts, mesh_indices) mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device) mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device) # test tri # print("Testing Single Triangle") # mesh_points = wp.array(np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]), dtype=wp.vec3, device=device) # mesh_indices = wp.array(np.array([0,1,2]), dtype=int, device=device) # create mesh mesh = wp.Mesh(points=mesh_points, velocities=None, indices=mesh_indices, support_winding_number=True) # p = particle_grid(32, 32, 32, np.array([-5.0, -5.0, -5.0]), 0.1, 0.1)*100.0 p = wp.vec3(50.0, 50.0, 50.0) tape = wp.Tape() # analytic gradients with tape: query_points = wp.array(p, dtype=wp.vec3, device=device, requires_grad=True) projected_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True) wp.launch( kernel=mesh_query_point_loss, dim=1, inputs=[mesh.id, query_points, projected_points, loss], device=device ) tape.backward(loss=loss) analytic = tape.gradients[query_points].numpy().flatten() # numeric gradients eps = 1.0e-3 loss_values = [] numeric = np.zeros(3) offset_query_points = [ wp.vec3(p[0] - eps, p[1], p[2]), wp.vec3(p[0] + eps, p[1], p[2]), wp.vec3(p[0], p[1] - eps, p[2]), wp.vec3(p[0], p[1] + eps, p[2]), wp.vec3(p[0], p[1], p[2] - eps), wp.vec3(p[0], p[1], p[2] + eps), ] for i in range(6): q = offset_query_points[i] query_points = wp.array(q, dtype=wp.vec3, device=device) projected_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device) wp.launch( kernel=mesh_query_point_loss, dim=1, inputs=[mesh.id, query_points, projected_points, loss], device=device ) loss_values.append(loss.numpy()[0]) for i in range(3): l_0 = loss_values[i * 2] l_1 = loss_values[i * 2 + 1] gradient = (l_1 - l_0) / (2.0 * eps) numeric[i] = gradient error = ((analytic - numeric) * (analytic - numeric)).sum(axis=0) tolerance = 1.0e-3 test.assertTrue(error < tolerance, f"error is {error} which is >= {tolerance}") @wp.kernel def sample_furthest_points(mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_result: wp.array(dtype=float)): tid = wp.tid() p = query_points[tid] face = int(0) bary_u = float(0.0) bary_v = float(0.0) if wp.mesh_query_furthest_point_no_sign(mesh, p, 0.0, face, bary_u, bary_v): closest = wp.mesh_eval_position(mesh, face, bary_u, bary_v) query_result[tid] = wp.length_sq(p - closest) query = wp.mesh_query_furthest_point_no_sign(mesh, p, 0.0) wp.expect_eq(query.face, face) wp.expect_eq(query.u, bary_u) wp.expect_eq(query.v, bary_v) @wp.kernel def sample_furthest_points_brute( mesh_points: wp.array(dtype=wp.vec3), query_points: wp.array(dtype=wp.vec3), query_result: wp.array(dtype=float) ): tid = wp.tid() p = query_points[tid] max_dist_sq = float(0.0) for i in range(mesh_points.shape[0]): dist_sq = wp.length_sq(p - mesh_points[i]) if dist_sq > max_dist_sq: max_dist_sq = dist_sq query_result[tid] = max_dist_sq @unittest.skipUnless(USD_AVAILABLE, "Requires usd-core") def test_mesh_query_furthest_point(test, device): from pxr import Usd, UsdGeom mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/spiky.usd"))) mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/Cube/Cube")) mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get() mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get() tri_indices = triangulate(mesh_counts, mesh_indices) mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device) mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device) # create mesh mesh = wp.Mesh(points=mesh_points, indices=mesh_indices) p = particle_grid(32, 32, 32, np.array([-1.1, -1.1, -1.1]), 0.05, 0.0) query_count = len(p) query_points = wp.array(p, dtype=wp.vec3, device=device) dist_query = wp.zeros(query_count, dtype=float, device=device) dist_brute = wp.zeros(query_count, dtype=float, device=device) wp.launch(sample_furthest_points, dim=query_count, inputs=[mesh.id, query_points, dist_query], device=device) wp.launch( sample_furthest_points_brute, dim=query_count, inputs=[mesh_points, query_points, dist_brute], device=device ) assert_np_equal(dist_query.numpy(), dist_brute.numpy(), tol=1.0e-3) devices = get_test_devices() class TestMeshQueryPoint(unittest.TestCase): def test_mesh_query_point_codegen_adjoints_with_select(self): def kernel_fn( mesh: wp.uint64, ): v = wp.vec3(0.0, 0.0, 0.0) d = 1e-6 if True: query_1 = wp.mesh_query_point(mesh, v, d) query_2 = wp.mesh_query_point_no_sign(mesh, v, d) query_3 = wp.mesh_query_furthest_point_no_sign(mesh, v, d) query_4 = wp.mesh_query_point_sign_normal(mesh, v, d) query_5 = wp.mesh_query_point_sign_winding_number(mesh, v, d) else: query_1 = wp.mesh_query_point(mesh, v, d) query_2 = wp.mesh_query_point_no_sign(mesh, v, d) query_3 = wp.mesh_query_furthest_point_no_sign(mesh, v, d) query_4 = wp.mesh_query_point_sign_normal(mesh, v, d) query_5 = wp.mesh_query_point_sign_winding_number(mesh, v, d) wp.Kernel(func=kernel_fn) add_function_test(TestMeshQueryPoint, "test_mesh_query_point", test_mesh_query_point, devices=devices) add_function_test(TestMeshQueryPoint, "test_mesh_query_furthest_point", test_mesh_query_furthest_point, devices=devices) add_function_test(TestMeshQueryPoint, "test_adj_mesh_query_point", test_adj_mesh_query_point, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
21,751
Python
30.479016
121
0.620247
NVIDIA/warp/warp/tests/test_atomic.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * # construct kernel + test function for atomic ops on each vec/matrix type def make_atomic_test(type): def test_atomic_kernel( out_add: wp.array(dtype=type), out_min: wp.array(dtype=type), out_max: wp.array(dtype=type), val: wp.array(dtype=type), ): tid = wp.tid() wp.atomic_add(out_add, 0, val[tid]) wp.atomic_min(out_min, 0, val[tid]) wp.atomic_max(out_max, 0, val[tid]) # register a custom kernel (no decorator) function # this lets us register the same function definition # against multiple symbols, with different arg types kernel = wp.Kernel(func=test_atomic_kernel, key=f"test_atomic_{type.__name__}_kernel") def test_atomic(test, device): n = 1024 rng = np.random.default_rng(42) if type == wp.int32: base = (rng.random(size=1, dtype=np.float32) * 100.0).astype(np.int32) val = (rng.random(size=n, dtype=np.float32) * 100.0).astype(np.int32) elif type == wp.float32: base = rng.random(size=1, dtype=np.float32) val = rng.random(size=n, dtype=np.float32) else: base = rng.random(size=(1, *type._shape_), dtype=float) val = rng.random(size=(n, *type._shape_), dtype=float) add_array = wp.array(base, dtype=type, device=device, requires_grad=True) min_array = wp.array(base, dtype=type, device=device, requires_grad=True) max_array = wp.array(base, dtype=type, device=device, requires_grad=True) add_array.zero_() min_array.fill_(10000) max_array.fill_(-10000) val_array = wp.array(val, dtype=type, device=device, requires_grad=True) tape = wp.Tape() with tape: wp.launch(kernel, n, inputs=[add_array, min_array, max_array, val_array], device=device) assert_np_equal(add_array.numpy(), np.sum(val, axis=0), tol=1.0e-2) assert_np_equal(min_array.numpy(), np.min(val, axis=0), tol=1.0e-2) assert_np_equal(max_array.numpy(), np.max(val, axis=0), tol=1.0e-2) if type != wp.int32: add_array.grad.fill_(1) tape.backward() assert_np_equal(val_array.grad.numpy(), np.ones_like(val)) tape.zero() min_array.grad.fill_(1) tape.backward() min_grad_array = np.zeros_like(val) argmin = val.argmin(axis=0) if val.ndim == 1: min_grad_array[argmin] = 1 elif val.ndim == 2: for i in range(val.shape[1]): min_grad_array[argmin[i], i] = 1 elif val.ndim == 3: for i in range(val.shape[1]): for j in range(val.shape[2]): min_grad_array[argmin[i, j], i, j] = 1 assert_np_equal(val_array.grad.numpy(), min_grad_array) tape.zero() max_array.grad.fill_(1) tape.backward() max_grad_array = np.zeros_like(val) argmax = val.argmax(axis=0) if val.ndim == 1: max_grad_array[argmax] = 1 elif val.ndim == 2: for i in range(val.shape[1]): max_grad_array[argmax[i], i] = 1 elif val.ndim == 3: for i in range(val.shape[1]): for j in range(val.shape[2]): max_grad_array[argmax[i, j], i, j] = 1 assert_np_equal(val_array.grad.numpy(), max_grad_array) return test_atomic # generate test functions for atomic types test_atomic_int = make_atomic_test(wp.int32) test_atomic_float = make_atomic_test(wp.float32) test_atomic_vec2 = make_atomic_test(wp.vec2) test_atomic_vec3 = make_atomic_test(wp.vec3) test_atomic_vec4 = make_atomic_test(wp.vec4) test_atomic_mat22 = make_atomic_test(wp.mat22) test_atomic_mat33 = make_atomic_test(wp.mat33) test_atomic_mat44 = make_atomic_test(wp.mat44) devices = get_test_devices() class TestAtomic(unittest.TestCase): pass add_function_test(TestAtomic, "test_atomic_int", test_atomic_int, devices=devices) add_function_test(TestAtomic, "test_atomic_float", test_atomic_float, devices=devices) add_function_test(TestAtomic, "test_atomic_vec2", test_atomic_vec2, devices=devices) add_function_test(TestAtomic, "test_atomic_vec3", test_atomic_vec3, devices=devices) add_function_test(TestAtomic, "test_atomic_vec4", test_atomic_vec4, devices=devices) add_function_test(TestAtomic, "test_atomic_mat22", test_atomic_mat22, devices=devices) add_function_test(TestAtomic, "test_atomic_mat33", test_atomic_mat33, devices=devices) add_function_test(TestAtomic, "test_atomic_mat44", test_atomic_mat44, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
5,349
Python
37.214285
100
0.619742
NVIDIA/warp/warp/tests/test_matmul.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest from typing import Any import numpy as np import warp as wp from warp.tests.unittest_utils import * wp.init() # For wp.context.runtime.core.is_cutlass_enabled() class gemm_test_bed_runner: def __init__(self, dtype, device): self.dtype = dtype self.device = device def alloc(self, m, n, k, batch_count): rng = np.random.default_rng(42) low = -4.5 high = 3.5 if batch_count == 1: A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array2d(np.zeros((m, n)), dtype=self.dtype, device=self.device, requires_grad=True) else: A = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array3d(np.zeros((batch_count, m, n)), dtype=self.dtype, device=self.device, requires_grad=True) return A, B, C, D def run_and_verify(self, m, n, k, batch_count, alpha, beta): A, B, C, D = self.alloc(m, n, k, batch_count) ones = wp.zeros_like(D) ones.fill_(1.0) if batch_count == 1: tape = wp.Tape() with tape: wp.matmul(A, B, C, D, alpha, beta, False) tape.backward(grads={D: ones}) D_np = alpha * (A.numpy() @ B.numpy()) + beta * C.numpy() assert_np_equal(D.numpy(), D_np) adj_A_np = alpha * np.matmul(ones.numpy(), B.numpy().transpose()) adj_B_np = alpha * (A.numpy().transpose() @ ones.numpy()) adj_C_np = beta * ones.numpy() else: tape = wp.Tape() with tape: wp.batched_matmul(A, B, C, D, alpha, beta, False) tape.backward(grads={D: ones}) D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C.numpy() assert_np_equal(D.numpy(), D_np) adj_A_np = alpha * np.matmul(ones.numpy(), B.numpy().transpose((0, 2, 1))) adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), ones.numpy()) adj_C_np = beta * ones.numpy() assert_np_equal(A.grad.numpy(), adj_A_np) assert_np_equal(B.grad.numpy(), adj_B_np) assert_np_equal(C.grad.numpy(), adj_C_np) def run(self): Ms = [64, 128, 512] Ns = [64, 128, 512] Ks = [64, 128, 512] batch_counts = [1, 4] betas = [0.0, 1.0] alpha = 1.0 for batch_count in batch_counts: for m in Ms: for n in Ns: for k in Ks: for beta in betas: self.run_and_verify(m, n, k, batch_count, alpha, beta) class gemm_test_bed_runner_transpose: def __init__(self, dtype, device): self.dtype = dtype self.device = device def alloc(self, m, n, k, batch_count): rng = np.random.default_rng(42) low = -4.5 high = 3.5 if batch_count == 1: A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array2d(np.zeros((m, n)), dtype=self.dtype, device=self.device, requires_grad=True) AT = wp.array2d(A.numpy().transpose([1, 0]), dtype=self.dtype, device=self.device, requires_grad=True) BT = wp.array2d(B.numpy().transpose([1, 0]), dtype=self.dtype, device=self.device, requires_grad=True) else: A = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array3d(np.zeros((batch_count, m, n)), dtype=self.dtype, device=self.device, requires_grad=True) AT = wp.array3d(A.numpy().transpose([0, 2, 1]), dtype=self.dtype, device=self.device, requires_grad=True) BT = wp.array3d(B.numpy().transpose([0, 2, 1]), dtype=self.dtype, device=self.device, requires_grad=True) return A, B, C, D, AT, BT def run_and_verify(self, m, n, k, batch_count, alpha, beta): A, B, C1, D1, AT1, BT1 = self.alloc(m, n, k, batch_count) C2 = wp.clone(C1) C3 = wp.clone(C1) D2 = wp.clone(D1) D3 = wp.clone(D1) AT2 = wp.clone(AT1) BT2 = wp.clone(BT1) ones1 = wp.zeros_like(D1) ones1.fill_(1.0) ones2 = wp.zeros_like(D2) ones2.fill_(1.0) ones3 = wp.zeros_like(D3) ones3.fill_(1.0) if batch_count == 1: ATT1 = AT1.transpose([1, 0]) BTT1 = BT1.transpose([1, 0]) ATT2 = AT2.transpose([1, 0]) BTT2 = BT2.transpose([1, 0]) tape = wp.Tape() with tape: wp.matmul(A, BTT1, C1, D1, alpha, beta, False) wp.matmul(ATT1, B, C2, D2, alpha, beta, False) wp.matmul(ATT2, BTT2, C3, D3, alpha, beta, False) tape.backward(grads={D1: ones1, D2: ones2, D3: ones3}) D_np = alpha * (A.numpy() @ B.numpy()) + beta * C1.numpy() assert_np_equal(D1.numpy(), D_np) assert_np_equal(D2.numpy(), D_np) assert_np_equal(D3.numpy(), D_np) adj_A_np = alpha * (ones1.numpy() @ B.numpy().transpose()) adj_B_np = alpha * (A.numpy().transpose() @ ones1.numpy()) adj_C_np = beta * ones1.numpy() else: ATT1 = AT1.transpose([0, 2, 1]) BTT1 = BT1.transpose([0, 2, 1]) ATT2 = AT2.transpose([0, 2, 1]) BTT2 = BT2.transpose([0, 2, 1]) tape = wp.Tape() with tape: wp.batched_matmul(A, BTT1, C1, D1, alpha, beta, False) wp.batched_matmul(ATT1, B, C2, D2, alpha, beta, False) wp.batched_matmul(ATT2, BTT2, C3, D3, alpha, beta, False) tape.backward(grads={D1: ones1, D2: ones2, D3: ones3}) D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C1.numpy() assert_np_equal(D1.numpy(), D_np) assert_np_equal(D2.numpy(), D_np) assert_np_equal(D3.numpy(), D_np) adj_A_np = alpha * np.matmul(ones1.numpy(), B.numpy().transpose((0, 2, 1))) adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), ones1.numpy()) adj_C_np = beta * ones1.numpy() assert_np_equal(A.grad.numpy(), adj_A_np) assert_np_equal(ATT1.grad.numpy(), adj_A_np) assert_np_equal(ATT2.grad.numpy(), adj_A_np) assert_np_equal(B.grad.numpy(), adj_B_np) assert_np_equal(BTT1.grad.numpy(), adj_B_np) assert_np_equal(BTT2.grad.numpy(), adj_B_np) assert_np_equal(C1.grad.numpy(), adj_C_np) assert_np_equal(C2.grad.numpy(), adj_C_np) assert_np_equal(C3.grad.numpy(), adj_C_np) def run(self): m = 16 n = 32 k = 64 batch_counts = [1, 4] beta = 1.0 alpha = 1.0 for batch_count in batch_counts: self.run_and_verify(m, n, k, batch_count, alpha, beta) # NOTE: F16 tests are slow due to the performance of the reference numpy F16 matmuls performed on CPU. def test_f16(test, device): gemm_test_bed_runner(wp.float16, device).run() gemm_test_bed_runner_transpose(wp.float16, device).run() @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_f32(test, device): gemm_test_bed_runner(wp.float32, device).run() gemm_test_bed_runner_transpose(wp.float32, device).run() @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_f64(test, device): gemm_test_bed_runner(wp.float64, device).run() gemm_test_bed_runner_transpose(wp.float64, device).run() @wp.kernel def matrix_sum_kernel(arr: wp.array2d(dtype=float), loss: wp.array(dtype=float)): i, j = wp.tid() wp.atomic_add(loss, 0, arr[i, j]) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_tape(test, device): rng = np.random.default_rng(42) low = -4.5 high = 3.5 m = 64 n = 128 k = 256 A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=float, device=device, requires_grad=True ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=float, device=device, requires_grad=True ) C = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, n))), dtype=float, device=device, requires_grad=True ) D = wp.array2d(np.zeros((m, n)), dtype=float, device=device, requires_grad=True) loss = wp.zeros(1, dtype=float, device=device, requires_grad=True) # test tape tape = wp.Tape() with tape: wp.matmul(A, B, C, D) wp.launch(matrix_sum_kernel, dim=(m, n), inputs=[D, loss], device=device) tape.backward(loss=loss) A_grad = A.grad.numpy() tape.reset() # test adjoint D.grad = wp.ones((m, n), dtype=float, device=device) wp.adj_matmul(A, B, C, A.grad, B.grad, C.grad, D.grad) assert_np_equal(A_grad, A.grad.numpy()) # test zero tape.zero() assert_array_equal(A.grad, wp.zeros_like(A)) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_operator(test, device): rng = np.random.default_rng(42) low = -4.5 high = 3.5 m = 64 n = 128 k = 256 A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=float, device=device, requires_grad=True ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=float, device=device, requires_grad=True ) loss = wp.zeros(1, dtype=float, device=device, requires_grad=True) # test tape tape = wp.Tape() with tape: D = A @ B wp.launch(matrix_sum_kernel, dim=(m, n), inputs=[D, loss], device=device) tape.backward(loss=loss) # test adjoint D.grad = wp.ones((m, n), dtype=float, device=device) B_transpose = wp.array2d(B.transpose().numpy(), dtype=float, device=device) adj_A = D.grad @ B_transpose assert_array_equal(adj_A, A.grad) # test zero tape.zero() assert_array_equal(A.grad, wp.zeros_like(A)) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_large_batch_count(test, device): rng = np.random.default_rng(42) low = -4.5 high = 3.5 m = 2 n = 3 k = 4 batch_count = 65535 * 2 + int(65535 / 2) A = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, k))), dtype=float, device=device, requires_grad=True, ) B = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, k, n))), dtype=float, device=device, requires_grad=True, ) C = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, n))), dtype=float, device=device, requires_grad=True, ) D = wp.array3d(np.zeros((batch_count, m, n)), dtype=float, device=device, requires_grad=True) ones = wp.zeros_like(D) ones.fill_(1.0) alpha = 1.0 beta = 1.0 tape = wp.Tape() with tape: wp.batched_matmul(A, B, C, D, alpha=alpha, beta=beta, allow_tf32x3_arith=False) tape.backward(grads={D: ones}) D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C.numpy() assert_np_equal(D.numpy(), D_np) adj_A_np = alpha * np.matmul(ones.numpy(), B.numpy().transpose((0, 2, 1))) adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), ones.numpy()) adj_C_np = beta * ones.numpy() assert_np_equal(A.grad.numpy(), adj_A_np) assert_np_equal(B.grad.numpy(), adj_B_np) assert_np_equal(C.grad.numpy(), adj_C_np) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_adjoint_accumulation(test, device): a_np = np.ones(shape=(2, 3)) b_np = np.ones(shape=(3, 2)) c_np = np.zeros(shape=(2, 2)) d_np = np.zeros(shape=(2, 2)) a_wp = wp.from_numpy(a_np, dtype=float, requires_grad=True, device=device) b_wp = wp.from_numpy(b_np, dtype=float, requires_grad=True, device=device) c_wp = wp.from_numpy(c_np, dtype=float, requires_grad=True, device=device) d1_wp = wp.from_numpy(d_np, dtype=float, requires_grad=True, device=device) d2_wp = wp.from_numpy(d_np, dtype=float, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.matmul(a_wp, b_wp, c_wp, d1_wp, alpha=1.0, beta=1.0) wp.matmul(a_wp, b_wp, d1_wp, d2_wp, alpha=1.0, beta=1.0) d_grad = wp.zeros_like(d2_wp, device=device) d_grad.fill_(1.0) grads = {d2_wp: d_grad} tape.backward(grads=grads) assert_np_equal(a_wp.grad.numpy(), 4.0 * np.ones(shape=(2, 3))) assert_np_equal(b_wp.grad.numpy(), 4.0 * np.ones(shape=(3, 2))) assert_np_equal(c_wp.grad.numpy(), np.ones(shape=(2, 2))) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_cuda_graph_capture(test, device): @wp.kernel def mat_sum(mat: wp.array2d(dtype=Any), loss: wp.array(dtype=Any)): i, j = wp.tid() e = mat[i, j] wp.atomic_add(loss, 0, e) for T in [wp.float16, wp.float32, wp.float64]: wp.overload(mat_sum, [wp.array2d(dtype=T), wp.array(dtype=T)]) wp.load_module(device=device) wp.load_module(module="warp.utils", device=device) for dtype in [wp.float16, wp.float32, wp.float64]: m = 8 n = 8 k = 8 A = wp.ones((m, n), dtype=dtype, device=device, requires_grad=True) B = wp.ones((n, k), dtype=dtype, device=device, requires_grad=True) C = wp.zeros((m, k), dtype=dtype, device=device, requires_grad=True) D = wp.zeros((m, k), dtype=dtype, device=device, requires_grad=True) loss = wp.zeros(1, dtype=dtype, device=device, requires_grad=True) wp.capture_begin(device, force_module_load=False) try: tape = wp.Tape() with tape: wp.matmul(A, B, C, D) wp.launch(mat_sum, dim=(m, k), inputs=[D, loss], device=device) tape.backward(loss=loss) finally: graph = wp.capture_end(device) wp.capture_launch(graph) assert_np_equal(A.grad.numpy(), 8.0 * np.ones((m, n), dtype=wp.types.warp_type_to_np_dtype[dtype])) devices = get_test_devices() cuda_devices = get_selected_cuda_test_devices() class TestMatmul(unittest.TestCase): pass # add_function_test(TestMatmul, "test_f16", test_f16, devices=devices) add_function_test(TestMatmul, "test_f32", test_f32, devices=devices) add_function_test(TestMatmul, "test_f64", test_f64, devices=devices) add_function_test(TestMatmul, "test_tape", test_tape, devices=devices) add_function_test(TestMatmul, "test_operator", test_operator, devices=devices) add_function_test(TestMatmul, "test_large_batch_count", test_large_batch_count, devices=devices) add_function_test(TestMatmul, "test_adjoint_accumulation", test_adjoint_accumulation, devices=devices) add_function_test(TestMatmul, "test_cuda_graph_capture", test_cuda_graph_capture, devices=cuda_devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
18,159
Python
35.392786
117
0.565615
NVIDIA/warp/warp/tests/test_dense.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp from warp.tests.unittest_utils import * @wp.kernel def eval_dense_gemm( m: int, n: int, p: int, t1: int, t2: int, A: wp.array(dtype=float), B: wp.array(dtype=float), C: wp.array(dtype=float), ): wp.dense_gemm(m, n, p, t1, t2, A, B, C) @wp.kernel def eval_dense_cholesky(n: int, A: wp.array(dtype=float), regularization: float, L: wp.array(dtype=float)): wp.dense_chol(n, A, regularization, L) @wp.kernel def eval_dense_subs(n: int, L: wp.array(dtype=float), b: wp.array(dtype=float), x: wp.array(dtype=float)): wp.dense_subs(n, L, b, x) # helper that propagates gradients back to A, treating L as a constant / temporary variable # allows us to reuse the Cholesky decomposition from the forward pass @wp.kernel def eval_dense_solve( n: int, A: wp.array(dtype=float), L: wp.array(dtype=float), b: wp.array(dtype=float), x: wp.array(dtype=float) ): wp.dense_solve(n, A, L, b, x) def test_dense_compilation(test, device): # just testing compilation of the dense matrix routines # most are deprecated / WIP wp.load_module(device=device) devices = get_test_devices() class TestDense(unittest.TestCase): pass add_function_test(TestDense, "test_dense_compilation", test_dense_compilation, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
1,835
Python
26.818181
114
0.707357
NVIDIA/warp/warp/tests/test_ctypes.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def add_vec2(dest: wp.array(dtype=wp.vec2), c: wp.vec2): tid = wp.tid() dest[tid] = c @wp.kernel def transform_vec2(dest_right: wp.array(dtype=wp.vec2), dest_left: wp.array(dtype=wp.vec2), m: wp.mat22, v: wp.vec2): tid = wp.tid() dest_right[tid] = wp.mul(m, v) dest_left[tid] = wp.mul(v, m) @wp.kernel def add_vec3(dest: wp.array(dtype=wp.vec3), c: wp.vec3): tid = wp.tid() dest[tid] = c @wp.kernel def transform_vec3(dest_right: wp.array(dtype=wp.vec3), dest_left: wp.array(dtype=wp.vec3), m: wp.mat33, v: wp.vec3): tid = wp.tid() dest_right[tid] = wp.mul(m, v) dest_left[tid] = wp.mul(v, m) @wp.kernel def transform_multiply(xforms: wp.array(dtype=wp.transform), a: wp.transform): tid = wp.tid() xforms[tid] = wp.transform_multiply(xforms[tid], a) def test_vec2_arg(test, device, n): dest = wp.zeros(n=n, dtype=wp.vec2, device=device) c = np.array((1.0, 2.0)) wp.launch(add_vec2, dim=n, inputs=[dest, c], device=device) # ensure type can round-trip from Python->GPU->Python assert_np_equal(dest.numpy(), np.tile(c, (n, 1))) def test_vec2_transform(test, device, n): dest_right = wp.zeros(n=n, dtype=wp.vec2, device=device) dest_left = wp.zeros(n=n, dtype=wp.vec2, device=device) c = np.array((1.0, 2.0)) m = np.array(((3.0, -1.0), (2.5, 4.0))) wp.launch(transform_vec2, dim=n, inputs=[dest_right, dest_left, m, c], device=device) assert_np_equal(dest_right.numpy(), np.tile(m @ c, (n, 1))) assert_np_equal(dest_left.numpy(), np.tile(c @ m, (n, 1))) def test_vec3_arg(test, device, n): dest = wp.zeros(n=n, dtype=wp.vec3, device=device) c = np.array((1.0, 2.0, 3.0)) wp.launch(add_vec3, dim=n, inputs=[dest, c], device=device) assert_np_equal(dest.numpy(), np.tile(c, (n, 1))) def test_vec3_transform(test, device, n): dest_right = wp.zeros(n=n, dtype=wp.vec3, device=device) dest_left = wp.zeros(n=n, dtype=wp.vec3, device=device) c = np.array((1.0, 2.0, 3.0)) m = np.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0))) wp.launch(transform_vec3, dim=n, inputs=[dest_right, dest_left, m, c], device=device) assert_np_equal(dest_right.numpy(), np.tile(m @ c, (n, 1))) assert_np_equal(dest_left.numpy(), np.tile(c @ m, (n, 1))) def test_transform_multiply(test, device, n): a = wp.transform((0.0, 1.0, 0.0), wp.quat_identity()) x = [] for _i in range(10): x.append(wp.transform_identity()) xforms = wp.array(x, dtype=wp.transform, device=device) wp.launch(transform_multiply, dim=n, inputs=[xforms, a], device=device) transformf = wp.types.transformation(dtype=wp.float32) @wp.kernel def test_transformation_constructor(): a = wp.transformation(wp.vec3(0.0), wp.quat_identity()) b = transformf(wp.vec3(0.0), wp.quat_identity()) c = wp.transform_identity(dtype=wp.float64) spatial_vector = wp.types.vector(length=6, dtype=wp.float32) @wp.kernel def test_spatial_vector_constructor(): a = wp.spatial_vector(wp.vec3(0.0), wp.vec3(0.0)) # construct kernel + test harness for given matrix / vector types def make_matrix_test(dim, matrix, vector): def test_matrix_kernel( a: wp.array(dtype=matrix), b: wp.array(dtype=matrix), c: wp.array(dtype=matrix), x: wp.array(dtype=vector), result_m: wp.array(dtype=matrix), result_i: wp.array(dtype=matrix), result_d: wp.array(dtype=float), result_x: wp.array(dtype=vector), ): tid = wp.tid() m = a[tid] * b[tid] + c[tid] * 2.0 result_m[tid] = m result_x[tid] = m * x[tid] result_d[tid] = wp.determinant(m) invm = wp.inverse(m) result_i[tid] = m * invm # register a custom kernel (no decorator) function # this lets us register the same function definition # against multiple symbols, with different arg types kernel = wp.Kernel(func=test_matrix_kernel, key=f"test_mat{dim}{dim}_kernel") def test_matrix(test, device): rng = np.random.default_rng(42) n = 1024 a = rng.random(size=(n, dim, dim), dtype=float) b = rng.random(size=(n, dim, dim), dtype=float) c = rng.random(size=(n, dim, dim), dtype=float) x = rng.random(size=(n, dim, 1), dtype=float) a_array = wp.array(a, dtype=matrix, device=device) b_array = wp.array(b, dtype=matrix, device=device) c_array = wp.array(c, dtype=matrix, device=device) x_array = wp.array(x, dtype=vector, device=device) result_m_array = wp.zeros_like(a_array) result_i_array = wp.zeros_like(a_array) result_x_array = wp.zeros_like(x_array) result_d_array = wp.zeros(n, dtype=float, device=device) wp.launch( kernel, n, inputs=[a_array, b_array, c_array, x_array, result_m_array, result_i_array, result_d_array, result_x_array], device=device, ) # numpy reference result result_m = np.matmul(a, b) + c * 2.0 result_x = np.matmul(result_m, x) result_i = np.array([np.eye(dim)] * n) result_d = np.linalg.det(result_m) assert_np_equal(result_m_array.numpy(), result_m, tol=1.0e-5) assert_np_equal(result_i_array.numpy(), result_i, tol=1.0e-3) assert_np_equal(result_d_array.numpy(), result_d, tol=1.0e-3) assert_np_equal(result_x_array.numpy(), result_x, tol=1.0e-5) return test_matrix # generate test functions for matrix types test_mat22 = make_matrix_test(2, wp.mat22, wp.vec2) test_mat33 = make_matrix_test(3, wp.mat33, wp.vec3) test_mat44 = make_matrix_test(4, wp.mat44, wp.vec4) def test_scalar_array(test, device): scalar_list = (0.0, 1.0, 2.0) scalar_array = wp.array(scalar_list, device=device) assert_np_equal(np.array(scalar_list), scalar_array.numpy()) def test_vector_array(test, device): vector_list = [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (2.0, 2.0, 2.0)] vector_array = wp.array(vector_list, dtype=wp.vec3, device=device) assert_np_equal(np.array(vector_list), vector_array.numpy()) @wp.kernel def test_vector_arg_types(v2: wp.vec2, v3: wp.vec3, v4: wp.vec4, m22: wp.mat22, m33: wp.mat33, m44: wp.mat44): wp.expect_eq(v2, wp.vec2(1.0, 2.0)) wp.expect_eq(v3, wp.vec3(1.0, 2.0, 3.0)) wp.expect_eq(v4, wp.vec4(1.0, 2.0, 3.0, 4.0)) wp.expect_eq(m22, wp.mat22(1.0, 2.0, 3.0, 4.0)) wp.expect_eq(m33, wp.mat33(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)) wp.expect_eq(m44, wp.mat44(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0)) @wp.kernel def test_scalar_arg_types( i8: wp.int8, u8: wp.uint8, i16: wp.int16, u16: wp.uint16, i32: wp.int32, u32: wp.uint32, i64: wp.int64, u64: wp.uint64, f32: wp.float32, f64: wp.float64, ): wp.expect_eq(int(i8), -64) wp.expect_eq(int(u8), 255) wp.expect_eq(int(i16), -64) wp.expect_eq(int(u16), 255) wp.expect_eq(int(i32), -64) wp.expect_eq(int(u32), 255) wp.expect_eq(int(i64), -64) wp.expect_eq(int(u64), 255) wp.expect_eq(int(f32), 3) wp.expect_eq(int(f64), 3) wp.expect_eq(float(f32), 3.14159) wp.expect_eq(float(f64), 3.14159) @wp.kernel def test_scalar_array_types_load( i8: wp.array(dtype=wp.int8), u8: wp.array(dtype=wp.uint8), i16: wp.array(dtype=wp.int16), u16: wp.array(dtype=wp.uint16), i32: wp.array(dtype=wp.int32), u32: wp.array(dtype=wp.uint32), i64: wp.array(dtype=wp.int64), u64: wp.array(dtype=wp.uint64), f32: wp.array(dtype=wp.float32), f64: wp.array(dtype=wp.float64), ): tid = wp.tid() wp.expect_eq(int(i8[tid]), tid) wp.expect_eq(int(u8[tid]), tid) wp.expect_eq(int(i16[tid]), tid) wp.expect_eq(int(u16[tid]), tid) wp.expect_eq(int(i32[tid]), tid) wp.expect_eq(int(u32[tid]), tid) wp.expect_eq(int(i64[tid]), tid) wp.expect_eq(int(u64[tid]), tid) wp.expect_eq(float(f32[tid]), float(tid)) wp.expect_eq(float(f64[tid]), float(tid)) @wp.kernel def test_scalar_array_types_store( i8: wp.array(dtype=wp.int8), u8: wp.array(dtype=wp.uint8), i16: wp.array(dtype=wp.int16), u16: wp.array(dtype=wp.uint16), i32: wp.array(dtype=wp.int32), u32: wp.array(dtype=wp.uint32), i64: wp.array(dtype=wp.int64), u64: wp.array(dtype=wp.uint64), f32: wp.array(dtype=wp.float32), f64: wp.array(dtype=wp.float64), ): tid = wp.tid() i8[tid] = wp.int8(tid) u8[tid] = wp.uint8(tid) i16[tid] = wp.int16(tid) u16[tid] = wp.uint16(tid) i32[tid] = wp.int32(tid) u32[tid] = wp.uint32(tid) i64[tid] = wp.int64(tid) u64[tid] = wp.uint64(tid) f32[tid] = wp.float32(tid) f64[tid] = wp.float64(tid) # check round-trip wp.expect_eq(int(i8[tid]), tid) wp.expect_eq(int(u8[tid]), tid) wp.expect_eq(int(i16[tid]), tid) wp.expect_eq(int(u16[tid]), tid) wp.expect_eq(int(i32[tid]), tid) wp.expect_eq(int(u32[tid]), tid) wp.expect_eq(int(i64[tid]), tid) wp.expect_eq(int(u64[tid]), tid) wp.expect_eq(float(f32[tid]), float(tid)) wp.expect_eq(float(f64[tid]), float(tid)) @wp.kernel def test_type_conversions(): # below tests auto-generated by the following snippet: # scalar_types_all = [*wp.types.scalar_types, int, float] # for t in scalar_types_all: # for u in scalar_types_all: # def prefix(t): # if t == int or t == float: # return t.__name__ # else: # return "wp." + t.__name__ # print(f"wp.expect_eq({prefix(t)}(2.0), {prefix(t)}({prefix(u)}(2.0)))") wp.expect_eq(wp.int8(2.0), wp.int8(wp.int8(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint8(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.int16(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint16(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.int32(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint32(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.int64(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint64(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.float16(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.float32(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(wp.float64(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(int(2.0))) wp.expect_eq(wp.int8(2.0), wp.int8(float(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int8(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint8(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int16(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint16(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int32(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint32(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int64(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint64(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.float16(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.float32(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.float64(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(int(2.0))) wp.expect_eq(wp.uint8(2.0), wp.uint8(float(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.int8(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint8(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.int16(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint16(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.int32(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint32(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.int64(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint64(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.float16(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.float32(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(wp.float64(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(int(2.0))) wp.expect_eq(wp.int16(2.0), wp.int16(float(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int8(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint8(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int16(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint16(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int32(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint32(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int64(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint64(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.float16(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.float32(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.float64(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(int(2.0))) wp.expect_eq(wp.uint16(2.0), wp.uint16(float(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.int8(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint8(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.int16(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint16(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.int32(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint32(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.int64(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint64(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.float16(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.float32(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(wp.float64(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(int(2.0))) wp.expect_eq(wp.int32(2.0), wp.int32(float(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int8(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint8(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int16(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint16(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int32(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint32(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int64(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint64(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.float16(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.float32(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.float64(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(int(2.0))) wp.expect_eq(wp.uint32(2.0), wp.uint32(float(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.int8(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint8(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.int16(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint16(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.int32(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint32(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.int64(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint64(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.float16(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.float32(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(wp.float64(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(int(2.0))) wp.expect_eq(wp.int64(2.0), wp.int64(float(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int8(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint8(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int16(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint16(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int32(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint32(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int64(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint64(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.float16(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.float32(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.float64(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(int(2.0))) wp.expect_eq(wp.uint64(2.0), wp.uint64(float(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.int8(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint8(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.int16(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint16(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.int32(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint32(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.int64(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint64(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.float16(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.float32(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(wp.float64(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(int(2.0))) wp.expect_eq(wp.float16(2.0), wp.float16(float(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.int8(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint8(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.int16(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint16(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.int32(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint32(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.int64(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint64(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.float16(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.float32(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(wp.float64(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(int(2.0))) wp.expect_eq(wp.float32(2.0), wp.float32(float(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.int8(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint8(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.int16(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint16(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.int32(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint32(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.int64(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint64(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.float16(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.float32(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(wp.float64(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(int(2.0))) wp.expect_eq(wp.float64(2.0), wp.float64(float(2.0))) wp.expect_eq(int(2.0), int(wp.int8(2.0))) wp.expect_eq(int(2.0), int(wp.uint8(2.0))) wp.expect_eq(int(2.0), int(wp.int16(2.0))) wp.expect_eq(int(2.0), int(wp.uint16(2.0))) wp.expect_eq(int(2.0), int(wp.int32(2.0))) wp.expect_eq(int(2.0), int(wp.uint32(2.0))) wp.expect_eq(int(2.0), int(wp.int64(2.0))) wp.expect_eq(int(2.0), int(wp.uint64(2.0))) wp.expect_eq(int(2.0), int(wp.float16(2.0))) wp.expect_eq(int(2.0), int(wp.float32(2.0))) wp.expect_eq(int(2.0), int(wp.float64(2.0))) wp.expect_eq(int(2.0), int(int(2.0))) wp.expect_eq(int(2.0), int(float(2.0))) wp.expect_eq(float(2.0), float(wp.int8(2.0))) wp.expect_eq(float(2.0), float(wp.uint8(2.0))) wp.expect_eq(float(2.0), float(wp.int16(2.0))) wp.expect_eq(float(2.0), float(wp.uint16(2.0))) wp.expect_eq(float(2.0), float(wp.int32(2.0))) wp.expect_eq(float(2.0), float(wp.uint32(2.0))) wp.expect_eq(float(2.0), float(wp.int64(2.0))) wp.expect_eq(float(2.0), float(wp.uint64(2.0))) wp.expect_eq(float(2.0), float(wp.float16(2.0))) wp.expect_eq(float(2.0), float(wp.float32(2.0))) wp.expect_eq(float(2.0), float(wp.float64(2.0))) wp.expect_eq(float(2.0), float(int(2.0))) wp.expect_eq(float(2.0), float(float(2.0))) def test_scalar_array_types(test, device, load, store): dim = 64 i8 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int8), device=device) u8 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint8), device=device) i16 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int16), device=device) u16 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint16), device=device) i32 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int32), device=device) u32 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint32), device=device) i64 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int64), device=device) u64 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint64), device=device) f32 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.float32), device=device) f64 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.float64), device=device) if load: wp.launch( test_scalar_array_types_load, dim=dim, inputs=[i8, u8, i16, u16, i32, u32, i64, u64, f32, f64], device=device, ) if store: wp.launch( test_scalar_array_types_store, dim=dim, inputs=[i8, u8, i16, u16, i32, u32, i64, u64, f32, f64], device=device, ) @wp.kernel def test_transform_matrix(): r = wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), 0.5) t = wp.vec3(0.25, 0.5, -0.75) s = wp.vec3(2.0, 0.5, 0.75) m = wp.mat44(t, r, s) p = wp.vec3(1.0, 2.0, 3.0) r_0 = wp.quat_rotate(r, wp.cw_mul(s, p)) + t r_1 = wp.transform_point(m, p) r_2 = wp.transform_vector(m, p) wp.expect_near(r_0, r_1, 1.0e-4) wp.expect_near(r_2, r_0 - t, 1.0e-4) devices = get_test_devices() class TestCTypes(unittest.TestCase): pass inputs = [ wp.vec2(1.0, 2.0), wp.vec3(1.0, 2.0, 3.0), wp.vec4(1.0, 2.0, 3.0, 4.0), wp.mat22(1.0, 2.0, 3.0, 4.0), wp.mat33(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), wp.mat44(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0), ] add_function_test(TestCTypes, "test_mat22", test_mat22, devices=devices) add_function_test(TestCTypes, "test_mat33", test_mat33, devices=devices) add_function_test(TestCTypes, "test_mat44", test_mat44, devices=devices) add_kernel_test( TestCTypes, name="test_transformation_constructor", kernel=test_transformation_constructor, dim=1, devices=devices ) add_kernel_test( TestCTypes, name="test_spatial_vector_constructor", kernel=test_spatial_vector_constructor, dim=1, devices=devices ) add_kernel_test( TestCTypes, name="test_scalar_arg_types", kernel=test_scalar_arg_types, dim=1, inputs=[-64, 255, -64, 255, -64, 255, -64, 255, 3.14159, 3.14159], devices=devices, ) add_kernel_test( TestCTypes, name="test_scalar_arg_types_explicit", kernel=test_scalar_arg_types, dim=1, inputs=[ wp.int8(-64), wp.uint8(255), wp.int16(-64), wp.uint16(255), wp.int32(-64), wp.uint32(255), wp.int64(-64), wp.uint64(255), wp.float32(3.14159), wp.float64(3.14159), ], devices=devices, ) add_kernel_test( TestCTypes, name="test_vector_arg_types", kernel=test_vector_arg_types, dim=1, inputs=inputs, devices=devices ) add_kernel_test(TestCTypes, name="test_type_convesrions", kernel=test_type_conversions, dim=1, devices=devices) add_function_test( TestCTypes, "test_scalar_array_load", test_scalar_array_types, devices=devices, load=True, store=False ) add_function_test( TestCTypes, "test_scalar_array_store", test_scalar_array_types, devices=devices, load=False, store=True ) add_function_test(TestCTypes, "test_vec2_arg", test_vec2_arg, devices=devices, n=8) add_function_test(TestCTypes, "test_vec2_transform", test_vec2_transform, devices=devices, n=8) add_function_test(TestCTypes, "test_vec3_arg", test_vec3_arg, devices=devices, n=8) add_function_test(TestCTypes, "test_vec3_transform", test_vec3_transform, devices=devices, n=8) add_function_test(TestCTypes, "test_transform_multiply", test_transform_multiply, devices=devices, n=8) add_kernel_test(TestCTypes, name="test_transform_matrix", kernel=test_transform_matrix, dim=1, devices=devices) add_function_test(TestCTypes, "test_scalar_array", test_scalar_array, devices=devices) add_function_test(TestCTypes, "test_vector_array", test_vector_array, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
24,546
Python
37.901743
120
0.622342
NVIDIA/warp/warp/tests/test_dlpack.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import ctypes import os import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * N = 1024 * 1024 def _jax_version(): try: import jax return jax.__version_info__ except (ImportError, AttributeError): return (0, 0, 0) @wp.kernel def inc(a: wp.array(dtype=float)): tid = wp.tid() a[tid] = a[tid] + 1.0 def test_dlpack_warp_to_warp(test, device): a1 = wp.array(data=np.arange(N, dtype=np.float32), device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1)) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a1.dtype, a2.dtype) test.assertEqual(a1.shape, a2.shape) test.assertEqual(a1.strides, a2.strides) assert_np_equal(a1.numpy(), a2.numpy()) wp.launch(inc, dim=a2.size, inputs=[a2], device=device) assert_np_equal(a1.numpy(), a2.numpy()) def test_dlpack_dtypes_and_shapes(test, device): # automatically determine scalar dtype def wrap_scalar_tensor_implicit(dtype): a1 = wp.zeros(N, dtype=dtype, device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1)) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a1.dtype, a2.dtype) test.assertEqual(a1.shape, a2.shape) test.assertEqual(a1.strides, a2.strides) # explicitly specify scalar dtype def wrap_scalar_tensor_explicit(dtype, target_dtype): a1 = wp.zeros(N, dtype=dtype, device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=target_dtype) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a1.dtype, dtype) test.assertEqual(a2.dtype, target_dtype) test.assertEqual(a1.shape, a2.shape) test.assertEqual(a1.strides, a2.strides) # convert vector arrays to scalar arrays def wrap_vector_to_scalar_tensor(vec_dtype): scalar_type = vec_dtype._wp_scalar_type_ scalar_size = ctypes.sizeof(vec_dtype._type_) a1 = wp.zeros(N, dtype=vec_dtype, device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=scalar_type) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a2.ndim, a1.ndim + 1) test.assertEqual(a1.dtype, vec_dtype) test.assertEqual(a2.dtype, scalar_type) test.assertEqual(a2.shape, (*a1.shape, vec_dtype._length_)) test.assertEqual(a2.strides, (*a1.strides, scalar_size)) # convert scalar arrays to vector arrays def wrap_scalar_to_vector_tensor(vec_dtype): scalar_type = vec_dtype._wp_scalar_type_ scalar_size = ctypes.sizeof(vec_dtype._type_) a1 = wp.zeros((N, vec_dtype._length_), dtype=scalar_type, device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=vec_dtype) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a2.ndim, a1.ndim - 1) test.assertEqual(a1.dtype, scalar_type) test.assertEqual(a2.dtype, vec_dtype) test.assertEqual(a1.shape, (*a2.shape, vec_dtype._length_)) test.assertEqual(a1.strides, (*a2.strides, scalar_size)) # convert matrix arrays to scalar arrays def wrap_matrix_to_scalar_tensor(mat_dtype): scalar_type = mat_dtype._wp_scalar_type_ scalar_size = ctypes.sizeof(mat_dtype._type_) a1 = wp.zeros(N, dtype=mat_dtype, device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=scalar_type) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a2.ndim, a1.ndim + 2) test.assertEqual(a1.dtype, mat_dtype) test.assertEqual(a2.dtype, scalar_type) test.assertEqual(a2.shape, (*a1.shape, *mat_dtype._shape_)) test.assertEqual(a2.strides, (*a1.strides, scalar_size * mat_dtype._shape_[1], scalar_size)) # convert scalar arrays to matrix arrays def wrap_scalar_to_matrix_tensor(mat_dtype): scalar_type = mat_dtype._wp_scalar_type_ scalar_size = ctypes.sizeof(mat_dtype._type_) a1 = wp.zeros((N, *mat_dtype._shape_), dtype=scalar_type, device=device) a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=mat_dtype) test.assertEqual(a1.ptr, a2.ptr) test.assertEqual(a1.device, a2.device) test.assertEqual(a2.ndim, a1.ndim - 2) test.assertEqual(a1.dtype, scalar_type) test.assertEqual(a2.dtype, mat_dtype) test.assertEqual(a1.shape, (*a2.shape, *mat_dtype._shape_)) test.assertEqual(a1.strides, (*a2.strides, scalar_size * mat_dtype._shape_[1], scalar_size)) for t in wp.types.scalar_types: wrap_scalar_tensor_implicit(t) for t in wp.types.scalar_types: wrap_scalar_tensor_explicit(t, t) # test signed/unsigned conversions wrap_scalar_tensor_explicit(wp.int8, wp.uint8) wrap_scalar_tensor_explicit(wp.uint8, wp.int8) wrap_scalar_tensor_explicit(wp.int16, wp.uint16) wrap_scalar_tensor_explicit(wp.uint16, wp.int16) wrap_scalar_tensor_explicit(wp.int32, wp.uint32) wrap_scalar_tensor_explicit(wp.uint32, wp.int32) wrap_scalar_tensor_explicit(wp.int64, wp.uint64) wrap_scalar_tensor_explicit(wp.uint64, wp.int64) vec_types = [] for t in wp.types.scalar_types: for vec_len in [2, 3, 4, 5]: vec_types.append(wp.types.vector(vec_len, t)) vec_types.append(wp.quath) vec_types.append(wp.quatf) vec_types.append(wp.quatd) vec_types.append(wp.transformh) vec_types.append(wp.transformf) vec_types.append(wp.transformd) vec_types.append(wp.spatial_vectorh) vec_types.append(wp.spatial_vectorf) vec_types.append(wp.spatial_vectord) for vec_type in vec_types: wrap_vector_to_scalar_tensor(vec_type) wrap_scalar_to_vector_tensor(vec_type) mat_shapes = [(2, 2), (3, 3), (4, 4), (5, 5), (2, 3), (3, 2), (3, 4), (4, 3)] mat_types = [] for t in wp.types.scalar_types: for mat_shape in mat_shapes: mat_types.append(wp.types.matrix(mat_shape, t)) mat_types.append(wp.spatial_matrixh) mat_types.append(wp.spatial_matrixf) mat_types.append(wp.spatial_matrixd) for mat_type in mat_types: wrap_matrix_to_scalar_tensor(mat_type) wrap_scalar_to_matrix_tensor(mat_type) def test_dlpack_warp_to_torch(test, device): import torch.utils.dlpack a = wp.array(data=np.arange(N, dtype=np.float32), device=device) t = torch.utils.dlpack.from_dlpack(wp.to_dlpack(a)) item_size = wp.types.type_size_in_bytes(a.dtype) test.assertEqual(a.ptr, t.data_ptr()) test.assertEqual(a.device, wp.device_from_torch(t.device)) test.assertEqual(a.dtype, wp.dtype_from_torch(t.dtype)) test.assertEqual(a.shape, tuple(t.shape)) test.assertEqual(a.strides, tuple(s * item_size for s in t.stride())) assert_np_equal(a.numpy(), t.cpu().numpy()) wp.launch(inc, dim=a.size, inputs=[a], device=device) assert_np_equal(a.numpy(), t.cpu().numpy()) t += 1 assert_np_equal(a.numpy(), t.cpu().numpy()) def test_dlpack_warp_to_torch_v2(test, device): # same as original test, but uses newer __dlpack__() method import torch.utils.dlpack a = wp.array(data=np.arange(N, dtype=np.float32), device=device) # pass the array directly t = torch.utils.dlpack.from_dlpack(a) item_size = wp.types.type_size_in_bytes(a.dtype) test.assertEqual(a.ptr, t.data_ptr()) test.assertEqual(a.device, wp.device_from_torch(t.device)) test.assertEqual(a.dtype, wp.dtype_from_torch(t.dtype)) test.assertEqual(a.shape, tuple(t.shape)) test.assertEqual(a.strides, tuple(s * item_size for s in t.stride())) assert_np_equal(a.numpy(), t.cpu().numpy()) wp.launch(inc, dim=a.size, inputs=[a], device=device) assert_np_equal(a.numpy(), t.cpu().numpy()) t += 1 assert_np_equal(a.numpy(), t.cpu().numpy()) def test_dlpack_torch_to_warp(test, device): import torch import torch.utils.dlpack t = torch.arange(N, dtype=torch.float32, device=wp.device_to_torch(device)) a = wp.from_dlpack(torch.utils.dlpack.to_dlpack(t)) item_size = wp.types.type_size_in_bytes(a.dtype) test.assertEqual(a.ptr, t.data_ptr()) test.assertEqual(a.device, wp.device_from_torch(t.device)) test.assertEqual(a.dtype, wp.dtype_from_torch(t.dtype)) test.assertEqual(a.shape, tuple(t.shape)) test.assertEqual(a.strides, tuple(s * item_size for s in t.stride())) assert_np_equal(a.numpy(), t.cpu().numpy()) wp.launch(inc, dim=a.size, inputs=[a], device=device) assert_np_equal(a.numpy(), t.cpu().numpy()) t += 1 assert_np_equal(a.numpy(), t.cpu().numpy()) def test_dlpack_torch_to_warp_v2(test, device): # same as original test, but uses newer __dlpack__() method import torch t = torch.arange(N, dtype=torch.float32, device=wp.device_to_torch(device)) # pass tensor directly a = wp.from_dlpack(t) item_size = wp.types.type_size_in_bytes(a.dtype) test.assertEqual(a.ptr, t.data_ptr()) test.assertEqual(a.device, wp.device_from_torch(t.device)) test.assertEqual(a.dtype, wp.dtype_from_torch(t.dtype)) test.assertEqual(a.shape, tuple(t.shape)) test.assertEqual(a.strides, tuple(s * item_size for s in t.stride())) assert_np_equal(a.numpy(), t.cpu().numpy()) wp.launch(inc, dim=a.size, inputs=[a], device=device) assert_np_equal(a.numpy(), t.cpu().numpy()) t += 1 assert_np_equal(a.numpy(), t.cpu().numpy()) def test_dlpack_warp_to_jax(test, device): import jax import jax.dlpack a = wp.array(data=np.arange(N, dtype=np.float32), device=device) # use generic dlpack conversion j1 = jax.dlpack.from_dlpack(wp.to_dlpack(a)) # use jax wrapper j2 = wp.to_jax(a) test.assertEqual(a.ptr, j1.unsafe_buffer_pointer()) test.assertEqual(a.ptr, j2.unsafe_buffer_pointer()) test.assertEqual(a.device, wp.device_from_jax(list(j1.devices())[0])) test.assertEqual(a.device, wp.device_from_jax(list(j2.devices())[0])) test.assertEqual(a.shape, j1.shape) test.assertEqual(a.shape, j2.shape) assert_np_equal(a.numpy(), np.asarray(j1)) assert_np_equal(a.numpy(), np.asarray(j2)) wp.launch(inc, dim=a.size, inputs=[a], device=device) wp.synchronize_device(device) # HACK? Run a no-op operation so that Jax flags the arrays as dirty # and gets the latest values, which were modified by Warp. j1 += 0 j2 += 0 assert_np_equal(a.numpy(), np.asarray(j1)) assert_np_equal(a.numpy(), np.asarray(j2)) @unittest.skipUnless(_jax_version() >= (0, 4, 15), "Jax version too old") def test_dlpack_warp_to_jax_v2(test, device): # same as original test, but uses newer __dlpack__() method import jax import jax.dlpack a = wp.array(data=np.arange(N, dtype=np.float32), device=device) # pass warp array directly j1 = jax.dlpack.from_dlpack(a) # use jax wrapper j2 = wp.to_jax(a) test.assertEqual(a.ptr, j1.unsafe_buffer_pointer()) test.assertEqual(a.ptr, j2.unsafe_buffer_pointer()) test.assertEqual(a.device, wp.device_from_jax(list(j1.devices())[0])) test.assertEqual(a.device, wp.device_from_jax(list(j2.devices())[0])) test.assertEqual(a.shape, j1.shape) test.assertEqual(a.shape, j2.shape) assert_np_equal(a.numpy(), np.asarray(j1)) assert_np_equal(a.numpy(), np.asarray(j2)) wp.launch(inc, dim=a.size, inputs=[a], device=device) wp.synchronize_device(device) # HACK? Run a no-op operation so that Jax flags the arrays as dirty # and gets the latest values, which were modified by Warp. j1 += 0 j2 += 0 assert_np_equal(a.numpy(), np.asarray(j1)) assert_np_equal(a.numpy(), np.asarray(j2)) def test_dlpack_jax_to_warp(test, device): import jax import jax.dlpack with jax.default_device(wp.device_to_jax(device)): j = jax.numpy.arange(N, dtype=jax.numpy.float32) # use generic dlpack conversion a1 = wp.from_dlpack(jax.dlpack.to_dlpack(j)) # use jax wrapper a2 = wp.from_jax(j) test.assertEqual(a1.ptr, j.unsafe_buffer_pointer()) test.assertEqual(a2.ptr, j.unsafe_buffer_pointer()) test.assertEqual(a1.device, wp.device_from_jax(list(j.devices())[0])) test.assertEqual(a2.device, wp.device_from_jax(list(j.devices())[0])) test.assertEqual(a1.shape, j.shape) test.assertEqual(a2.shape, j.shape) assert_np_equal(a1.numpy(), np.asarray(j)) assert_np_equal(a2.numpy(), np.asarray(j)) wp.launch(inc, dim=a1.size, inputs=[a1], device=device) wp.synchronize_device(device) # HACK? Run a no-op operation so that Jax flags the array as dirty # and gets the latest values, which were modified by Warp. j += 0 assert_np_equal(a1.numpy(), np.asarray(j)) assert_np_equal(a2.numpy(), np.asarray(j)) @unittest.skipUnless(_jax_version() >= (0, 4, 15), "Jax version too old") def test_dlpack_jax_to_warp_v2(test, device): # same as original test, but uses newer __dlpack__() method import jax with jax.default_device(wp.device_to_jax(device)): j = jax.numpy.arange(N, dtype=jax.numpy.float32) # pass jax array directly a1 = wp.from_dlpack(j) # use jax wrapper a2 = wp.from_jax(j) test.assertEqual(a1.ptr, j.unsafe_buffer_pointer()) test.assertEqual(a2.ptr, j.unsafe_buffer_pointer()) test.assertEqual(a1.device, wp.device_from_jax(list(j.devices())[0])) test.assertEqual(a2.device, wp.device_from_jax(list(j.devices())[0])) test.assertEqual(a1.shape, j.shape) test.assertEqual(a2.shape, j.shape) assert_np_equal(a1.numpy(), np.asarray(j)) assert_np_equal(a2.numpy(), np.asarray(j)) wp.launch(inc, dim=a1.size, inputs=[a1], device=device) wp.synchronize_device(device) # HACK? Run a no-op operation so that Jax flags the array as dirty # and gets the latest values, which were modified by Warp. j += 0 assert_np_equal(a1.numpy(), np.asarray(j)) assert_np_equal(a2.numpy(), np.asarray(j)) class TestDLPack(unittest.TestCase): pass devices = get_test_devices() add_function_test(TestDLPack, "test_dlpack_warp_to_warp", test_dlpack_warp_to_warp, devices=devices) add_function_test(TestDLPack, "test_dlpack_dtypes_and_shapes", test_dlpack_dtypes_and_shapes, devices=devices) # torch interop via dlpack try: import torch import torch.utils.dlpack # check which Warp devices work with Torch # CUDA devices may fail if Torch was not compiled with CUDA support test_devices = get_test_devices() torch_compatible_devices = [] for d in test_devices: try: t = torch.arange(10, device=wp.device_to_torch(d)) t += 1 torch_compatible_devices.append(d) except Exception as e: print(f"Skipping Torch DLPack tests on device '{d}' due to exception: {e}") if torch_compatible_devices: add_function_test( TestDLPack, "test_dlpack_warp_to_torch", test_dlpack_warp_to_torch, devices=torch_compatible_devices ) add_function_test( TestDLPack, "test_dlpack_warp_to_torch_v2", test_dlpack_warp_to_torch_v2, devices=torch_compatible_devices ) add_function_test( TestDLPack, "test_dlpack_torch_to_warp", test_dlpack_torch_to_warp, devices=torch_compatible_devices ) add_function_test( TestDLPack, "test_dlpack_torch_to_warp_v2", test_dlpack_torch_to_warp_v2, devices=torch_compatible_devices ) except Exception as e: print(f"Skipping Torch DLPack tests due to exception: {e}") # jax interop via dlpack try: # prevent Jax from gobbling up GPU memory os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false" os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform" import jax import jax.dlpack # check which Warp devices work with Jax # CUDA devices may fail if Jax cannot find a CUDA Toolkit test_devices = get_test_devices() jax_compatible_devices = [] for d in test_devices: try: with jax.default_device(wp.device_to_jax(d)): j = jax.numpy.arange(10, dtype=jax.numpy.float32) j += 1 jax_compatible_devices.append(d) except Exception as e: print(f"Skipping Jax DLPack tests on device '{d}' due to exception: {e}") if jax_compatible_devices: add_function_test( TestDLPack, "test_dlpack_warp_to_jax", test_dlpack_warp_to_jax, devices=jax_compatible_devices ) add_function_test( TestDLPack, "test_dlpack_warp_to_jax_v2", test_dlpack_warp_to_jax_v2, devices=jax_compatible_devices ) add_function_test( TestDLPack, "test_dlpack_jax_to_warp", test_dlpack_jax_to_warp, devices=jax_compatible_devices ) add_function_test( TestDLPack, "test_dlpack_jax_to_warp_v2", test_dlpack_jax_to_warp_v2, devices=jax_compatible_devices ) except Exception as e: print(f"Skipping Jax DLPack tests due to exception: {e}") if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
17,903
Python
32.84499
118
0.651678
NVIDIA/warp/warp/tests/__main__.py
from warp.thirdparty.unittest_parallel import main if __name__ == "__main__": main()
90
Python
17.199997
50
0.644444
NVIDIA/warp/warp/tests/test_vec_lite.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp from warp.tests.unittest_utils import * @wp.kernel def test_vector_constructor_value_func(): a = wp.vec2() b = wp.vector(a, dtype=wp.float16) c = wp.vector(a) d = wp.vector(a, length=2) # Test matrix constructors using explicit type (float16) # note that these tests are specifically not using generics / closure # args to create kernels dynamically (like the rest of this file) # as those use different code paths to resolve arg types which # has lead to regressions. @wp.kernel def test_constructors_explicit_precision(): # construction for custom vector types ones = wp.vector(wp.float16(1.0), length=2) zeros = wp.vector(length=2, dtype=wp.float16) custom = wp.vector(wp.float16(0.0), wp.float16(1.0)) for i in range(2): wp.expect_eq(ones[i], wp.float16(1.0)) wp.expect_eq(zeros[i], wp.float16(0.0)) wp.expect_eq(custom[i], wp.float16(i)) # Same as above but with a default (float/int) type # which tests some different code paths that # need to ensure types are correctly canonicalized # during codegen @wp.kernel def test_constructors_default_precision(): # construction for custom vector types ones = wp.vector(1.0, length=2) zeros = wp.vector(length=2, dtype=float) custom = wp.vector(0.0, 1.0) for i in range(2): wp.expect_eq(ones[i], 1.0) wp.expect_eq(zeros[i], 0.0) wp.expect_eq(custom[i], float(i)) devices = get_test_devices() class TestVecLite(unittest.TestCase): pass add_kernel_test(TestVecLite, test_vector_constructor_value_func, dim=1, devices=devices) add_kernel_test(TestVecLite, test_constructors_explicit_precision, dim=1, devices=devices) add_kernel_test(TestVecLite, test_constructors_default_precision, dim=1, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=True)
2,343
Python
31.555555
90
0.718737
NVIDIA/warp/warp/tests/aux_test_square.py
import warp as wp @wp.func def multiply(x: float): return x * x @wp.kernel def kern(expect: float): wp.expect_eq(multiply(4.0), expect) def run(expect, device): wp.launch(kern, dim=1, inputs=[expect], device=device)
234
Python
13.687499
58
0.662393
NVIDIA/warp/warp/tests/aux_test_reference.py
# This file is used to test reloading module references. import warp as wp import warp.tests.aux_test_reference_reference as refref @wp.func def magic(): return 2.0 * refref.more_magic()
194
Python
18.499998
56
0.742268
NVIDIA/warp/warp/tests/test_verify_fp.py
# Copyright (c) 2024 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import warp as wp from warp.tests.unittest_utils import * def setUpModule(): wp.config.verify_fp = True # Enable checking floating-point values to be finite def tearDownModule(): wp.config.verify_fp = False @wp.struct class TestStruct: field: wp.float32 @wp.kernel def finite_kernel(foos: wp.array(dtype=TestStruct)): i = wp.tid() foos[i].field += wp.float32(1.0) def test_finite(test, device): foos = wp.zeros((10,), dtype=TestStruct, device=device) wp.launch( kernel=finite_kernel, dim=(10,), inputs=[foos], device=device, ) wp.synchronize() expected = TestStruct() expected.field = 1.0 for f in foos.list(): if f.field != expected.field: raise AssertionError(f"Unexpected result, got: {f} expected: {expected}") @wp.kernel def nan_kernel(foos: wp.array(dtype=TestStruct)): i = wp.tid() foos[i].field /= wp.float32(0.0) # Division by zero produces Not-a-Number (NaN) def test_nan(test, device): foos = wp.zeros((10,), dtype=TestStruct, device=device) capture = StdOutCapture() capture.begin() wp.launch( kernel=nan_kernel, dim=(10,), inputs=[foos], device=device, ) wp.synchronize() output = capture.end() # Check that the output contains warnings about "nan" being produced. # Older Windows C runtimes have a bug where stdout sometimes does not get properly flushed. if output != "" or sys.platform != "win32": test.assertRegex(output, r"nan") devices = get_test_devices() class TestVerifyFP(unittest.TestCase): pass add_function_test(TestVerifyFP, "test_finite", test_finite, devices=devices) add_function_test(TestVerifyFP, "test_nan", test_nan, devices=devices, check_output=False) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
2,343
Python
24.204301
95
0.679044
NVIDIA/warp/warp/tests/aux_test_grad_customs.py
# Copyright (c) 2024 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """This file is used to test importing a user-defined function with a custom gradient""" import warp as wp @wp.func def aux_custom_fn(x: float, y: float): return x * 3.0 + y / 3.0, y**2.5 @wp.func_grad(aux_custom_fn) def aux_custom_fn_grad(x: float, y: float, adj_ret0: float, adj_ret1: float): wp.adjoint[x] += x * adj_ret0 * 42.0 + y * adj_ret1 * 10.0 wp.adjoint[y] += y * adj_ret1 * 3.0
831
Python
36.81818
88
0.724428
NVIDIA/warp/warp/tests/run_coverage_serial.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """Serial code-coverage runner This script is used to generate code-coverage reports by running Warp tests. It runs in serial so can take over an hour to finish. To generate a coverage report in parallel, use the warp/thirdparty./unittest_parallel.py script instead with the --coverage option, e.g. python -m warp.tests --coverage """ import coverage cover = coverage.Coverage(config_file=True, messages=True) cover.start() with cover.collect(): import unittest_serial # noqa: E402 unittest_serial.run_specified() cover.save() cover.report() cover.html_report(title="Warp Testing Code Coverage Report")
1,045
Python
31.687499
76
0.781818
NVIDIA/warp/warp/tests/test_sim_kinematics.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import math import os import unittest import warp as wp import warp.sim from warp.tests.unittest_utils import * def test_fk_ik(test, device): builder = wp.sim.ModelBuilder() num_envs = 1 for i in range(num_envs): wp.sim.parse_mjcf( os.path.join(os.path.dirname(__file__), "../examples/assets/nv_ant.xml"), builder, stiffness=0.0, damping=1.0, armature=0.1, contact_ke=1.0e4, contact_kd=1.0e2, contact_kf=1.0e2, contact_mu=0.75, limit_ke=1.0e3, limit_kd=1.0e1, up_axis="y", ) coord_count = 15 dof_count = 14 coord_start = i * coord_count dof_start = i * dof_count # base builder.joint_q[coord_start : coord_start + 3] = [i * 2.0, 0.70, 0.0] builder.joint_q[coord_start + 3 : coord_start + 7] = wp.quat_from_axis_angle( wp.vec3(1.0, 0.0, 0.0), -math.pi * 0.5 ) # joints builder.joint_q[coord_start + 7 : coord_start + coord_count] = [0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0, 1.0] builder.joint_qd[dof_start + 6 : dof_start + dof_count] = [1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0] # finalize model model = builder.finalize(device=device) model.ground = True model.joint_attach_ke *= 16.0 model.joint_attach_kd *= 4.0 state = model.state() # save a copy of joint values q_fk = model.joint_q.numpy() qd_fk = model.joint_qd.numpy() wp.sim.eval_fk(model, model.joint_q, model.joint_qd, None, state) q_ik = wp.zeros_like(model.joint_q, device=device) qd_ik = wp.zeros_like(model.joint_qd, device=device) wp.sim.eval_ik(model, state, q_ik, qd_ik) assert_np_equal(q_fk, q_ik.numpy(), tol=1e-6) assert_np_equal(qd_fk, qd_ik.numpy(), tol=1e-6) devices = get_test_devices() class TestSimKinematics(unittest.TestCase): pass add_function_test(TestSimKinematics, "test_fk_ik", test_fk_ik, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=True)
2,578
Python
27.655555
113
0.610163
NVIDIA/warp/warp/tests/test_vec_scalar_ops.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * np_signed_int_types = [ np.int8, np.int16, np.int32, np.int64, np.byte, ] np_unsigned_int_types = [ np.uint8, np.uint16, np.uint32, np.uint64, np.ubyte, ] np_int_types = np_signed_int_types + np_unsigned_int_types np_float_types = [np.float16, np.float32, np.float64] np_scalar_types = np_int_types + np_float_types def randvals(rng, shape, dtype): if dtype in np_float_types: return rng.standard_normal(size=shape).astype(dtype) elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]: return rng.integers(1, high=3, size=shape, dtype=dtype) return rng.integers(1, high=5, size=shape, dtype=dtype) kernel_cache = {} def getkernel(func, suffix=""): key = func.__name__ + "_" + suffix if key not in kernel_cache: kernel_cache[key] = wp.Kernel(func=func, key=key) return kernel_cache[key] def get_select_kernel(dtype): def output_select_kernel_fn( input: wp.array(dtype=dtype), index: int, out: wp.array(dtype=dtype), ): out[0] = input[index] return getkernel(output_select_kernel_fn, suffix=dtype.__name__) def get_select_kernel2(dtype): def output_select_kernel2_fn( input: wp.array(dtype=dtype, ndim=2), index0: int, index1: int, out: wp.array(dtype=dtype), ): out[0] = input[index0, index1] return getkernel(output_select_kernel2_fn, suffix=dtype.__name__) def test_arrays(test, device, dtype): rng = np.random.default_rng(123) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) v2_np = randvals(rng, (10, 2), dtype) v3_np = randvals(rng, (10, 3), dtype) v4_np = randvals(rng, (10, 4), dtype) v5_np = randvals(rng, (10, 5), dtype) v2 = wp.array(v2_np, dtype=vec2, requires_grad=True, device=device) v3 = wp.array(v3_np, dtype=vec3, requires_grad=True, device=device) v4 = wp.array(v4_np, dtype=vec4, requires_grad=True, device=device) v5 = wp.array(v5_np, dtype=vec5, requires_grad=True, device=device) assert_np_equal(v2.numpy(), v2_np, tol=1.0e-6) assert_np_equal(v3.numpy(), v3_np, tol=1.0e-6) assert_np_equal(v4.numpy(), v4_np, tol=1.0e-6) assert_np_equal(v5.numpy(), v5_np, tol=1.0e-6) vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) v2 = wp.array(v2_np, dtype=vec2, requires_grad=True, device=device) v3 = wp.array(v3_np, dtype=vec3, requires_grad=True, device=device) v4 = wp.array(v4_np, dtype=vec4, requires_grad=True, device=device) assert_np_equal(v2.numpy(), v2_np, tol=1.0e-6) assert_np_equal(v3.numpy(), v3_np, tol=1.0e-6) assert_np_equal(v4.numpy(), v4_np, tol=1.0e-6) def test_components(test, device, dtype): # test accessing vector components from Python - this is especially important # for float16, which requires special handling internally wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec3 = wp.types.vector(length=3, dtype=wptype) v = vec3(1, 2, 3) # test __getitem__ for individual components test.assertEqual(v[0], 1) test.assertEqual(v[1], 2) test.assertEqual(v[2], 3) # test __getitem__ for slices s = v[:] test.assertEqual(s[0], 1) test.assertEqual(s[1], 2) test.assertEqual(s[2], 3) s = v[1:] test.assertEqual(s[0], 2) test.assertEqual(s[1], 3) s = v[:2] test.assertEqual(s[0], 1) test.assertEqual(s[1], 2) s = v[::2] test.assertEqual(s[0], 1) test.assertEqual(s[1], 3) # test __setitem__ for individual components v[0] = 4 v[1] = 5 v[2] = 6 test.assertEqual(v[0], 4) test.assertEqual(v[1], 5) test.assertEqual(v[2], 6) # test __setitem__ for slices v[:] = [7, 8, 9] test.assertEqual(v[0], 7) test.assertEqual(v[1], 8) test.assertEqual(v[2], 9) v[1:] = [10, 11] test.assertEqual(v[0], 7) test.assertEqual(v[1], 10) test.assertEqual(v[2], 11) v[:2] = [12, 13] test.assertEqual(v[0], 12) test.assertEqual(v[1], 13) test.assertEqual(v[2], 11) v[::2] = [14, 15] test.assertEqual(v[0], 14) test.assertEqual(v[1], 13) test.assertEqual(v[2], 15) def test_py_arithmetic_ops(test, device, dtype): wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def make_vec(*args): if wptype in wp.types.int_types: # Cast to the correct integer type to simulate wrapping. return tuple(wptype._type_(x).value for x in args) return args vec_cls = wp.vec(3, wptype) v = vec_cls(1, -2, 3) test.assertSequenceEqual(+v, make_vec(1, -2, 3)) test.assertSequenceEqual(-v, make_vec(-1, 2, -3)) test.assertSequenceEqual(v + vec_cls(5, 5, 5), make_vec(6, 3, 8)) test.assertSequenceEqual(v - vec_cls(5, 5, 5), make_vec(-4, -7, -2)) v = vec_cls(2, 4, 6) test.assertSequenceEqual(v * wptype(2), make_vec(4, 8, 12)) test.assertSequenceEqual(wptype(2) * v, make_vec(4, 8, 12)) test.assertSequenceEqual(v / wptype(2), make_vec(1, 2, 3)) test.assertSequenceEqual(wptype(24) / v, make_vec(12, 6, 4)) def test_constructors(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_scalar_constructor( input: wp.array(dtype=wptype), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = vec2(input[0]) v3result = vec3(input[0]) v4result = vec4(input[0]) v5result = vec5(input[0]) v2[0] = v2result v3[0] = v3result v4[0] = v4result v5[0] = v5result # multiply outputs by 2 so we've got something to backpropagate v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] def check_vector_constructors( input: wp.array(dtype=wptype), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = vec2(input[0], input[1]) v3result = vec3(input[2], input[3], input[4]) v4result = vec4(input[5], input[6], input[7], input[8]) v5result = vec5(input[9], input[10], input[11], input[12], input[13]) v2[0] = v2result v3[0] = v3result v4[0] = v4result v5[0] = v5result # multiply the output by 2 so we've got something to backpropagate: v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] vec_kernel = getkernel(check_vector_constructors, suffix=dtype.__name__) kernel = getkernel(check_scalar_constructor, suffix=dtype.__name__) if register_kernels: return input = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device) v2 = wp.zeros(1, dtype=vec2, device=device) v3 = wp.zeros(1, dtype=vec3, device=device) v4 = wp.zeros(1, dtype=vec4, device=device) v5 = wp.zeros(1, dtype=vec5, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[input], outputs=[v2, v3, v4, v5, v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) if dtype in np_float_types: for l in [v20, v21]: tape.backward(loss=l) test.assertEqual(tape.gradients[input].numpy()[0], 2.0) tape.zero() for l in [v30, v31, v32]: tape.backward(loss=l) test.assertEqual(tape.gradients[input].numpy()[0], 2.0) tape.zero() for l in [v40, v41, v42, v43]: tape.backward(loss=l) test.assertEqual(tape.gradients[input].numpy()[0], 2.0) tape.zero() for l in [v50, v51, v52, v53, v54]: tape.backward(loss=l) test.assertEqual(tape.gradients[input].numpy()[0], 2.0) tape.zero() val = input.numpy()[0] assert_np_equal(v2.numpy()[0], np.array([val, val]), tol=1.0e-6) assert_np_equal(v3.numpy()[0], np.array([val, val, val]), tol=1.0e-6) assert_np_equal(v4.numpy()[0], np.array([val, val, val, val]), tol=1.0e-6) assert_np_equal(v5.numpy()[0], np.array([val, val, val, val, val]), tol=1.0e-6) assert_np_equal(v20.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v21.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v30.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v31.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v32.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v40.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v41.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v42.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v43.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v50.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v51.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v52.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v53.numpy()[0], 2 * val, tol=1.0e-6) assert_np_equal(v54.numpy()[0], 2 * val, tol=1.0e-6) input = wp.array(randvals(rng, [14], dtype), requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( vec_kernel, dim=1, inputs=[input], outputs=[v2, v3, v4, v5, v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]): tape.backward(loss=l) grad = tape.gradients[input].numpy() expected_grad = np.zeros_like(grad) expected_grad[i] = 2 assert_np_equal(grad, expected_grad, tol=tol) tape.zero() assert_np_equal(v2.numpy()[0, 0], input.numpy()[0], tol=tol) assert_np_equal(v2.numpy()[0, 1], input.numpy()[1], tol=tol) assert_np_equal(v3.numpy()[0, 0], input.numpy()[2], tol=tol) assert_np_equal(v3.numpy()[0, 1], input.numpy()[3], tol=tol) assert_np_equal(v3.numpy()[0, 2], input.numpy()[4], tol=tol) assert_np_equal(v4.numpy()[0, 0], input.numpy()[5], tol=tol) assert_np_equal(v4.numpy()[0, 1], input.numpy()[6], tol=tol) assert_np_equal(v4.numpy()[0, 2], input.numpy()[7], tol=tol) assert_np_equal(v4.numpy()[0, 3], input.numpy()[8], tol=tol) assert_np_equal(v5.numpy()[0, 0], input.numpy()[9], tol=tol) assert_np_equal(v5.numpy()[0, 1], input.numpy()[10], tol=tol) assert_np_equal(v5.numpy()[0, 2], input.numpy()[11], tol=tol) assert_np_equal(v5.numpy()[0, 3], input.numpy()[12], tol=tol) assert_np_equal(v5.numpy()[0, 4], input.numpy()[13], tol=tol) assert_np_equal(v20.numpy()[0], 2 * input.numpy()[0], tol=tol) assert_np_equal(v21.numpy()[0], 2 * input.numpy()[1], tol=tol) assert_np_equal(v30.numpy()[0], 2 * input.numpy()[2], tol=tol) assert_np_equal(v31.numpy()[0], 2 * input.numpy()[3], tol=tol) assert_np_equal(v32.numpy()[0], 2 * input.numpy()[4], tol=tol) assert_np_equal(v40.numpy()[0], 2 * input.numpy()[5], tol=tol) assert_np_equal(v41.numpy()[0], 2 * input.numpy()[6], tol=tol) assert_np_equal(v42.numpy()[0], 2 * input.numpy()[7], tol=tol) assert_np_equal(v43.numpy()[0], 2 * input.numpy()[8], tol=tol) assert_np_equal(v50.numpy()[0], 2 * input.numpy()[9], tol=tol) assert_np_equal(v51.numpy()[0], 2 * input.numpy()[10], tol=tol) assert_np_equal(v52.numpy()[0], 2 * input.numpy()[11], tol=tol) assert_np_equal(v53.numpy()[0], 2 * input.numpy()[12], tol=tol) assert_np_equal(v54.numpy()[0], 2 * input.numpy()[13], tol=tol) def test_anon_type_instance(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] def check_scalar_init( input: wp.array(dtype=wptype), output: wp.array(dtype=wptype), ): v2result = wp.vector(input[0], length=2) v3result = wp.vector(input[1], length=3) v4result = wp.vector(input[2], length=4) v5result = wp.vector(input[3], length=5) idx = 0 for i in range(2): output[idx] = wptype(2) * v2result[i] idx = idx + 1 for i in range(3): output[idx] = wptype(2) * v3result[i] idx = idx + 1 for i in range(4): output[idx] = wptype(2) * v4result[i] idx = idx + 1 for i in range(5): output[idx] = wptype(2) * v5result[i] idx = idx + 1 def check_component_init( input: wp.array(dtype=wptype), output: wp.array(dtype=wptype), ): v2result = wp.vector(input[0], input[1]) v3result = wp.vector(input[2], input[3], input[4]) v4result = wp.vector(input[5], input[6], input[7], input[8]) v5result = wp.vector(input[9], input[10], input[11], input[12], input[13]) idx = 0 for i in range(2): output[idx] = wptype(2) * v2result[i] idx = idx + 1 for i in range(3): output[idx] = wptype(2) * v3result[i] idx = idx + 1 for i in range(4): output[idx] = wptype(2) * v4result[i] idx = idx + 1 for i in range(5): output[idx] = wptype(2) * v5result[i] idx = idx + 1 scalar_kernel = getkernel(check_scalar_init, suffix=dtype.__name__) component_kernel = getkernel(check_component_init, suffix=dtype.__name__) output_select_kernel = get_select_kernel(wptype) if register_kernels: return input = wp.array(randvals(rng, [4], dtype), requires_grad=True, device=device) output = wp.zeros(2 + 3 + 4 + 5, dtype=wptype, requires_grad=True, device=device) wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy()[:2], 2 * np.array([input.numpy()[0]] * 2), tol=1.0e-6) assert_np_equal(output.numpy()[2:5], 2 * np.array([input.numpy()[1]] * 3), tol=1.0e-6) assert_np_equal(output.numpy()[5:9], 2 * np.array([input.numpy()[2]] * 4), tol=1.0e-6) assert_np_equal(output.numpy()[9:], 2 * np.array([input.numpy()[3]] * 5), tol=1.0e-6) if dtype in np_float_types: out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(len(output)): tape = wp.Tape() with tape: wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(input.numpy()) if i < 2: expected[0] = 2 elif i < 5: expected[1] = 2 elif i < 9: expected[2] = 2 else: expected[3] = 2 assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol) tape.reset() tape.zero() input = wp.array(randvals(rng, [2 + 3 + 4 + 5], dtype), requires_grad=True, device=device) output = wp.zeros(2 + 3 + 4 + 5, dtype=wptype, requires_grad=True, device=device) wp.launch(component_kernel, dim=1, inputs=[input], outputs=[output], device=device) assert_np_equal(output.numpy(), 2 * input.numpy(), tol=1.0e-6) if dtype in np_float_types: out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) for i in range(len(output)): tape = wp.Tape() with tape: wp.launch(component_kernel, dim=1, inputs=[input], outputs=[output], device=device) wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(input.numpy()) expected[i] = 2 assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol) tape.reset() tape.zero() def test_indexing(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_indexing( v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): # multiply outputs by 2 so we've got something to backpropagate: v20[0] = wptype(2) * v2[0][0] v21[0] = wptype(2) * v2[0][1] v30[0] = wptype(2) * v3[0][0] v31[0] = wptype(2) * v3[0][1] v32[0] = wptype(2) * v3[0][2] v40[0] = wptype(2) * v4[0][0] v41[0] = wptype(2) * v4[0][1] v42[0] = wptype(2) * v4[0][2] v43[0] = wptype(2) * v4[0][3] v50[0] = wptype(2) * v5[0][0] v51[0] = wptype(2) * v5[0][1] v52[0] = wptype(2) * v5[0][2] v53[0] = wptype(2) * v5[0][3] v54[0] = wptype(2) * v5[0][4] kernel = getkernel(check_indexing, suffix=dtype.__name__) if register_kernels: return v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[v2, v3, v4, v5], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]): tape.backward(loss=l) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]]) expected_grads = np.zeros_like(allgrads) expected_grads[i] = 2 assert_np_equal(allgrads, expected_grads, tol=tol) tape.zero() assert_np_equal(v20.numpy()[0], 2.0 * v2.numpy()[0, 0], tol=tol) assert_np_equal(v21.numpy()[0], 2.0 * v2.numpy()[0, 1], tol=tol) assert_np_equal(v30.numpy()[0], 2.0 * v3.numpy()[0, 0], tol=tol) assert_np_equal(v31.numpy()[0], 2.0 * v3.numpy()[0, 1], tol=tol) assert_np_equal(v32.numpy()[0], 2.0 * v3.numpy()[0, 2], tol=tol) assert_np_equal(v40.numpy()[0], 2.0 * v4.numpy()[0, 0], tol=tol) assert_np_equal(v41.numpy()[0], 2.0 * v4.numpy()[0, 1], tol=tol) assert_np_equal(v42.numpy()[0], 2.0 * v4.numpy()[0, 2], tol=tol) assert_np_equal(v43.numpy()[0], 2.0 * v4.numpy()[0, 3], tol=tol) assert_np_equal(v50.numpy()[0], 2.0 * v5.numpy()[0, 0], tol=tol) assert_np_equal(v51.numpy()[0], 2.0 * v5.numpy()[0, 1], tol=tol) assert_np_equal(v52.numpy()[0], 2.0 * v5.numpy()[0, 2], tol=tol) assert_np_equal(v53.numpy()[0], 2.0 * v5.numpy()[0, 3], tol=tol) assert_np_equal(v54.numpy()[0], 2.0 * v5.numpy()[0, 4], tol=tol) def test_equality(test, device, dtype, register_kernels=False): wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_equality( v20: wp.array(dtype=vec2), v21: wp.array(dtype=vec2), v22: wp.array(dtype=vec2), v30: wp.array(dtype=vec3), v31: wp.array(dtype=vec3), v32: wp.array(dtype=vec3), v33: wp.array(dtype=vec3), v40: wp.array(dtype=vec4), v41: wp.array(dtype=vec4), v42: wp.array(dtype=vec4), v43: wp.array(dtype=vec4), v44: wp.array(dtype=vec4), v50: wp.array(dtype=vec5), v51: wp.array(dtype=vec5), v52: wp.array(dtype=vec5), v53: wp.array(dtype=vec5), v54: wp.array(dtype=vec5), v55: wp.array(dtype=vec5), ): wp.expect_eq(v20[0], v20[0]) wp.expect_neq(v21[0], v20[0]) wp.expect_neq(v22[0], v20[0]) wp.expect_eq(v30[0], v30[0]) wp.expect_neq(v31[0], v30[0]) wp.expect_neq(v32[0], v30[0]) wp.expect_neq(v33[0], v30[0]) wp.expect_eq(v40[0], v40[0]) wp.expect_neq(v41[0], v40[0]) wp.expect_neq(v42[0], v40[0]) wp.expect_neq(v43[0], v40[0]) wp.expect_neq(v44[0], v40[0]) wp.expect_eq(v50[0], v50[0]) wp.expect_neq(v51[0], v50[0]) wp.expect_neq(v52[0], v50[0]) wp.expect_neq(v53[0], v50[0]) wp.expect_neq(v54[0], v50[0]) wp.expect_neq(v55[0], v50[0]) kernel = getkernel(check_equality, suffix=dtype.__name__) if register_kernels: return v20 = wp.array([1.0, 2.0], dtype=vec2, requires_grad=True, device=device) v21 = wp.array([1.0, 3.0], dtype=vec2, requires_grad=True, device=device) v22 = wp.array([3.0, 2.0], dtype=vec2, requires_grad=True, device=device) v30 = wp.array([1.0, 2.0, 3.0], dtype=vec3, requires_grad=True, device=device) v31 = wp.array([-1.0, 2.0, 3.0], dtype=vec3, requires_grad=True, device=device) v32 = wp.array([1.0, -2.0, 3.0], dtype=vec3, requires_grad=True, device=device) v33 = wp.array([1.0, 2.0, -3.0], dtype=vec3, requires_grad=True, device=device) v40 = wp.array([1.0, 2.0, 3.0, 4.0], dtype=vec4, requires_grad=True, device=device) v41 = wp.array([-1.0, 2.0, 3.0, 4.0], dtype=vec4, requires_grad=True, device=device) v42 = wp.array([1.0, -2.0, 3.0, 4.0], dtype=vec4, requires_grad=True, device=device) v43 = wp.array([1.0, 2.0, -3.0, 4.0], dtype=vec4, requires_grad=True, device=device) v44 = wp.array([1.0, 2.0, 3.0, -4.0], dtype=vec4, requires_grad=True, device=device) v50 = wp.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device) v51 = wp.array([-1.0, 2.0, 3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device) v52 = wp.array([1.0, -2.0, 3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device) v53 = wp.array([1.0, 2.0, -3.0, 4.0, 5.0], dtype=vec5, requires_grad=True, device=device) v54 = wp.array([1.0, 2.0, 3.0, -4.0, 5.0], dtype=vec5, requires_grad=True, device=device) v55 = wp.array([1.0, 2.0, 3.0, 4.0, -5.0], dtype=vec5, requires_grad=True, device=device) wp.launch( kernel, dim=1, inputs=[ v20, v21, v22, v30, v31, v32, v33, v40, v41, v42, v43, v44, v50, v51, v52, v53, v54, v55, ], outputs=[], device=device, ) def test_scalar_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_mul( s: wp.array(dtype=wptype), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = s[0] * v2[0] v3result = s[0] * v3[0] v4result = s[0] * v4[0] v5result = s[0] * v5[0] # multiply outputs by 2 so we've got something to backpropagate: v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] kernel = getkernel(check_mul, suffix=dtype.__name__) if register_kernels: return s = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, v2, v3, v4, v5, ], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) assert_np_equal(v20.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 0], tol=tol) assert_np_equal(v21.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 1], tol=tol) assert_np_equal(v30.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 0], tol=10 * tol) assert_np_equal(v31.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 1], tol=10 * tol) assert_np_equal(v32.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 2], tol=10 * tol) assert_np_equal(v40.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 0], tol=10 * tol) assert_np_equal(v41.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 1], tol=10 * tol) assert_np_equal(v42.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 2], tol=10 * tol) assert_np_equal(v43.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 3], tol=10 * tol) assert_np_equal(v50.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 0], tol=10 * tol) assert_np_equal(v51.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 1], tol=10 * tol) assert_np_equal(v52.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 2], tol=10 * tol) assert_np_equal(v53.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 3], tol=10 * tol) assert_np_equal(v54.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 4], tol=10 * tol) incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]]) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43]): tape.backward(loss=l) sgrad = tape.gradients[s].numpy()[0] assert_np_equal(sgrad, 2 * incmps[i], tol=10 * tol) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4]]) expected_grads = np.zeros_like(allgrads) expected_grads[i] = s.numpy()[0] * 2 assert_np_equal(allgrads, expected_grads, tol=10 * tol) tape.zero() def test_scalar_multiplication_rightmul(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_rightmul( s: wp.array(dtype=wptype), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = v2[0] * s[0] v3result = v3[0] * s[0] v4result = v4[0] * s[0] v5result = v5[0] * s[0] # multiply outputs by 2 so we've got something to backpropagate: v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] kernel = getkernel(check_rightmul, suffix=dtype.__name__) if register_kernels: return s = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, v2, v3, v4, v5, ], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) assert_np_equal(v20.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 0], tol=tol) assert_np_equal(v21.numpy()[0], 2 * s.numpy()[0] * v2.numpy()[0, 1], tol=tol) assert_np_equal(v30.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 0], tol=10 * tol) assert_np_equal(v31.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 1], tol=10 * tol) assert_np_equal(v32.numpy()[0], 2 * s.numpy()[0] * v3.numpy()[0, 2], tol=10 * tol) assert_np_equal(v40.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 0], tol=10 * tol) assert_np_equal(v41.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 1], tol=10 * tol) assert_np_equal(v42.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 2], tol=10 * tol) assert_np_equal(v43.numpy()[0], 2 * s.numpy()[0] * v4.numpy()[0, 3], tol=10 * tol) assert_np_equal(v50.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 0], tol=10 * tol) assert_np_equal(v51.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 1], tol=10 * tol) assert_np_equal(v52.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 2], tol=10 * tol) assert_np_equal(v53.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 3], tol=10 * tol) assert_np_equal(v54.numpy()[0], 2 * s.numpy()[0] * v5.numpy()[0, 4], tol=10 * tol) incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]]) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43]): tape.backward(loss=l) sgrad = tape.gradients[s].numpy()[0] assert_np_equal(sgrad, 2 * incmps[i], tol=10 * tol) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4]]) expected_grads = np.zeros_like(allgrads) expected_grads[i] = s.numpy()[0] * 2 assert_np_equal(allgrads, expected_grads, tol=10 * tol) tape.zero() def test_cw_multiplication(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_cw_mul( s2: wp.array(dtype=vec2), s3: wp.array(dtype=vec3), s4: wp.array(dtype=vec4), s5: wp.array(dtype=vec5), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = wp.cw_mul(s2[0], v2[0]) v3result = wp.cw_mul(s3[0], v3[0]) v4result = wp.cw_mul(s4[0], v4[0]) v5result = wp.cw_mul(s5[0], v5[0]) v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] kernel = getkernel(check_cw_mul, suffix=dtype.__name__) if register_kernels: return s2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) s3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) s4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) s5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s2, s3, s4, s5, v2, v3, v4, v5, ], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) assert_np_equal(v20.numpy()[0], 2 * s2.numpy()[0, 0] * v2.numpy()[0, 0], tol=10 * tol) assert_np_equal(v21.numpy()[0], 2 * s2.numpy()[0, 1] * v2.numpy()[0, 1], tol=10 * tol) assert_np_equal(v30.numpy()[0], 2 * s3.numpy()[0, 0] * v3.numpy()[0, 0], tol=10 * tol) assert_np_equal(v31.numpy()[0], 2 * s3.numpy()[0, 1] * v3.numpy()[0, 1], tol=10 * tol) assert_np_equal(v32.numpy()[0], 2 * s3.numpy()[0, 2] * v3.numpy()[0, 2], tol=10 * tol) assert_np_equal(v40.numpy()[0], 2 * s4.numpy()[0, 0] * v4.numpy()[0, 0], tol=10 * tol) assert_np_equal(v41.numpy()[0], 2 * s4.numpy()[0, 1] * v4.numpy()[0, 1], tol=10 * tol) assert_np_equal(v42.numpy()[0], 2 * s4.numpy()[0, 2] * v4.numpy()[0, 2], tol=10 * tol) assert_np_equal(v43.numpy()[0], 2 * s4.numpy()[0, 3] * v4.numpy()[0, 3], tol=10 * tol) assert_np_equal(v50.numpy()[0], 2 * s5.numpy()[0, 0] * v5.numpy()[0, 0], tol=10 * tol) assert_np_equal(v51.numpy()[0], 2 * s5.numpy()[0, 1] * v5.numpy()[0, 1], tol=10 * tol) assert_np_equal(v52.numpy()[0], 2 * s5.numpy()[0, 2] * v5.numpy()[0, 2], tol=10 * tol) assert_np_equal(v53.numpy()[0], 2 * s5.numpy()[0, 3] * v5.numpy()[0, 3], tol=10 * tol) assert_np_equal(v54.numpy()[0], 2 * s5.numpy()[0, 4] * v5.numpy()[0, 4], tol=10 * tol) incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]]) scmps = np.concatenate([v.numpy()[0] for v in [s2, s3, s4, s5]]) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]): tape.backward(loss=l) sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]]) expected_grads = np.zeros_like(sgrads) expected_grads[i] = incmps[i] * 2 assert_np_equal(sgrads, expected_grads, tol=10 * tol) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]]) expected_grads = np.zeros_like(allgrads) expected_grads[i] = scmps[i] * 2 assert_np_equal(allgrads, expected_grads, tol=10 * tol) tape.zero() def test_scalar_division(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_div( s: wp.array(dtype=wptype), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = v2[0] / s[0] v3result = v3[0] / s[0] v4result = v4[0] / s[0] v5result = v5[0] / s[0] v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] kernel = getkernel(check_div, suffix=dtype.__name__) if register_kernels: return s = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s, v2, v3, v4, v5, ], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) if dtype in np_int_types: assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] // (s.numpy()[0])), tol=tol) assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] // (s.numpy()[0])), tol=tol) assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] // (s.numpy()[0])), tol=10 * tol) assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] // (s.numpy()[0])), tol=10 * tol) else: assert_np_equal(v20.numpy()[0], 2 * v2.numpy()[0, 0] / (s.numpy()[0]), tol=tol) assert_np_equal(v21.numpy()[0], 2 * v2.numpy()[0, 1] / (s.numpy()[0]), tol=tol) assert_np_equal(v30.numpy()[0], 2 * v3.numpy()[0, 0] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v31.numpy()[0], 2 * v3.numpy()[0, 1] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v32.numpy()[0], 2 * v3.numpy()[0, 2] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v40.numpy()[0], 2 * v4.numpy()[0, 0] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v41.numpy()[0], 2 * v4.numpy()[0, 1] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v42.numpy()[0], 2 * v4.numpy()[0, 2] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v43.numpy()[0], 2 * v4.numpy()[0, 3] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v50.numpy()[0], 2 * v5.numpy()[0, 0] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v51.numpy()[0], 2 * v5.numpy()[0, 1] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v52.numpy()[0], 2 * v5.numpy()[0, 2] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v53.numpy()[0], 2 * v5.numpy()[0, 3] / (s.numpy()[0]), tol=10 * tol) assert_np_equal(v54.numpy()[0], 2 * v5.numpy()[0, 4] / (s.numpy()[0]), tol=10 * tol) incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]]) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]): tape.backward(loss=l) sgrad = tape.gradients[s].numpy()[0] # d/ds v/s = -v/s^2 assert_np_equal(sgrad, -2 * incmps[i] / (s.numpy()[0] * s.numpy()[0]), tol=10 * tol) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]]) expected_grads = np.zeros_like(allgrads) expected_grads[i] = 2 / s.numpy()[0] # d/dv v/s = 1/s assert_np_equal(allgrads, expected_grads, tol=tol) tape.zero() def test_cw_division(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_cw_div( s2: wp.array(dtype=vec2), s3: wp.array(dtype=vec3), s4: wp.array(dtype=vec4), s5: wp.array(dtype=vec5), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = wp.cw_div(v2[0], s2[0]) v3result = wp.cw_div(v3[0], s3[0]) v4result = wp.cw_div(v4[0], s4[0]) v5result = wp.cw_div(v5[0], s5[0]) v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] kernel = getkernel(check_cw_div, suffix=dtype.__name__) if register_kernels: return s2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) s3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) s4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) s5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s2, s3, s4, s5, v2, v3, v4, v5, ], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) if dtype in np_int_types: assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] // s2.numpy()[0, 0]), tol=tol) assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] // s2.numpy()[0, 1]), tol=tol) assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] // s3.numpy()[0, 0]), tol=tol) assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] // s3.numpy()[0, 1]), tol=tol) assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] // s3.numpy()[0, 2]), tol=tol) assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] // s4.numpy()[0, 0]), tol=tol) assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] // s4.numpy()[0, 1]), tol=tol) assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] // s4.numpy()[0, 2]), tol=tol) assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] // s4.numpy()[0, 3]), tol=tol) assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] // s5.numpy()[0, 0]), tol=tol) assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] // s5.numpy()[0, 1]), tol=tol) assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] // s5.numpy()[0, 2]), tol=tol) assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] // s5.numpy()[0, 3]), tol=tol) assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] // s5.numpy()[0, 4]), tol=tol) else: assert_np_equal(v20.numpy()[0], 2 * v2.numpy()[0, 0] / s2.numpy()[0, 0], tol=tol) assert_np_equal(v21.numpy()[0], 2 * v2.numpy()[0, 1] / s2.numpy()[0, 1], tol=tol) assert_np_equal(v30.numpy()[0], 2 * v3.numpy()[0, 0] / s3.numpy()[0, 0], tol=tol) assert_np_equal(v31.numpy()[0], 2 * v3.numpy()[0, 1] / s3.numpy()[0, 1], tol=tol) assert_np_equal(v32.numpy()[0], 2 * v3.numpy()[0, 2] / s3.numpy()[0, 2], tol=tol) assert_np_equal(v40.numpy()[0], 2 * v4.numpy()[0, 0] / s4.numpy()[0, 0], tol=tol) assert_np_equal(v41.numpy()[0], 2 * v4.numpy()[0, 1] / s4.numpy()[0, 1], tol=tol) assert_np_equal(v42.numpy()[0], 2 * v4.numpy()[0, 2] / s4.numpy()[0, 2], tol=tol) assert_np_equal(v43.numpy()[0], 2 * v4.numpy()[0, 3] / s4.numpy()[0, 3], tol=tol) assert_np_equal(v50.numpy()[0], 2 * v5.numpy()[0, 0] / s5.numpy()[0, 0], tol=tol) assert_np_equal(v51.numpy()[0], 2 * v5.numpy()[0, 1] / s5.numpy()[0, 1], tol=tol) assert_np_equal(v52.numpy()[0], 2 * v5.numpy()[0, 2] / s5.numpy()[0, 2], tol=tol) assert_np_equal(v53.numpy()[0], 2 * v5.numpy()[0, 3] / s5.numpy()[0, 3], tol=tol) assert_np_equal(v54.numpy()[0], 2 * v5.numpy()[0, 4] / s5.numpy()[0, 4], tol=tol) if dtype in np_float_types: incmps = np.concatenate([v.numpy()[0] for v in [v2, v3, v4, v5]]) scmps = np.concatenate([v.numpy()[0] for v in [s2, s3, s4, s5]]) for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]): tape.backward(loss=l) sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]]) expected_grads = np.zeros_like(sgrads) # d/ds v/s = -v/s^2 expected_grads[i] = -incmps[i] * 2 / (scmps[i] * scmps[i]) assert_np_equal(sgrads, expected_grads, tol=20 * tol) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]]) expected_grads = np.zeros_like(allgrads) # d/dv v/s = 1/s expected_grads[i] = 2 / scmps[i] assert_np_equal(allgrads, expected_grads, tol=tol) tape.zero() def test_addition(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 5.0e-3, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_add( s2: wp.array(dtype=vec2), s3: wp.array(dtype=vec3), s4: wp.array(dtype=vec4), s5: wp.array(dtype=vec5), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), v20: wp.array(dtype=wptype), v21: wp.array(dtype=wptype), v30: wp.array(dtype=wptype), v31: wp.array(dtype=wptype), v32: wp.array(dtype=wptype), v40: wp.array(dtype=wptype), v41: wp.array(dtype=wptype), v42: wp.array(dtype=wptype), v43: wp.array(dtype=wptype), v50: wp.array(dtype=wptype), v51: wp.array(dtype=wptype), v52: wp.array(dtype=wptype), v53: wp.array(dtype=wptype), v54: wp.array(dtype=wptype), ): v2result = v2[0] + s2[0] v3result = v3[0] + s3[0] v4result = v4[0] + s4[0] v5result = v5[0] + s5[0] v20[0] = wptype(2) * v2result[0] v21[0] = wptype(2) * v2result[1] v30[0] = wptype(2) * v3result[0] v31[0] = wptype(2) * v3result[1] v32[0] = wptype(2) * v3result[2] v40[0] = wptype(2) * v4result[0] v41[0] = wptype(2) * v4result[1] v42[0] = wptype(2) * v4result[2] v43[0] = wptype(2) * v4result[3] v50[0] = wptype(2) * v5result[0] v51[0] = wptype(2) * v5result[1] v52[0] = wptype(2) * v5result[2] v53[0] = wptype(2) * v5result[3] v54[0] = wptype(2) * v5result[4] kernel = getkernel(check_add, suffix=dtype.__name__) if register_kernels: return s2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) s3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) s4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) s5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v20 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v21 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v30 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v31 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v32 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v40 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v41 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v42 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v43 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v50 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v51 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v52 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v53 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) v54 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s2, s3, s4, s5, v2, v3, v4, v5, ], outputs=[v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54], device=device, ) assert_np_equal(v20.numpy()[0], 2 * (v2.numpy()[0, 0] + s2.numpy()[0, 0]), tol=tol) assert_np_equal(v21.numpy()[0], 2 * (v2.numpy()[0, 1] + s2.numpy()[0, 1]), tol=tol) assert_np_equal(v30.numpy()[0], 2 * (v3.numpy()[0, 0] + s3.numpy()[0, 0]), tol=tol) assert_np_equal(v31.numpy()[0], 2 * (v3.numpy()[0, 1] + s3.numpy()[0, 1]), tol=tol) assert_np_equal(v32.numpy()[0], 2 * (v3.numpy()[0, 2] + s3.numpy()[0, 2]), tol=tol) assert_np_equal(v40.numpy()[0], 2 * (v4.numpy()[0, 0] + s4.numpy()[0, 0]), tol=tol) assert_np_equal(v41.numpy()[0], 2 * (v4.numpy()[0, 1] + s4.numpy()[0, 1]), tol=tol) assert_np_equal(v42.numpy()[0], 2 * (v4.numpy()[0, 2] + s4.numpy()[0, 2]), tol=tol) assert_np_equal(v43.numpy()[0], 2 * (v4.numpy()[0, 3] + s4.numpy()[0, 3]), tol=tol) assert_np_equal(v50.numpy()[0], 2 * (v5.numpy()[0, 0] + s5.numpy()[0, 0]), tol=tol) assert_np_equal(v51.numpy()[0], 2 * (v5.numpy()[0, 1] + s5.numpy()[0, 1]), tol=tol) assert_np_equal(v52.numpy()[0], 2 * (v5.numpy()[0, 2] + s5.numpy()[0, 2]), tol=tol) assert_np_equal(v53.numpy()[0], 2 * (v5.numpy()[0, 3] + s5.numpy()[0, 3]), tol=tol) assert_np_equal(v54.numpy()[0], 2 * (v5.numpy()[0, 4] + s5.numpy()[0, 4]), tol=2 * tol) if dtype in np_float_types: for i, l in enumerate([v20, v21, v30, v31, v32, v40, v41, v42, v43, v50, v51, v52, v53, v54]): tape.backward(loss=l) sgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [s2, s3, s4, s5]]) expected_grads = np.zeros_like(sgrads) expected_grads[i] = 2 assert_np_equal(sgrads, expected_grads, tol=10 * tol) allgrads = np.concatenate([tape.gradients[v].numpy()[0] for v in [v2, v3, v4, v5]]) assert_np_equal(allgrads, expected_grads, tol=tol) tape.zero() def test_dotproduct(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) tol = { np.float16: 1.0e-2, np.float32: 1.0e-6, np.float64: 1.0e-8, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) def check_dot( s2: wp.array(dtype=vec2), s3: wp.array(dtype=vec3), s4: wp.array(dtype=vec4), s5: wp.array(dtype=vec5), v2: wp.array(dtype=vec2), v3: wp.array(dtype=vec3), v4: wp.array(dtype=vec4), v5: wp.array(dtype=vec5), dot2: wp.array(dtype=wptype), dot3: wp.array(dtype=wptype), dot4: wp.array(dtype=wptype), dot5: wp.array(dtype=wptype), ): dot2[0] = wptype(2) * wp.dot(v2[0], s2[0]) dot3[0] = wptype(2) * wp.dot(v3[0], s3[0]) dot4[0] = wptype(2) * wp.dot(v4[0], s4[0]) dot5[0] = wptype(2) * wp.dot(v5[0], s5[0]) kernel = getkernel(check_dot, suffix=dtype.__name__) if register_kernels: return s2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) s3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) s4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) s5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) v2 = wp.array(randvals(rng, (1, 2), dtype), dtype=vec2, requires_grad=True, device=device) v3 = wp.array(randvals(rng, (1, 3), dtype), dtype=vec3, requires_grad=True, device=device) v4 = wp.array(randvals(rng, (1, 4), dtype), dtype=vec4, requires_grad=True, device=device) v5 = wp.array(randvals(rng, (1, 5), dtype), dtype=vec5, requires_grad=True, device=device) dot2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) dot3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) dot4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) dot5 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch( kernel, dim=1, inputs=[ s2, s3, s4, s5, v2, v3, v4, v5, ], outputs=[dot2, dot3, dot4, dot5], device=device, ) assert_np_equal(dot2.numpy()[0], 2.0 * (v2.numpy() * s2.numpy()).sum(), tol=10 * tol) assert_np_equal(dot3.numpy()[0], 2.0 * (v3.numpy() * s3.numpy()).sum(), tol=10 * tol) assert_np_equal(dot4.numpy()[0], 2.0 * (v4.numpy() * s4.numpy()).sum(), tol=10 * tol) assert_np_equal(dot5.numpy()[0], 2.0 * (v5.numpy() * s5.numpy()).sum(), tol=10 * tol) if dtype in np_float_types: tape.backward(loss=dot2) sgrads = tape.gradients[s2].numpy()[0] expected_grads = 2.0 * v2.numpy()[0] assert_np_equal(sgrads, expected_grads, tol=10 * tol) vgrads = tape.gradients[v2].numpy()[0] expected_grads = 2.0 * s2.numpy()[0] assert_np_equal(vgrads, expected_grads, tol=tol) tape.zero() tape.backward(loss=dot3) sgrads = tape.gradients[s3].numpy()[0] expected_grads = 2.0 * v3.numpy()[0] assert_np_equal(sgrads, expected_grads, tol=10 * tol) vgrads = tape.gradients[v3].numpy()[0] expected_grads = 2.0 * s3.numpy()[0] assert_np_equal(vgrads, expected_grads, tol=tol) tape.zero() tape.backward(loss=dot4) sgrads = tape.gradients[s4].numpy()[0] expected_grads = 2.0 * v4.numpy()[0] assert_np_equal(sgrads, expected_grads, tol=10 * tol) vgrads = tape.gradients[v4].numpy()[0] expected_grads = 2.0 * s4.numpy()[0] assert_np_equal(vgrads, expected_grads, tol=tol) tape.zero() tape.backward(loss=dot5) sgrads = tape.gradients[s5].numpy()[0] expected_grads = 2.0 * v5.numpy()[0] assert_np_equal(sgrads, expected_grads, tol=10 * tol) vgrads = tape.gradients[v5].numpy()[0] expected_grads = 2.0 * s5.numpy()[0] assert_np_equal(vgrads, expected_grads, tol=10 * tol) tape.zero() def test_equivalent_types(test, device, dtype, register_kernels=False): wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] # vector types vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) # vector types equivalent to the above vec2_equiv = wp.types.vector(length=2, dtype=wptype) vec3_equiv = wp.types.vector(length=3, dtype=wptype) vec4_equiv = wp.types.vector(length=4, dtype=wptype) vec5_equiv = wp.types.vector(length=5, dtype=wptype) # declare kernel with original types def check_equivalence( v2: vec2, v3: vec3, v4: vec4, v5: vec5, ): wp.expect_eq(v2, vec2(wptype(1), wptype(2))) wp.expect_eq(v3, vec3(wptype(1), wptype(2), wptype(3))) wp.expect_eq(v4, vec4(wptype(1), wptype(2), wptype(3), wptype(4))) wp.expect_eq(v5, vec5(wptype(1), wptype(2), wptype(3), wptype(4), wptype(5))) wp.expect_eq(v2, vec2_equiv(wptype(1), wptype(2))) wp.expect_eq(v3, vec3_equiv(wptype(1), wptype(2), wptype(3))) wp.expect_eq(v4, vec4_equiv(wptype(1), wptype(2), wptype(3), wptype(4))) wp.expect_eq(v5, vec5_equiv(wptype(1), wptype(2), wptype(3), wptype(4), wptype(5))) kernel = getkernel(check_equivalence, suffix=dtype.__name__) if register_kernels: return # call kernel with equivalent types v2 = vec2_equiv(1, 2) v3 = vec3_equiv(1, 2, 3) v4 = vec4_equiv(1, 2, 3, 4) v5 = vec5_equiv(1, 2, 3, 4, 5) wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5], device=device) def test_conversions(test, device, dtype, register_kernels=False): def check_vectors_equal( v0: wp.vec3, v1: wp.vec3, v2: wp.vec3, v3: wp.vec3, ): wp.expect_eq(v1, v0) wp.expect_eq(v2, v0) wp.expect_eq(v3, v0) kernel = getkernel(check_vectors_equal, suffix=dtype.__name__) if register_kernels: return v0 = wp.vec3(1, 2, 3) # test explicit conversions - constructing vectors from different containers v1 = wp.vec3((1, 2, 3)) v2 = wp.vec3([1, 2, 3]) v3 = wp.vec3(np.array([1, 2, 3], dtype=dtype)) wp.launch(kernel, dim=1, inputs=[v0, v1, v2, v3], device=device) # test implicit conversions - passing different containers as vectors to wp.launch() v1 = (1, 2, 3) v2 = [1, 2, 3] v3 = np.array([1, 2, 3], dtype=dtype) wp.launch(kernel, dim=1, inputs=[v0, v1, v2, v3], device=device) def test_constants(test, device, dtype, register_kernels=False): wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) cv2 = wp.constant(vec2(1, 2)) cv3 = wp.constant(vec3(1, 2, 3)) cv4 = wp.constant(vec4(1, 2, 3, 4)) cv5 = wp.constant(vec5(1, 2, 3, 4, 5)) def check_vector_constants(): wp.expect_eq(cv2, vec2(wptype(1), wptype(2))) wp.expect_eq(cv3, vec3(wptype(1), wptype(2), wptype(3))) wp.expect_eq(cv4, vec4(wptype(1), wptype(2), wptype(3), wptype(4))) wp.expect_eq(cv5, vec5(wptype(1), wptype(2), wptype(3), wptype(4), wptype(5))) kernel = getkernel(check_vector_constants, suffix=dtype.__name__) if register_kernels: return wp.launch(kernel, dim=1, inputs=[], device=device) def test_minmax(test, device, dtype, register_kernels=False): rng = np.random.default_rng(123) # \TODO: not quite sure why, but the numbers are off for 16 bit float # on the cpu (but not cuda). This is probably just the sketchy float16 # arithmetic I implemented to get all this stuff working, so # hopefully that can be fixed when we do that correctly. tol = { np.float16: 1.0e-2, }.get(dtype, 0) wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)] vec2 = wp.types.vector(length=2, dtype=wptype) vec3 = wp.types.vector(length=3, dtype=wptype) vec4 = wp.types.vector(length=4, dtype=wptype) vec5 = wp.types.vector(length=5, dtype=wptype) # \TODO: Also not quite sure why: this kernel compiles incredibly # slowly though... def check_vec_min_max( a: wp.array(dtype=wptype, ndim=2), b: wp.array(dtype=wptype, ndim=2), mins: wp.array(dtype=wptype, ndim=2), maxs: wp.array(dtype=wptype, ndim=2), ): for i in range(10): # multiplying by 2 so we've got something to backpropagate: a2read = vec2(a[i, 0], a[i, 1]) b2read = vec2(b[i, 0], b[i, 1]) c2 = wptype(2) * wp.min(a2read, b2read) d2 = wptype(2) * wp.max(a2read, b2read) a3read = vec3(a[i, 2], a[i, 3], a[i, 4]) b3read = vec3(b[i, 2], b[i, 3], b[i, 4]) c3 = wptype(2) * wp.min(a3read, b3read) d3 = wptype(2) * wp.max(a3read, b3read) a4read = vec4(a[i, 5], a[i, 6], a[i, 7], a[i, 8]) b4read = vec4(b[i, 5], b[i, 6], b[i, 7], b[i, 8]) c4 = wptype(2) * wp.min(a4read, b4read) d4 = wptype(2) * wp.max(a4read, b4read) a5read = vec5(a[i, 9], a[i, 10], a[i, 11], a[i, 12], a[i, 13]) b5read = vec5(b[i, 9], b[i, 10], b[i, 11], b[i, 12], b[i, 13]) c5 = wptype(2) * wp.min(a5read, b5read) d5 = wptype(2) * wp.max(a5read, b5read) mins[i, 0] = c2[0] mins[i, 1] = c2[1] mins[i, 2] = c3[0] mins[i, 3] = c3[1] mins[i, 4] = c3[2] mins[i, 5] = c4[0] mins[i, 6] = c4[1] mins[i, 7] = c4[2] mins[i, 8] = c4[3] mins[i, 9] = c5[0] mins[i, 10] = c5[1] mins[i, 11] = c5[2] mins[i, 12] = c5[3] mins[i, 13] = c5[4] maxs[i, 0] = d2[0] maxs[i, 1] = d2[1] maxs[i, 2] = d3[0] maxs[i, 3] = d3[1] maxs[i, 4] = d3[2] maxs[i, 5] = d4[0] maxs[i, 6] = d4[1] maxs[i, 7] = d4[2] maxs[i, 8] = d4[3] maxs[i, 9] = d5[0] maxs[i, 10] = d5[1] maxs[i, 11] = d5[2] maxs[i, 12] = d5[3] maxs[i, 13] = d5[4] kernel = getkernel(check_vec_min_max, suffix=dtype.__name__) output_select_kernel = get_select_kernel2(wptype) if register_kernels: return a = wp.array(randvals(rng, (10, 14), dtype), dtype=wptype, requires_grad=True, device=device) b = wp.array(randvals(rng, (10, 14), dtype), dtype=wptype, requires_grad=True, device=device) mins = wp.zeros((10, 14), dtype=wptype, requires_grad=True, device=device) maxs = wp.zeros((10, 14), dtype=wptype, requires_grad=True, device=device) tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[a, b], outputs=[mins, maxs], device=device) assert_np_equal(mins.numpy(), 2 * np.minimum(a.numpy(), b.numpy()), tol=tol) assert_np_equal(maxs.numpy(), 2 * np.maximum(a.numpy(), b.numpy()), tol=tol) out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device) if dtype in np_float_types: for i in range(10): for j in range(14): tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[a, b], outputs=[mins, maxs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[mins, i, j], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(a.numpy()) expected[i, j] = 2 if (a.numpy()[i, j] < b.numpy()[i, j]) else 0 assert_np_equal(tape.gradients[a].numpy(), expected, tol=tol) expected[i, j] = 2 if (b.numpy()[i, j] < a.numpy()[i, j]) else 0 assert_np_equal(tape.gradients[b].numpy(), expected, tol=tol) tape.zero() tape = wp.Tape() with tape: wp.launch(kernel, dim=1, inputs=[a, b], outputs=[mins, maxs], device=device) wp.launch(output_select_kernel, dim=1, inputs=[maxs, i, j], outputs=[out], device=device) tape.backward(loss=out) expected = np.zeros_like(a.numpy()) expected[i, j] = 2 if (a.numpy()[i, j] > b.numpy()[i, j]) else 0 assert_np_equal(tape.gradients[a].numpy(), expected, tol=tol) expected[i, j] = 2 if (b.numpy()[i, j] > a.numpy()[i, j]) else 0 assert_np_equal(tape.gradients[b].numpy(), expected, tol=tol) tape.zero() devices = get_test_devices() class TestVecScalarOps(unittest.TestCase): pass for dtype in np_scalar_types: add_function_test(TestVecScalarOps, f"test_arrays_{dtype.__name__}", test_arrays, devices=devices, dtype=dtype) add_function_test(TestVecScalarOps, f"test_components_{dtype.__name__}", test_components, devices=None, dtype=dtype) add_function_test( TestVecScalarOps, f"test_py_arithmetic_ops_{dtype.__name__}", test_py_arithmetic_ops, devices=None, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_constructors_{dtype.__name__}", test_constructors, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_anon_type_instance_{dtype.__name__}", test_anon_type_instance, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestVecScalarOps, f"test_indexing_{dtype.__name__}", test_indexing, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_equality_{dtype.__name__}", test_equality, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_scalar_multiplication_{dtype.__name__}", test_scalar_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestVecScalarOps, f"test_scalar_multiplication_rightmul_{dtype.__name__}", test_scalar_multiplication_rightmul, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestVecScalarOps, f"test_cw_multiplication_{dtype.__name__}", test_cw_multiplication, devices=devices, dtype=dtype, ) add_function_test_register_kernel( TestVecScalarOps, f"test_scalar_division_{dtype.__name__}", test_scalar_division, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_cw_division_{dtype.__name__}", test_cw_division, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_addition_{dtype.__name__}", test_addition, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_dotproduct_{dtype.__name__}", test_dotproduct, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_equivalent_types_{dtype.__name__}", test_equivalent_types, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_conversions_{dtype.__name__}", test_conversions, devices=devices, dtype=dtype ) add_function_test_register_kernel( TestVecScalarOps, f"test_constants_{dtype.__name__}", test_constants, devices=devices, dtype=dtype ) # the kernels in this test compile incredibly slowly... # add_function_test_register_kernel(TestVecScalarOps, f"test_minmax_{dtype.__name__}", test_minmax, devices=devices, dtype=dtype) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=True)
84,906
Python
39.470448
133
0.571703
NVIDIA/warp/warp/tests/test_matmul_lite.py
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * wp.init() # For wp.context.runtime.core.is_cutlass_enabled() class gemm_test_bed_runner: def __init__(self, dtype, device): self.dtype = dtype self.device = device def alloc(self, m, n, k, batch_count): rng = np.random.default_rng(42) low = -4.5 high = 3.5 if batch_count == 1: A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array2d(np.zeros((m, n)), dtype=self.dtype, device=self.device, requires_grad=True) else: A = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array3d(np.zeros((batch_count, m, n)), dtype=self.dtype, device=self.device, requires_grad=True) return A, B, C, D def run_and_verify(self, m, n, k, batch_count, alpha, beta): A, B, C, D = self.alloc(m, n, k, batch_count) ones = wp.zeros_like(D) ones.fill_(1.0) if batch_count == 1: tape = wp.Tape() with tape: wp.matmul(A, B, C, D, alpha, beta, False) tape.backward(grads={D: ones}) D_np = alpha * (A.numpy() @ B.numpy()) + beta * C.numpy() assert_np_equal(D.numpy(), D_np) adj_A_np = alpha * np.matmul(ones.numpy(), B.numpy().transpose()) adj_B_np = alpha * (A.numpy().transpose() @ ones.numpy()) adj_C_np = beta * ones.numpy() else: tape = wp.Tape() with tape: wp.batched_matmul(A, B, C, D, alpha, beta, False) tape.backward(grads={D: ones}) D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C.numpy() assert_np_equal(D.numpy(), D_np) adj_A_np = alpha * np.matmul(ones.numpy(), B.numpy().transpose((0, 2, 1))) adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), ones.numpy()) adj_C_np = beta * ones.numpy() assert_np_equal(A.grad.numpy(), adj_A_np) assert_np_equal(B.grad.numpy(), adj_B_np) assert_np_equal(C.grad.numpy(), adj_C_np) def run(self): Ms = [8] Ns = [16] Ks = [32] batch_counts = [1] betas = [1.0] alpha = 1.0 for batch_count in batch_counts: for m in Ms: for n in Ns: for k in Ks: for beta in betas: self.run_and_verify(m, n, k, batch_count, alpha, beta) class gemm_test_bed_runner_transpose: def __init__(self, dtype, device): self.dtype = dtype self.device = device def alloc(self, m, n, k, batch_count): rng = np.random.default_rng(42) low = -4.5 high = 3.5 if batch_count == 1: A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array2d(np.zeros((m, n)), dtype=self.dtype, device=self.device, requires_grad=True) AT = wp.array2d(A.numpy().transpose([1, 0]), dtype=self.dtype, device=self.device, requires_grad=True) BT = wp.array2d(B.numpy().transpose([1, 0]), dtype=self.dtype, device=self.device, requires_grad=True) else: A = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, k))), dtype=self.dtype, device=self.device, requires_grad=True, ) B = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, k, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) C = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, n))), dtype=self.dtype, device=self.device, requires_grad=True, ) D = wp.array3d(np.zeros((batch_count, m, n)), dtype=self.dtype, device=self.device, requires_grad=True) AT = wp.array3d(A.numpy().transpose([0, 2, 1]), dtype=self.dtype, device=self.device, requires_grad=True) BT = wp.array3d(B.numpy().transpose([0, 2, 1]), dtype=self.dtype, device=self.device, requires_grad=True) return A, B, C, D, AT, BT def run_and_verify(self, m, n, k, batch_count, alpha, beta): A, B, C1, D1, AT1, BT1 = self.alloc(m, n, k, batch_count) C2 = wp.clone(C1) C3 = wp.clone(C1) D2 = wp.clone(D1) D3 = wp.clone(D1) AT2 = wp.clone(AT1) BT2 = wp.clone(BT1) ones1 = wp.zeros_like(D1) ones1.fill_(1.0) ones2 = wp.zeros_like(D2) ones2.fill_(1.0) ones3 = wp.zeros_like(D3) ones3.fill_(1.0) if batch_count == 1: ATT1 = AT1.transpose([1, 0]) BTT1 = BT1.transpose([1, 0]) ATT2 = AT2.transpose([1, 0]) BTT2 = BT2.transpose([1, 0]) tape = wp.Tape() with tape: wp.matmul(A, BTT1, C1, D1, alpha, beta, False) wp.matmul(ATT1, B, C2, D2, alpha, beta, False) wp.matmul(ATT2, BTT2, C3, D3, alpha, beta, False) tape.backward(grads={D1: ones1, D2: ones2, D3: ones3}) D_np = alpha * (A.numpy() @ B.numpy()) + beta * C1.numpy() assert_np_equal(D1.numpy(), D_np) assert_np_equal(D2.numpy(), D_np) assert_np_equal(D3.numpy(), D_np) adj_A_np = alpha * (ones1.numpy() @ B.numpy().transpose()) adj_B_np = alpha * (A.numpy().transpose() @ ones1.numpy()) adj_C_np = beta * ones1.numpy() else: ATT1 = AT1.transpose([0, 2, 1]) BTT1 = BT1.transpose([0, 2, 1]) ATT2 = AT2.transpose([0, 2, 1]) BTT2 = BT2.transpose([0, 2, 1]) tape = wp.Tape() with tape: wp.batched_matmul(A, BTT1, C1, D1, alpha, beta, False) wp.batched_matmul(ATT1, B, C2, D2, alpha, beta, False) wp.batched_matmul(ATT2, BTT2, C3, D3, alpha, beta, False) tape.backward(grads={D1: ones1, D2: ones2, D3: ones3}) D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C1.numpy() assert_np_equal(D1.numpy(), D_np) assert_np_equal(D2.numpy(), D_np) assert_np_equal(D3.numpy(), D_np) adj_A_np = alpha * np.matmul(ones1.numpy(), B.numpy().transpose((0, 2, 1))) adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), ones1.numpy()) adj_C_np = beta * ones1.numpy() assert_np_equal(A.grad.numpy(), adj_A_np) assert_np_equal(ATT1.grad.numpy(), adj_A_np) assert_np_equal(ATT2.grad.numpy(), adj_A_np) assert_np_equal(B.grad.numpy(), adj_B_np) assert_np_equal(BTT1.grad.numpy(), adj_B_np) assert_np_equal(BTT2.grad.numpy(), adj_B_np) assert_np_equal(C1.grad.numpy(), adj_C_np) assert_np_equal(C2.grad.numpy(), adj_C_np) assert_np_equal(C3.grad.numpy(), adj_C_np) def run(self): m = 8 n = 16 k = 32 batch_counts = [1, 4] beta = 1.0 alpha = 1.0 for batch_count in batch_counts: self.run_and_verify(m, n, k, batch_count, alpha, beta) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_f32(test, device): gemm_test_bed_runner(wp.float32, device).run() gemm_test_bed_runner_transpose(wp.float32, device).run() @wp.kernel def matrix_sum_kernel(arr: wp.array2d(dtype=float), loss: wp.array(dtype=float)): i, j = wp.tid() wp.atomic_add(loss, 0, arr[i, j]) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_tape(test, device): rng = np.random.default_rng(42) low = -4.5 high = 3.5 m = 8 n = 16 k = 32 A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=float, device=device, requires_grad=True ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=float, device=device, requires_grad=True ) C = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, n))), dtype=float, device=device, requires_grad=True ) D = wp.array2d(np.zeros((m, n)), dtype=float, device=device, requires_grad=True) loss = wp.zeros(1, dtype=float, device=device, requires_grad=True) # test tape tape = wp.Tape() with tape: wp.matmul(A, B, C, D) wp.launch(matrix_sum_kernel, dim=(m, n), inputs=[D, loss], device=device) tape.backward(loss=loss) A_grad = A.grad.numpy() tape.reset() # test adjoint D.grad = wp.ones((m, n), dtype=float, device=device) wp.adj_matmul(A, B, C, A.grad, B.grad, C.grad, D.grad) assert_np_equal(A_grad, A.grad.numpy()) # test zero tape.zero() assert_array_equal(A.grad, wp.zeros_like(A)) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_operator(test, device): rng = np.random.default_rng(42) low = -4.5 high = 3.5 m = 8 n = 16 k = 32 A = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(m, k))), dtype=float, device=device, requires_grad=True ) B = wp.array2d( np.ceil(rng.uniform(low=low, high=high, size=(k, n))), dtype=float, device=device, requires_grad=True ) loss = wp.zeros(1, dtype=float, device=device, requires_grad=True) # test tape tape = wp.Tape() with tape: D = A @ B wp.launch(matrix_sum_kernel, dim=(m, n), inputs=[D, loss], device=device) tape.backward(loss=loss) # test adjoint D.grad = wp.ones((m, n), dtype=float, device=device) B_transpose = wp.array2d(B.transpose().numpy(), dtype=float, device=device) adj_A = D.grad @ B_transpose assert_array_equal(adj_A, A.grad) # test zero tape.zero() assert_array_equal(A.grad, wp.zeros_like(A)) @unittest.skipUnless(wp.context.runtime.core.is_cutlass_enabled(), "Warp was not built with CUTLASS support") def test_large_batch_count(test, device): rng = np.random.default_rng(42) low = -4.5 high = 3.5 m = 2 n = 3 k = 4 batch_count = 65535 * 2 + int(65535 / 2) A = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, k))), dtype=float, device=device, requires_grad=True, ) B = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, k, n))), dtype=float, device=device, requires_grad=True, ) C = wp.array3d( np.ceil(rng.uniform(low=low, high=high, size=(batch_count, m, n))), dtype=float, device=device, requires_grad=True, ) D = wp.array3d(np.zeros((batch_count, m, n)), dtype=float, device=device, requires_grad=True) ones = wp.zeros_like(D) ones.fill_(1.0) alpha = 1.0 beta = 1.0 tape = wp.Tape() with tape: wp.batched_matmul(A, B, C, D, alpha=alpha, beta=beta, allow_tf32x3_arith=False) tape.backward(grads={D: ones}) D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C.numpy() assert_np_equal(D.numpy(), D_np) adj_A_np = alpha * np.matmul(ones.numpy(), B.numpy().transpose((0, 2, 1))) adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), ones.numpy()) adj_C_np = beta * ones.numpy() assert_np_equal(A.grad.numpy(), adj_A_np) assert_np_equal(B.grad.numpy(), adj_B_np) assert_np_equal(C.grad.numpy(), adj_C_np) devices = get_test_devices() class TestMatmulLite(unittest.TestCase): pass add_function_test(TestMatmulLite, "test_f32", test_f32, devices=devices) add_function_test(TestMatmulLite, "test_tape", test_tape, devices=devices) add_function_test(TestMatmulLite, "test_operator", test_operator, devices=devices) add_function_test(TestMatmulLite, "test_large_batch_count", test_large_batch_count, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
14,532
Python
34.533007
117
0.546036
NVIDIA/warp/warp/tests/test_func.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import math import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.func def sqr(x: float): return x * x # test nested user function calls # and explicit return type hints @wp.func def cube(x: float) -> float: return sqr(x) * x @wp.func def custom(x: int): return x + 1 @wp.func def custom(x: float): return x + 1.0 @wp.func def custom(x: wp.vec3): return x + wp.vec3(1.0, 0.0, 0.0) @wp.func def noreturn(x: wp.vec3): x = x + wp.vec3(0.0, 1.0, 0.0) wp.expect_eq(x, wp.vec3(1.0, 1.0, 0.0)) @wp.kernel def test_overload_func(): # tests overloading a custom @wp.func i = custom(1) f = custom(1.0) v = custom(wp.vec3(1.0, 0.0, 0.0)) wp.expect_eq(i, 2) wp.expect_eq(f, 2.0) wp.expect_eq(v, wp.vec3(2.0, 0.0, 0.0)) noreturn(wp.vec3(1.0, 0.0, 0.0)) @wp.func def foo(x: int): # This shouldn't be picked up. return x * 2 @wp.func def foo(x: int): return x * 3 @wp.kernel def test_override_func(): i = foo(1) wp.expect_eq(i, 3) def test_func_closure_capture(test, device): def make_closure_kernel(func): def closure_kernel_fn(data: wp.array(dtype=float), expected: float): f = func(data[wp.tid()]) wp.expect_eq(f, expected) return wp.Kernel(func=closure_kernel_fn) sqr_closure = make_closure_kernel(sqr) cube_closure = make_closure_kernel(cube) data = wp.array([2.0], dtype=float, device=device) expected_sqr = 4.0 expected_cube = 8.0 wp.launch(sqr_closure, dim=data.shape, inputs=[data, expected_sqr], device=device) wp.launch(cube_closure, dim=data.shape, inputs=[data, expected_cube], device=device) @wp.func def test_func(param1: wp.int32, param2: wp.int32, param3: wp.int32) -> wp.float32: return 1.0 @wp.kernel def test_return_kernel(test_data: wp.array(dtype=wp.float32)): tid = wp.tid() test_data[tid] = wp.lerp(test_func(0, 1, 2), test_func(0, 1, 2), 0.5) def test_return_func(test, device): test_data = wp.zeros(100, dtype=wp.float32, device=device) wp.launch(kernel=test_return_kernel, dim=test_data.size, inputs=[test_data], device=device) @wp.func def multi_valued_func(a: wp.float32, b: wp.float32): return a + b, a - b, a * b, a / b def test_multi_valued_func(test, device): @wp.kernel def test_multi_valued_kernel(test_data1: wp.array(dtype=wp.float32), test_data2: wp.array(dtype=wp.float32)): tid = wp.tid() d1, d2 = test_data1[tid], test_data2[tid] a, b, c, d = multi_valued_func(d1, d2) wp.expect_eq(a, d1 + d2) wp.expect_eq(b, d1 - d2) wp.expect_eq(c, d1 * d2) wp.expect_eq(d, d1 / d2) test_data1 = wp.array(np.arange(100), dtype=wp.float32, device=device) test_data2 = wp.array(np.arange(100, 0, -1), dtype=wp.float32, device=device) wp.launch(kernel=test_multi_valued_kernel, dim=test_data1.size, inputs=[test_data1, test_data2], device=device) @wp.kernel def test_func_defaults(): # test default as expected wp.expect_near(1.0, 1.0 + 1.0e-6) # test that changing tolerance still works wp.expect_near(1.0, 1.1, 0.5) @wp.func def sign(x: float): return 123.0 @wp.kernel def test_builtin_shadowing(): wp.expect_eq(sign(1.23), 123.0) devices = get_test_devices() class TestFunc(unittest.TestCase): def test_user_func_export(self): # tests calling overloaded user-defined functions from Python i = custom(1) f = custom(1.0) v = custom(wp.vec3(1.0, 0.0, 0.0)) self.assertEqual(i, 2) self.assertEqual(f, 2.0) assert_np_equal(np.array([*v]), np.array([2.0, 0.0, 0.0])) def test_native_func_export(self): # tests calling native functions from Python q = wp.quat(0.0, 0.0, 0.0, 1.0) assert_np_equal(np.array([*q]), np.array([0.0, 0.0, 0.0, 1.0])) r = wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), 2.0) assert_np_equal(np.array([*r]), np.array([0.8414709568023682, 0.0, 0.0, 0.5403022170066833]), tol=1.0e-3) q = wp.quat(1.0, 2.0, 3.0, 4.0) q = wp.normalize(q) * 2.0 assert_np_equal( np.array([*q]), np.array([0.18257418274879456, 0.3651483654975891, 0.547722578048706, 0.7302967309951782]) * 2.0, tol=1.0e-3, ) v2 = wp.vec2(1.0, 2.0) v2 = wp.normalize(v2) * 2.0 assert_np_equal(np.array([*v2]), np.array([0.4472135901451111, 0.8944271802902222]) * 2.0, tol=1.0e-3) v3 = wp.vec3(1.0, 2.0, 3.0) v3 = wp.normalize(v3) * 2.0 assert_np_equal( np.array([*v3]), np.array([0.26726123690605164, 0.5345224738121033, 0.8017836809158325]) * 2.0, tol=1.0e-3 ) v4 = wp.vec4(1.0, 2.0, 3.0, 4.0) v4 = wp.normalize(v4) * 2.0 assert_np_equal( np.array([*v4]), np.array([0.18257418274879456, 0.3651483654975891, 0.547722578048706, 0.7302967309951782]) * 2.0, tol=1.0e-3, ) v = wp.vec2(0.0) v += wp.vec2(1.0, 1.0) assert v == wp.vec2(1.0, 1.0) v -= wp.vec2(1.0, 1.0) assert v == wp.vec2(0.0, 0.0) v = wp.vec2(2.0, 2.0) - wp.vec2(1.0, 1.0) assert v == wp.vec2(1.0, 1.0) v *= 2.0 assert v == wp.vec2(2.0, 2.0) v = v * 2.0 assert v == wp.vec2(4.0, 4.0) v = v / 2.0 assert v == wp.vec2(2.0, 2.0) v /= 2.0 assert v == wp.vec2(1.0, 1.0) v = -v assert v == wp.vec2(-1.0, -1.0) v = +v assert v == wp.vec2(-1.0, -1.0) m22 = wp.mat22(1.0, 2.0, 3.0, 4.0) m22 = m22 + m22 self.assertEqual(m22[1, 1], 8.0) self.assertEqual(str(m22), "[[2.0, 4.0],\n [6.0, 8.0]]") t = wp.transform( wp.vec3(1.0, 2.0, 3.0), wp.quat(4.0, 5.0, 6.0, 7.0), ) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual( t * wp.transform(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0), (396.0, 432.0, 720.0, 56.0, 70.0, 84.0, -28.0) ) self.assertSequenceEqual( t * wp.transform((1.0, 2.0, 3.0), (4.0, 5.0, 6.0, 7.0)), (396.0, 432.0, 720.0, 56.0, 70.0, 84.0, -28.0) ) t = wp.transform() self.assertSequenceEqual(t, (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) t = wp.transform(p=(1.0, 2.0, 3.0), q=(4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform(q=(4.0, 5.0, 6.0, 7.0), p=(1.0, 2.0, 3.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform((1.0, 2.0, 3.0), q=(4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform(p=(1.0, 2.0, 3.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1.0)) t = wp.transform(q=(4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (0.0, 0.0, 0.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform((1.0, 2.0, 3.0), (4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform(p=wp.vec3(1.0, 2.0, 3.0), q=wp.quat(4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform(wp.transform(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) t = wp.transform(*wp.transform(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual(t, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)) transformf = wp.types.transformation(dtype=float) t = wp.transformf((1.0, 2.0, 3.0), (4.0, 5.0, 6.0, 7.0)) self.assertSequenceEqual( t + transformf((2.0, 3.0, 4.0), (5.0, 6.0, 7.0, 8.0)), (3.0, 5.0, 7.0, 9.0, 11.0, 13.0, 15.0), ) self.assertSequenceEqual( t - transformf((2.0, 3.0, 4.0), (5.0, 6.0, 7.0, 8.0)), (-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0), ) f = wp.sin(math.pi * 0.5) self.assertAlmostEqual(f, 1.0, places=3) m = wp.mat22(0.0, 0.0, 0.0, 0.0) m += wp.mat22(1.0, 1.0, 1.0, 1.0) assert m == wp.mat22(1.0, 1.0, 1.0, 1.0) m -= wp.mat22(1.0, 1.0, 1.0, 1.0) assert m == wp.mat22(0.0, 0.0, 0.0, 0.0) m = wp.mat22(2.0, 2.0, 2.0, 2.0) - wp.mat22(1.0, 1.0, 1.0, 1.0) assert m == wp.mat22(1.0, 1.0, 1.0, 1.0) m *= 2.0 assert m == wp.mat22(2.0, 2.0, 2.0, 2.0) m = m * 2.0 assert m == wp.mat22(4.0, 4.0, 4.0, 4.0) m = m / 2.0 assert m == wp.mat22(2.0, 2.0, 2.0, 2.0) m /= 2.0 assert m == wp.mat22(1.0, 1.0, 1.0, 1.0) m = -m assert m == wp.mat22(-1.0, -1.0, -1.0, -1.0) m = +m assert m == wp.mat22(-1.0, -1.0, -1.0, -1.0) m = m * m assert m == wp.mat22(2.0, 2.0, 2.0, 2.0) def test_native_function_error_resolution(self): a = wp.mat22f(1.0, 2.0, 3.0, 4.0) b = wp.mat22d(1.0, 2.0, 3.0, 4.0) with self.assertRaisesRegex( RuntimeError, r"^Couldn't find a function 'mul' compatible with " r"the arguments 'mat22f, mat22d'$", ): a * b add_kernel_test(TestFunc, kernel=test_overload_func, name="test_overload_func", dim=1, devices=devices) add_function_test(TestFunc, func=test_return_func, name="test_return_func", devices=devices) add_kernel_test(TestFunc, kernel=test_override_func, name="test_override_func", dim=1, devices=devices) add_function_test(TestFunc, func=test_func_closure_capture, name="test_func_closure_capture", devices=devices) add_function_test(TestFunc, func=test_multi_valued_func, name="test_multi_valued_func", devices=devices) add_kernel_test(TestFunc, kernel=test_func_defaults, name="test_func_defaults", dim=1, devices=devices) add_kernel_test(TestFunc, kernel=test_builtin_shadowing, name="test_builtin_shadowing", dim=1, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
10,744
Python
30.884273
118
0.557148
NVIDIA/warp/warp/tests/test_tape.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def mul_constant(x: wp.array(dtype=float), y: wp.array(dtype=float)): tid = wp.tid() y[tid] = x[tid] * 2.0 @wp.struct class Multiplicands: x: wp.array(dtype=float) y: wp.array(dtype=float) @wp.kernel def mul_variable(mutiplicands: Multiplicands, z: wp.array(dtype=float)): tid = wp.tid() z[tid] = mutiplicands.x[tid] * mutiplicands.y[tid] @wp.kernel def dot_product(x: wp.array(dtype=float), y: wp.array(dtype=float), z: wp.array(dtype=float)): tid = wp.tid() wp.atomic_add(z, 0, x[tid] * y[tid]) def test_tape_mul_constant(test, device): dim = 8 iters = 16 tape = wp.Tape() # record onto tape with tape: # input data x0 = wp.array(np.zeros(dim), dtype=wp.float32, device=device, requires_grad=True) x = x0 for _i in range(iters): y = wp.empty_like(x, requires_grad=True) wp.launch(kernel=mul_constant, dim=dim, inputs=[x], outputs=[y], device=device) x = y # loss = wp.sum(x) x.grad = wp.array(np.ones(dim), device=device, dtype=wp.float32) # run backward tape.backward() # grad = 2.0^iters assert_np_equal(tape.gradients[x0].numpy(), np.ones(dim) * (2**iters)) def test_tape_mul_variable(test, device): dim = 8 tape = wp.Tape() # record onto tape with tape: # input data (Note: We're intentionally testing structs in tapes here) multiplicands = Multiplicands() multiplicands.x = wp.array(np.ones(dim) * 16.0, dtype=wp.float32, device=device, requires_grad=True) multiplicands.y = wp.array(np.ones(dim) * 32.0, dtype=wp.float32, device=device, requires_grad=True) z = wp.zeros_like(multiplicands.x) wp.launch(kernel=mul_variable, dim=dim, inputs=[multiplicands], outputs=[z], device=device) # loss = wp.sum(x) z.grad = wp.array(np.ones(dim), device=device, dtype=wp.float32) # run backward tape.backward() # grad_x=y, grad_y=x assert_np_equal(tape.gradients[multiplicands].x.numpy(), multiplicands.y.numpy()) assert_np_equal(tape.gradients[multiplicands].y.numpy(), multiplicands.x.numpy()) # run backward again with different incoming gradient # should accumulate the same gradients again onto output # so gradients = 2.0*prev tape.backward() assert_np_equal(tape.gradients[multiplicands].x.numpy(), multiplicands.y.numpy() * 2.0) assert_np_equal(tape.gradients[multiplicands].y.numpy(), multiplicands.x.numpy() * 2.0) # Clear launches and zero out the gradients tape.reset() assert_np_equal(tape.gradients[multiplicands].x.numpy(), np.zeros_like(tape.gradients[multiplicands].x.numpy())) test.assertFalse(tape.launches) def test_tape_dot_product(test, device): dim = 8 tape = wp.Tape() # record onto tape with tape: # input data x = wp.array(np.ones(dim) * 16.0, dtype=wp.float32, device=device, requires_grad=True) y = wp.array(np.ones(dim) * 32.0, dtype=wp.float32, device=device, requires_grad=True) z = wp.zeros(n=1, dtype=wp.float32, device=device, requires_grad=True) wp.launch(kernel=dot_product, dim=dim, inputs=[x, y], outputs=[z], device=device) # scalar loss tape.backward(loss=z) # grad_x=y, grad_y=x assert_np_equal(tape.gradients[x].numpy(), y.numpy()) assert_np_equal(tape.gradients[y].numpy(), x.numpy()) def test_tape_visualize(test, device): dim = 8 tape = wp.Tape() # record onto tape with tape: # input data x = wp.array(np.ones(dim) * 16.0, dtype=wp.float32, device=device, requires_grad=True) y = wp.array(np.ones(dim) * 32.0, dtype=wp.float32, device=device, requires_grad=True) z = wp.zeros(n=1, dtype=wp.float32, device=device, requires_grad=True) tape.record_scope_begin("my loop") for _ in range(16): wp.launch(kernel=dot_product, dim=dim, inputs=[x, y], outputs=[z], device=device) tape.record_scope_end() # generate GraphViz diagram code dot_code = tape.visualize(simplify_graph=True) assert "repeated 16x" in dot_code assert "my loop" in dot_code assert dot_code.count("dot_product") == 1 devices = get_test_devices() class TestTape(unittest.TestCase): def test_tape_no_nested_tapes(self): with self.assertRaises(RuntimeError): with wp.Tape(): with wp.Tape(): pass add_function_test(TestTape, "test_tape_mul_constant", test_tape_mul_constant, devices=devices) add_function_test(TestTape, "test_tape_mul_variable", test_tape_mul_variable, devices=devices) add_function_test(TestTape, "test_tape_dot_product", test_tape_dot_product, devices=devices) add_function_test(TestTape, "test_tape_visualize", test_tape_visualize, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
5,456
Python
30.726744
116
0.660557
NVIDIA/warp/warp/tests/aux_test_dependent.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """This file is used to test reloading module references.""" import warp as wp import warp.tests.aux_test_reference as ref @wp.kernel def kern(expect: float): wp.expect_eq(ref.magic(), expect) def run(expect, device): wp.launch(kern, dim=1, inputs=[expect], device=device)
710
Python
32.857141
76
0.773239
NVIDIA/warp/warp/tests/test_mesh_query_ray.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * # triangulate a list of polygon face indices def triangulate(face_counts, face_indices): num_tris = np.sum(np.subtract(face_counts, 2)) num_tri_vtx = num_tris * 3 tri_indices = np.zeros(num_tri_vtx, dtype=int) ctr = 0 wedgeIdx = 0 for nb in face_counts: for i in range(nb - 2): tri_indices[ctr] = face_indices[wedgeIdx] tri_indices[ctr + 1] = face_indices[wedgeIdx + i + 1] tri_indices[ctr + 2] = face_indices[wedgeIdx + i + 2] ctr += 3 wedgeIdx += nb return tri_indices @wp.kernel def mesh_query_ray_loss( mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_dirs: wp.array(dtype=wp.vec3), intersection_points: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float), ): tid = wp.tid() p = query_points[tid] D = query_dirs[tid] max_t = 10012.0 t = float(0.0) bary_u = float(0.0) bary_v = float(0.0) sign = float(0.0) normal = wp.vec3() face_index = int(0) q = wp.vec3() if wp.mesh_query_ray(mesh, p, D, max_t, t, bary_u, bary_v, sign, normal, face_index): q = wp.mesh_eval_position(mesh, face_index, bary_u, bary_v) intersection_points[tid] = q l = q[0] loss[tid] = l query = wp.mesh_query_ray(mesh, p, D, max_t) wp.expect_eq(query.t, t) wp.expect_eq(query.u, bary_u) wp.expect_eq(query.v, bary_v) wp.expect_eq(query.sign, sign) wp.expect_eq(query.normal, normal) wp.expect_eq(query.face, face_index) @unittest.skipUnless(USD_AVAILABLE, "Requires usd-core") def test_mesh_query_ray_grad(test, device): from pxr import Usd, UsdGeom # test tri # print("Testing Single Triangle") # mesh_points = wp.array(np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]), dtype=wp.vec3, device=device) # mesh_indices = wp.array(np.array([0,1,2]), dtype=int, device=device) mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/torus.usda"))) mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/World/Torus")) mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get() mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get() tri_indices = triangulate(mesh_counts, mesh_indices) mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device) mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device) p = wp.vec3(50.0, 50.0, 0.0) D = wp.vec3(0.0, -1.0, 0.0) # create mesh mesh = wp.Mesh(points=mesh_points, velocities=None, indices=mesh_indices) tape = wp.Tape() # analytic gradients with tape: query_points = wp.array(p, dtype=wp.vec3, device=device, requires_grad=True) query_dirs = wp.array(D, dtype=wp.vec3, device=device, requires_grad=True) intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True) wp.launch( kernel=mesh_query_ray_loss, dim=1, inputs=[mesh.id, query_points, query_dirs, intersection_points, loss], device=device, ) tape.backward(loss=loss) q = intersection_points.numpy().flatten() analytic_p = tape.gradients[query_points].numpy().flatten() analytic_D = tape.gradients[query_dirs].numpy().flatten() # numeric gradients # ray origin eps = 1.0e-3 loss_values_p = [] numeric_p = np.zeros(3) offset_query_points = [ wp.vec3(p[0] - eps, p[1], p[2]), wp.vec3(p[0] + eps, p[1], p[2]), wp.vec3(p[0], p[1] - eps, p[2]), wp.vec3(p[0], p[1] + eps, p[2]), wp.vec3(p[0], p[1], p[2] - eps), wp.vec3(p[0], p[1], p[2] + eps), ] for i in range(6): q = offset_query_points[i] query_points = wp.array(q, dtype=wp.vec3, device=device) query_dirs = wp.array(D, dtype=wp.vec3, device=device) intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device) wp.launch( kernel=mesh_query_ray_loss, dim=1, inputs=[mesh.id, query_points, query_dirs, intersection_points, loss], device=device, ) loss_values_p.append(loss.numpy()[0]) for i in range(3): l_0 = loss_values_p[i * 2] l_1 = loss_values_p[i * 2 + 1] gradient = (l_1 - l_0) / (2.0 * eps) numeric_p[i] = gradient # ray dir loss_values_D = [] numeric_D = np.zeros(3) offset_query_dirs = [ wp.vec3(D[0] - eps, D[1], D[2]), wp.vec3(D[0] + eps, D[1], D[2]), wp.vec3(D[0], D[1] - eps, D[2]), wp.vec3(D[0], D[1] + eps, D[2]), wp.vec3(D[0], D[1], D[2] - eps), wp.vec3(D[0], D[1], D[2] + eps), ] for i in range(6): q = offset_query_dirs[i] query_points = wp.array(p, dtype=wp.vec3, device=device) query_dirs = wp.array(q, dtype=wp.vec3, device=device) intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device) wp.launch( kernel=mesh_query_ray_loss, dim=1, inputs=[mesh.id, query_points, query_dirs, intersection_points, loss], device=device, ) loss_values_D.append(loss.numpy()[0]) for i in range(3): l_0 = loss_values_D[i * 2] l_1 = loss_values_D[i * 2 + 1] gradient = (l_1 - l_0) / (2.0 * eps) numeric_D[i] = gradient error_p = ((analytic_p - numeric_p) * (analytic_p - numeric_p)).sum(axis=0) error_D = ((analytic_D - numeric_D) * (analytic_D - numeric_D)).sum(axis=0) tolerance = 1.0e-3 test.assertTrue(error_p < tolerance, f"error is {error_p} which is >= {tolerance}") test.assertTrue(error_D < tolerance, f"error is {error_D} which is >= {tolerance}") @wp.kernel def raycast_kernel( mesh: wp.uint64, ray_starts: wp.array(dtype=wp.vec3), ray_directions: wp.array(dtype=wp.vec3), count: wp.array(dtype=int), ): t = float(0.0) # hit distance along ray u = float(0.0) # hit face barycentric u v = float(0.0) # hit face barycentric v sign = float(0.0) # hit face sign n = wp.vec3() # hit face normal f = int(0) # hit face index max_dist = 1e6 # max raycast distance # ray cast against the mesh tid = wp.tid() if wp.mesh_query_ray(mesh, ray_starts[tid], ray_directions[tid], max_dist, t, u, v, sign, n, f): wp.atomic_add(count, 0, 1) # tests rays against a quad of two connected triangles # with rays exactly falling on the edge, tests that # there are no leaks def test_mesh_query_ray_edge(test, device): # Create raycast starts and directions xx, yy = np.meshgrid(np.arange(0.1, 0.4, 0.01), np.arange(0.1, 0.4, 0.01)) xx = xx.flatten().reshape(-1, 1) yy = yy.flatten().reshape(-1, 1) zz = np.ones_like(xx) ray_starts = np.concatenate((xx, yy, zz), axis=1) ray_dirs = np.zeros_like(ray_starts) ray_dirs[:, 2] = -1.0 # Create simple square mesh vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.5, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0]], dtype=np.float32) triangles = np.array([[1, 0, 2], [1, 2, 3]], dtype=np.int32) mesh = wp.Mesh( points=wp.array(vertices, dtype=wp.vec3, device=device), indices=wp.array(triangles.flatten(), dtype=int, device=device), ) counts = wp.zeros(1, dtype=int, device=device) n = len(ray_starts) ray_starts = wp.array(ray_starts, shape=(n,), dtype=wp.vec3, device=device) ray_dirs = wp.array(ray_dirs, shape=(n,), dtype=wp.vec3, device=device) wp.launch(kernel=raycast_kernel, dim=n, inputs=[mesh.id, ray_starts, ray_dirs, counts], device=device) wp.synchronize() test.assertEqual(counts.numpy()[0], n) devices = get_test_devices() class TestMeshQueryRay(unittest.TestCase): def test_mesh_query_codegen_adjoints_with_select(self): def kernel_fn( mesh: wp.uint64, ): v = wp.vec3(0.0, 0.0, 0.0) d = 1e-6 if True: query = wp.mesh_query_ray(mesh, v, v, d) else: query = wp.mesh_query_ray(mesh, v, v, d) wp.Kernel(func=kernel_fn) add_function_test(TestMeshQueryRay, "test_mesh_query_ray_edge", test_mesh_query_ray_edge, devices=devices) add_function_test(TestMeshQueryRay, "test_mesh_query_ray_grad", test_mesh_query_ray_grad, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
9,199
Python
30.61512
121
0.599957
NVIDIA/warp/warp/tests/test_multigpu.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * from warp.utils import check_iommu @wp.kernel def inc(a: wp.array(dtype=float)): tid = wp.tid() a[tid] = a[tid] + 1.0 @wp.kernel def arange(start: int, step: int, a: wp.array(dtype=int)): tid = wp.tid() a[tid] = start + step * tid class TestMultiGPU(unittest.TestCase): @unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices") def test_multigpu_set_device(self): # save default device saved_device = wp.get_device() n = 32 wp.set_device("cuda:0") a0 = wp.empty(n, dtype=int) wp.launch(arange, dim=a0.size, inputs=[0, 1, a0]) wp.set_device("cuda:1") a1 = wp.empty(n, dtype=int) wp.launch(arange, dim=a1.size, inputs=[0, 1, a1]) # restore default device wp.set_device(saved_device) assert a0.device == "cuda:0" assert a1.device == "cuda:1" expected = np.arange(n, dtype=int) assert_np_equal(a0.numpy(), expected) assert_np_equal(a1.numpy(), expected) @unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices") def test_multigpu_scoped_device(self): n = 32 with wp.ScopedDevice("cuda:0"): a0 = wp.empty(n, dtype=int) wp.launch(arange, dim=a0.size, inputs=[0, 1, a0]) with wp.ScopedDevice("cuda:1"): a1 = wp.empty(n, dtype=int) wp.launch(arange, dim=a1.size, inputs=[0, 1, a1]) assert a0.device == "cuda:0" assert a1.device == "cuda:1" expected = np.arange(n, dtype=int) assert_np_equal(a0.numpy(), expected) assert_np_equal(a1.numpy(), expected) @unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices") def test_multigpu_nesting(self): initial_device = wp.get_device() initial_cuda_device = wp.get_cuda_device() with wp.ScopedDevice("cuda:1"): assert wp.get_device() == "cuda:1" assert wp.get_cuda_device() == "cuda:1" with wp.ScopedDevice("cuda:0"): assert wp.get_device() == "cuda:0" assert wp.get_cuda_device() == "cuda:0" with wp.ScopedDevice("cpu"): assert wp.get_device() == "cpu" assert wp.get_cuda_device() == "cuda:0" wp.set_device("cuda:1") assert wp.get_device() == "cuda:1" assert wp.get_cuda_device() == "cuda:1" assert wp.get_device() == "cuda:0" assert wp.get_cuda_device() == "cuda:0" assert wp.get_device() == "cuda:1" assert wp.get_cuda_device() == "cuda:1" assert wp.get_device() == initial_device assert wp.get_cuda_device() == initial_cuda_device @unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices") @unittest.skipUnless(check_iommu(), "IOMMU seems enabled") def test_multigpu_pingpong(self): n = 1024 * 1024 a0 = wp.zeros(n, dtype=float, device="cuda:0") a1 = wp.zeros(n, dtype=float, device="cuda:1") iters = 10 for _ in range(iters): wp.launch(inc, dim=a0.size, inputs=[a0], device=a0.device) wp.synchronize_device(a0.device) wp.copy(a1, a0) wp.launch(inc, dim=a1.size, inputs=[a1], device=a1.device) wp.synchronize_device(a1.device) wp.copy(a0, a1) expected = np.full(n, iters * 2, dtype=np.float32) assert_np_equal(a0.numpy(), expected) assert_np_equal(a1.numpy(), expected) @unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices") @unittest.skipUnless(check_iommu(), "IOMMU seems enabled") def test_multigpu_pingpong_streams(self): n = 1024 * 1024 a0 = wp.zeros(n, dtype=float, device="cuda:0") a1 = wp.zeros(n, dtype=float, device="cuda:1") stream0 = wp.get_stream("cuda:0") stream1 = wp.get_stream("cuda:1") iters = 10 for _ in range(iters): wp.launch(inc, dim=a0.size, inputs=[a0], stream=stream0) stream1.wait_stream(stream0) wp.copy(a1, a0, stream=stream1) wp.launch(inc, dim=a1.size, inputs=[a1], stream=stream1) stream0.wait_stream(stream1) wp.copy(a0, a1, stream=stream0) expected = np.full(n, iters * 2, dtype=np.float32) assert_np_equal(a0.numpy(), expected) assert_np_equal(a1.numpy(), expected) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=False)
5,247
Python
31.395062
94
0.589289
NVIDIA/warp/warp/tests/unittest_utils.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import ctypes import ctypes.util import importlib import os import sys import time import unittest from typing import Optional import numpy as np import warp as wp pxr = importlib.util.find_spec("pxr") USD_AVAILABLE = pxr is not None # default test mode (see get_test_devices()) # "basic" - only run on CPU and first GPU device # "unique" - run on CPU and all unique GPU arches # "unique_or_2x" - run on CPU and all unique GPU arches. If there is a single GPU arch, add a second GPU if it exists. # "all" - run on all devices test_mode = "unique_or_2x" coverage_enabled = False coverage_temp_dir = None coverage_branch = None try: if sys.platform == "win32": LIBC = ctypes.CDLL("ucrtbase.dll") else: LIBC = ctypes.CDLL(ctypes.util.find_library("c")) except OSError: print("Failed to load the standard C library") LIBC = None def get_selected_cuda_test_devices(mode: Optional[str] = None): """Returns a list of CUDA devices according the selected ``mode`` behavior. If ``mode`` is ``None``, the ``global test_mode`` value will be used and this list will be a subset of the devices returned from ``get_test_devices()``. Args: mode: ``"basic"``, returns a list containing up to a single CUDA device. ``"unique"``, returns a list containing no more than one device of every CUDA architecture on the system. ``"unique_or_2x"`` behaves like ``"unique"`` but adds up to one additional CUDA device if the system only devices of a single CUDA architecture. """ if mode is None: global test_mode mode = test_mode if mode == "basic": if wp.is_cuda_available(): return [wp.get_device("cuda:0")] else: return [] cuda_devices = wp.get_cuda_devices() first_cuda_devices = {} for d in cuda_devices: if d.arch not in first_cuda_devices: first_cuda_devices[d.arch] = d selected_cuda_devices = list(first_cuda_devices.values()) if mode == "unique_or_2x" and len(selected_cuda_devices) == 1 and len(cuda_devices) > 1: for d in cuda_devices: if d not in selected_cuda_devices: selected_cuda_devices.append(d) break return selected_cuda_devices def get_test_devices(mode: Optional[str] = None): """Returns a list of devices based on the mode selected. Args: mode: The testing mode to specify which devices to include. If not provided or ``None``, the ``global test_mode`` value will be used. "basic": Returns the CPU and the first GPU device when available. "unique": Returns the CPU and all unique GPU architectures. "unique_or_2x" (default): Behaves like "unique" but adds up to one additional CUDA device if the system only devices of a single CUDA architecture. "all": Returns all available devices. """ if mode is None: global test_mode mode = test_mode devices = [] if mode == "basic": # only run on CPU and first GPU device if wp.is_cpu_available(): devices.append(wp.get_device("cpu")) if wp.is_cuda_available(): devices.append(wp.get_device("cuda:0")) elif mode == "unique" or mode == "unique_or_2x": # run on CPU and a subset of GPUs if wp.is_cpu_available(): devices.append(wp.get_device("cpu")) devices.extend(get_selected_cuda_test_devices(mode)) elif mode == "all": # run on all devices devices = wp.get_devices() else: raise ValueError(f"Unknown test mode selected: {mode}") return devices def get_cuda_test_devices(mode=None): devices = get_test_devices(mode=mode) return [d for d in devices if d.is_cuda] # redirects and captures all stdout output (including from C-libs) class StdOutCapture: def begin(self): # Flush the stream buffers managed by libc. # This is needed at the moment due to Carbonite not flushing the logs # being printed out when extensions are starting up. if LIBC is not None: LIBC.fflush(None) # save original self.saved = sys.stdout self.target = os.dup(self.saved.fileno()) # create temporary capture stream import io import tempfile self.tempfile = io.TextIOWrapper( tempfile.TemporaryFile(buffering=0), encoding="utf-8", errors="replace", newline="", write_through=True, ) os.dup2(self.tempfile.fileno(), self.saved.fileno()) sys.stdout = self.tempfile def end(self): # The following sleep doesn't seem to fix the test_print failure on Windows # if sys.platform == "win32": # # Workaround for what seems to be a Windows-specific bug where # # the output of CUDA's `printf` is not being immediately flushed # # despite the context synchronisation. # time.sleep(0.01) if LIBC is not None: LIBC.fflush(None) os.dup2(self.target, self.saved.fileno()) os.close(self.target) self.tempfile.seek(0) res = self.tempfile.buffer.read() self.tempfile.close() sys.stdout = self.saved return str(res.decode("utf-8")) class CheckOutput: def __init__(self, test): self.test = test def __enter__(self): # wp.force_load() self.capture = StdOutCapture() self.capture.begin() def __exit__(self, exc_type, exc_value, traceback): # ensure any stdout output is flushed wp.synchronize() s = self.capture.end() if s != "": print(s.rstrip()) # fail if test produces unexpected output (e.g.: from wp.expect_eq() builtins) # we allow strings starting of the form "Module xxx load on device xxx" # for lazy loaded modules if s != "" and not s.startswith("Module"): self.test.fail(f"Unexpected output:\n'{s.rstrip()}'") def assert_array_equal(result: wp.array, expect: wp.array): np.testing.assert_equal(result.numpy(), expect.numpy()) def assert_np_equal(result: np.ndarray, expect: np.ndarray, tol=0.0): if tol != 0.0: # TODO: Get all tests working without the .flatten() np.testing.assert_allclose(result.flatten(), expect.flatten(), atol=tol, equal_nan=True) else: # TODO: Get all tests working with strict=True np.testing.assert_array_equal(result, expect) # if check_output is True any output to stdout will be treated as an error def create_test_func(func, device, check_output, **kwargs): # pass args to func def test_func(self): if check_output: with CheckOutput(self): func(self, device, **kwargs) else: func(self, device, **kwargs) return test_func def skip_test_func(self): # A function to use so we can tell unittest that the test was skipped. self.skipTest("No suitable devices to run the test.") def sanitize_identifier(s): """replace all non-identifier characters with '_'""" s = str(s) if s.isidentifier(): return s else: import re return re.sub(r"\W|^(?=\d)", "_", s) def add_function_test(cls, name, func, devices=None, check_output=True, **kwargs): if devices is None: setattr(cls, name, create_test_func(func, None, check_output, **kwargs)) elif isinstance(devices, list): if not devices: # No devices to run this test setattr(cls, name, skip_test_func) else: for device in devices: setattr( cls, name + "_" + sanitize_identifier(device), create_test_func(func, device, check_output, **kwargs), ) else: setattr( cls, name + "_" + sanitize_identifier(devices), create_test_func(func, devices, check_output, **kwargs), ) def add_kernel_test(cls, kernel, dim, name=None, expect=None, inputs=None, devices=None): def test_func(self, device): args = [] if inputs: args.extend(inputs) if expect: # allocate outputs to match results result = wp.array(expect, dtype=int, device=device) output = wp.zeros_like(result) args.append(output) # force load so that we don't generate any log output during launch kernel.module.load(device) with CheckOutput(self): wp.launch(kernel, dim=dim, inputs=args, device=device) # check output values if expect: assert_array_equal(output, result) if name is None: name = kernel.key # device is required for kernel tests, so use all devices if none were given if devices is None: devices = get_test_devices() # register test func with class for the given devices for d in devices: # use a function to forward the device to the inner test function def test_func_wrapper(test, device=d): test_func(test, device) setattr(cls, name + "_" + sanitize_identifier(d), test_func_wrapper) # helper that first calls the test function to generate all kernel permutations # so that compilation is done in one-shot instead of per-test def add_function_test_register_kernel(cls, name, func, devices=None, **kwargs): func(None, None, **kwargs, register_kernels=True) add_function_test(cls, name, func, devices=devices, **kwargs) def write_junit_results( outfile: str, test_records: list, tests_run: int, tests_failed: int, tests_errored: int, tests_skipped: int, test_duration: float, ): """Write a JUnit XML from our report data The report file is needed for GitLab to add test reports in merge requests. """ import xml.etree.ElementTree as ET root = ET.Element( "testsuite", name="Warp Tests", failures=str(tests_failed), errors=str(tests_errored), skipped=str(tests_skipped), tests=str(tests_run), time=f"{test_duration:.3f}", ) for test_data in test_records: test = test_data[0] test_duration = test_data[1] test_status = test_data[2] test_case = ET.SubElement( root, "testcase", classname=test.__class__.__name__, name=test._testMethodName, time=f"{test_duration:.3f}" ) if test_status == "FAIL": failure = ET.SubElement(test_case, "failure", message=str(test_data[3])) failure.text = str(test_data[4]) # Stacktrace elif test_status == "ERROR": error = ET.SubElement(test_case, "error") error.text = str(test_data[4]) # Stacktrace elif test_status == "SKIP": skip = ET.SubElement(test_case, "skipped") skip.text = str(test_data[3]) # The skip reason tree = ET.ElementTree(root) if hasattr(ET, "indent"): ET.indent(root) # Pretty-printed XML output, Python 3.9 required tree.write(outfile, encoding="utf-8", xml_declaration=True) class ParallelJunitTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): stream = type(stream)(sys.stderr) self.test_record = [] super().__init__(stream, descriptions, verbosity) def startTest(self, test): if self.showAll: self.stream.writeln(f"{self.getDescription(test)} ...") self.stream.flush() self.start_time = time.perf_counter_ns() super(unittest.TextTestResult, self).startTest(test) def _add_helper(self, test, dots_message, show_all_message): if self.showAll: self.stream.writeln(f"{self.getDescription(test)} ... {show_all_message}") elif self.dots: self.stream.write(dots_message) self.stream.flush() def _record_test(self, test, code, message=None, details=None): duration = round((time.perf_counter_ns() - self.start_time) * 1e-9, 3) # [s] self.test_record.append((test, duration, code, message, details)) def addSuccess(self, test): super(unittest.TextTestResult, self).addSuccess(test) self._add_helper(test, ".", "ok") self._record_test(test, "OK") def addError(self, test, err): super(unittest.TextTestResult, self).addError(test, err) self._add_helper(test, "E", "ERROR") self._record_test(test, "ERROR", str(err[1]), self._exc_info_to_string(err, test)) def addFailure(self, test, err): super(unittest.TextTestResult, self).addFailure(test, err) self._add_helper(test, "F", "FAIL") self._record_test(test, "FAIL", str(err[1]), self._exc_info_to_string(err, test)) def addSkip(self, test, reason): super(unittest.TextTestResult, self).addSkip(test, reason) self._add_helper(test, "s", f"skipped {reason!r}") self._record_test(test, "SKIP", reason) def addExpectedFailure(self, test, err): super(unittest.TextTestResult, self).addExpectedFailure(test, err) self._add_helper(test, "x", "expected failure") self._record_test(test, "OK", "expected failure") def addUnexpectedSuccess(self, test): super(unittest.TextTestResult, self).addUnexpectedSuccess(test) self._add_helper(test, "u", "unexpected success") self._record_test(test, "FAIL", "unexpected success") def addSubTest(self, test, subtest, err): super(unittest.TextTestResult, self).addSubTest(test, subtest, err) if err is not None: self._add_helper(test, "E", "ERROR") # err is (class, error, traceback) self._record_test(test, "FAIL", str(err[1]), self._exc_info_to_string(err, test)) def printErrors(self): pass
14,463
Python
32.250575
120
0.617438
NVIDIA/warp/warp/tests/aux_test_compile_consts_dummy.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import warp as wp MINUS_ONE = wp.constant(-1)
471
Python
41.909087
76
0.804671
NVIDIA/warp/warp/tests/test_closest_point_edge_edge.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * epsilon = 0.00001 @wp.kernel def closest_point_edge_edge_kernel( p1: wp.array(dtype=wp.vec3), q1: wp.array(dtype=wp.vec3), p2: wp.array(dtype=wp.vec3), q2: wp.array(dtype=wp.vec3), epsilon: float, st0: wp.array(dtype=wp.vec3), c1: wp.array(dtype=wp.vec3), c2: wp.array(dtype=wp.vec3), ): tid = wp.tid() st = wp.closest_point_edge_edge(p1[tid], q1[tid], p2[tid], q2[tid], epsilon) s = st[0] t = st[1] st0[tid] = st c1[tid] = p1[tid] + (q1[tid] - p1[tid]) * s c2[tid] = p2[tid] + (q2[tid] - p2[tid]) * t def closest_point_edge_edge_launch(p1, q1, p2, q2, epsilon, st0, c1, c2, device): n = len(p1) wp.launch( kernel=closest_point_edge_edge_kernel, dim=n, inputs=[p1, q1, p2, q2, epsilon], outputs=[st0, c1, c2], device=device, ) def run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device): p1 = wp.array(p1_h, dtype=wp.vec3, device=device) q1 = wp.array(q1_h, dtype=wp.vec3, device=device) p2 = wp.array(p2_h, dtype=wp.vec3, device=device) q2 = wp.array(q2_h, dtype=wp.vec3, device=device) st0 = wp.empty_like(p1) c1 = wp.empty_like(p1) c2 = wp.empty_like(p1) closest_point_edge_edge_launch(p1, q1, p2, q2, epsilon, st0, c1, c2, device) wp.synchronize() view = st0.numpy() return view def test_edge_edge_middle_crossing(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[1, 1, 0]]) p2_h = np.array([[0, 1, 0]]) q2_h = np.array([[1, 0, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.5) # s value test.assertAlmostEqual(st0[1], 0.5) # t value def test_edge_edge_parallel_s1_t0(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[1, 1, 0]]) p2_h = np.array([[2, 2, 0]]) q2_h = np.array([[3, 3, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 1.0) # s value test.assertAlmostEqual(st0[1], 0.0) # t value def test_edge_edge_parallel_s0_t1(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[1, 1, 0]]) p2_h = np.array([[-2, -2, 0]]) q2_h = np.array([[-1, -1, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.0) # s value test.assertAlmostEqual(st0[1], 1.0) # t value def test_edge_edge_both_degenerate_case(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[0, 0, 0]]) p2_h = np.array([[1, 1, 1]]) q2_h = np.array([[1, 1, 1]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.0) # s value test.assertAlmostEqual(st0[1], 0.0) # t value def test_edge_edge_degenerate_first_edge(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[0, 0, 0]]) p2_h = np.array([[0, 1, 0]]) q2_h = np.array([[1, 0, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.0) # s value test.assertAlmostEqual(st0[1], 0.5) # t value def test_edge_edge_degenerate_second_edge(test, device): p1_h = np.array([[1, 0, 0]]) q1_h = np.array([[0, 1, 0]]) p2_h = np.array([[1, 1, 0]]) q2_h = np.array([[1, 1, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.5) # s value test.assertAlmostEqual(st0[1], 0.0) # t value def test_edge_edge_parallel(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[1, 0, 0]]) p2_h = np.array([[-0.5, 1, 0]]) q2_h = np.array([[0.5, 1, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.0) # s value test.assertAlmostEqual(st0[1], 0.5) # t value def test_edge_edge_perpendicular_s1_t0(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[1, 1, 0]]) p2_h = np.array([[10, 1, 0]]) q2_h = np.array([[11, 0, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 1.0) # s value test.assertAlmostEqual(st0[1], 0.0) # t value def test_edge_edge_perpendicular_s0_t1(test, device): p1_h = np.array([[0, 0, 0]]) q1_h = np.array([[1, 1, 0]]) p2_h = np.array([[-11, -1, 0]]) q2_h = np.array([[-5, 0, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.0) # s value test.assertAlmostEqual(st0[1], 1.0) # t value devices = get_test_devices() class TestClosestPointEdgeEdgeMethods(unittest.TestCase): pass add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_middle_crossing", test_edge_edge_middle_crossing, devices=devices, ) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_parallel_s1_t0", test_edge_edge_parallel_s1_t0, devices=devices ) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_parallel_s0_t1", test_edge_edge_parallel_s0_t1, devices=devices ) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_both_degenerate_case", test_edge_edge_both_degenerate_case, devices=devices, ) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_degenerate_first_edge", test_edge_edge_degenerate_first_edge, devices=devices, ) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_degenerate_second_edge", test_edge_edge_degenerate_second_edge, devices=devices, ) add_function_test(TestClosestPointEdgeEdgeMethods, "test_edge_edge_parallel", test_edge_edge_parallel, devices=devices) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_perpendicular_s1_t0", test_edge_edge_perpendicular_s1_t0, devices=devices, ) add_function_test( TestClosestPointEdgeEdgeMethods, "test_edge_edge_perpendicular_s0_t1", test_edge_edge_perpendicular_s0_t1, devices=devices, ) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
6,831
Python
28.964912
119
0.624213
NVIDIA/warp/warp/tests/test_sim_grad.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp import warp.sim from warp.tests.unittest_utils import * @wp.kernel def evaluate_loss( joint_q: wp.array(dtype=float), weighting: float, target: float, # output loss: wp.array(dtype=float), ): tid = wp.tid() # wp.atomic_add(loss, 0, weighting * (target - joint_q[tid * 2 + 1]) ** 2.0) d = wp.abs(target - joint_q[tid * 2 + 1]) wp.atomic_add(loss, 0, weighting * d) @wp.kernel def assign_action(action: wp.array(dtype=float), joint_act: wp.array(dtype=float)): tid = wp.tid() joint_act[2 * tid] = action[tid] def gradcheck(func, inputs, device, eps=1e-1, tol=1e-2): """ Checks that the gradient of the Warp kernel is correct by comparing it to the numerical gradient computed using finite differences. """ def f(xs): # call the kernel without taping for finite differences wp_xs = [wp.array(xs[i], ndim=1, dtype=inputs[i].dtype, device=device) for i in range(len(inputs))] output = func(*wp_xs) return output.numpy()[0] # compute numerical gradient numerical_grad = [] np_xs = [] for i in range(len(inputs)): np_xs.append(inputs[i].numpy().flatten().copy()) numerical_grad.append(np.zeros_like(np_xs[-1])) inputs[i].requires_grad = True for i in range(len(np_xs)): for j in range(len(np_xs[i])): np_xs[i][j] += eps y1 = f(np_xs) np_xs[i][j] -= 2 * eps y2 = f(np_xs) np_xs[i][j] += eps numerical_grad[i][j] = (y1 - y2) / (2 * eps) # compute analytical gradient tape = wp.Tape() with tape: output = func(*inputs) tape.backward(loss=output) # compare gradients for i in range(len(inputs)): grad = tape.gradients[inputs[i]] assert_np_equal(grad.numpy(), numerical_grad[i], tol=tol) # ensure the signs match assert np.allclose(grad.numpy() * numerical_grad[i] > 0, True) tape.zero() def test_box_pushing_on_rails(test, device, joint_type, integrator_type): # Two boxes on a rail (prismatic or D6 joint), one is pushed, the other is passive. # The absolute distance to a target is measured and gradients are compared for # a push that is too far and too close. num_envs = 2 num_steps = 200 sim_substeps = 2 dt = 1 / 30 target = 5.0 if integrator_type == 0: contact_ke = 1e5 contact_kd = 1e3 else: contact_ke = 1e5 contact_kd = 1e1 complete_builder = wp.sim.ModelBuilder() complete_builder.default_shape_ke = contact_ke complete_builder.default_shape_kd = contact_kd for _ in range(num_envs): builder = wp.sim.ModelBuilder() builder.default_shape_ke = complete_builder.default_shape_ke builder.default_shape_kd = complete_builder.default_shape_kd b0 = builder.add_body(name="pusher") builder.add_shape_box(b0, density=1000.0) b1 = builder.add_body(name="passive") builder.add_shape_box(b1, hx=0.4, hy=0.4, hz=0.4, density=1000.0) if joint_type == 0: builder.add_joint_prismatic(-1, b0) builder.add_joint_prismatic(-1, b1) else: builder.add_joint_d6(-1, b0, linear_axes=[wp.sim.JointAxis((1.0, 0.0, 0.0))]) builder.add_joint_d6(-1, b1, linear_axes=[wp.sim.JointAxis((1.0, 0.0, 0.0))]) builder.joint_q[-2:] = [0.0, 1.0] complete_builder.add_builder(builder) assert complete_builder.body_count == 2 * num_envs assert complete_builder.joint_count == 2 * num_envs assert set(complete_builder.shape_collision_group) == set(range(1, num_envs + 1)) complete_builder.gravity = 0.0 model = complete_builder.finalize(device=device, requires_grad=True) model.ground = False model.joint_attach_ke = 32000.0 * 16 model.joint_attach_kd = 500.0 * 4 if integrator_type == 0: integrator = wp.sim.FeatherstoneIntegrator(model, update_mass_matrix_every=num_steps * sim_substeps) elif integrator_type == 1: integrator = wp.sim.SemiImplicitIntegrator() sim_substeps *= 5 else: integrator = wp.sim.XPBDIntegrator(iterations=2, rigid_contact_relaxation=1.0) # renderer = wp.sim.render.SimRenderer(model, "test_sim_grad.usd", scaling=1.0) renderer = None render_time = 0.0 def rollout(action: wp.array) -> wp.array: nonlocal render_time states = [model.state() for _ in range(num_steps * sim_substeps + 1)] if not isinstance(integrator, wp.sim.FeatherstoneIntegrator): # apply initial generalized coordinates wp.sim.eval_fk(model, model.joint_q, model.joint_qd, None, states[0]) control_active = model.control() control_nop = model.control() wp.launch( assign_action, dim=num_envs, inputs=[action], outputs=[control_active.joint_act], device=model.device, ) i = 0 for step in range(num_steps): wp.sim.collide(model, states[i]) control = control_active if step < 10 else control_nop if renderer: renderer.begin_frame(render_time) renderer.render(states[i]) renderer.end_frame() render_time += dt for _ in range(sim_substeps): integrator.simulate(model, states[i], states[i + 1], dt / sim_substeps, control) i += 1 if not isinstance(integrator, wp.sim.FeatherstoneIntegrator): # compute generalized coordinates wp.sim.eval_ik(model, states[-1], states[-1].joint_q, states[-1].joint_qd) loss = wp.zeros(1, requires_grad=True, device=device) wp.launch( evaluate_loss, dim=num_envs, inputs=[states[-1].joint_q, 1.0, target], outputs=[loss], device=model.device, ) if renderer: renderer.save() return loss action_too_far = wp.array( [5000.0 for _ in range(num_envs)], device=device, dtype=wp.float32, requires_grad=True, ) tol = 1e-2 if isinstance(integrator, wp.sim.XPBDIntegrator): # Euler, XPBD do not yield as accurate gradients, but at least the # signs should match tol = 0.1 gradcheck(rollout, [action_too_far], device=device, eps=0.2, tol=tol) action_too_close = wp.array( [1500.0 for _ in range(num_envs)], device=device, dtype=wp.float32, requires_grad=True, ) gradcheck(rollout, [action_too_close], device=device, eps=0.2, tol=tol) devices = get_test_devices() class TestSimGradients(unittest.TestCase): pass for int_type, int_name in enumerate(["featherstone", "semiimplicit"]): for jt_type, jt_name in enumerate(["prismatic", "d6"]): test_name = f"test_box_pushing_on_rails_{int_name}_{jt_name}" def test_fn(self, device, jt_type=jt_type, int_type=int_type): return test_box_pushing_on_rails(self, device, jt_type, int_type) add_function_test(TestSimGradients, test_name, test_fn, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2, failfast=True)
7,819
Python
31.314049
108
0.611203
NVIDIA/warp/warp/tests/test_bvh.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import unittest import numpy as np import warp as wp from warp.tests.unittest_utils import * @wp.kernel def bvh_query_aabb(bvh_id: wp.uint64, lower: wp.vec3, upper: wp.vec3, bounds_intersected: wp.array(dtype=int)): query = wp.bvh_query_aabb(bvh_id, lower, upper) bounds_nr = int(0) while wp.bvh_query_next(query, bounds_nr): bounds_intersected[bounds_nr] = 1 @wp.kernel def bvh_query_ray(bvh_id: wp.uint64, start: wp.vec3, dir: wp.vec3, bounds_intersected: wp.array(dtype=int)): query = wp.bvh_query_ray(bvh_id, start, dir) bounds_nr = int(0) while wp.bvh_query_next(query, bounds_nr): bounds_intersected[bounds_nr] = 1 def aabb_overlap(a_lower, a_upper, b_lower, b_upper): if ( a_lower[0] > b_upper[0] or a_lower[1] > b_upper[1] or a_lower[2] > b_upper[2] or a_upper[0] < b_lower[0] or a_upper[1] < b_lower[1] or a_upper[2] < b_lower[2] ): return 0 else: return 1 def intersect_ray_aabb(start, dir, lower, upper): l1 = (lower[0] - start[0]) * dir[0] l2 = (upper[0] - start[0]) * dir[0] lmin = min(l1, l2) lmax = max(l1, l2) l1 = (lower[1] - start[1]) * dir[1] l2 = (upper[1] - start[1]) * dir[1] lmin = max(min(l1, l2), lmin) lmax = min(max(l1, l2), lmax) l1 = (lower[2] - start[2]) * dir[2] l2 = (upper[2] - start[2]) * dir[2] lmin = max(min(l1, l2), lmin) lmax = min(max(l1, l2), lmax) if lmax >= 0.0 and lmax >= lmin: return 1 else: return 0 def test_bvh(test, type, device): rng = np.random.default_rng(123) num_bounds = 100 lowers = rng.random(size=(num_bounds, 3)) * 5.0 uppers = lowers + rng.random(size=(num_bounds, 3)) * 5.0 device_lowers = wp.array(lowers, dtype=wp.vec3, device=device) device_uppers = wp.array(uppers, dtype=wp.vec3, device=device) bvh = wp.Bvh(device_lowers, device_uppers) bounds_intersected = wp.zeros(shape=(num_bounds), dtype=int, device=device) query_lower = wp.vec3(2.0, 2.0, 2.0) query_upper = wp.vec3(8.0, 8.0, 8.0) query_start = wp.vec3(0.0, 0.0, 0.0) query_dir = wp.normalize(wp.vec3(1.0, 1.0, 1.0)) for test_case in range(2): if type == "AABB": wp.launch( kernel=bvh_query_aabb, dim=1, inputs=[bvh.id, query_lower, query_upper, bounds_intersected], device=device, ) else: wp.launch( kernel=bvh_query_ray, dim=1, inputs=[bvh.id, query_start, query_dir, bounds_intersected], device=device ) device_intersected = bounds_intersected.numpy() for i in range(num_bounds): lower = lowers[i] upper = uppers[i] if type == "AABB": host_intersected = aabb_overlap(lower, upper, query_lower, query_upper) else: host_intersected = intersect_ray_aabb(query_start, query_dir, lower, upper) test.assertEqual(host_intersected, device_intersected[i]) if test_case == 0: lowers = rng.random(size=(num_bounds, 3)) * 5.0 uppers = lowers + rng.random(size=(num_bounds, 3)) * 5.0 wp.copy(device_lowers, wp.array(lowers, dtype=wp.vec3, device=device)) wp.copy(device_uppers, wp.array(uppers, dtype=wp.vec3, device=device)) bvh.refit() bounds_intersected.zero_() def test_bvh_query_aabb(test, device): test_bvh(test, "AABB", device) def test_bvh_query_ray(test, device): test_bvh(test, "ray", device) devices = get_test_devices() class TestBvh(unittest.TestCase): def test_bvh_codegen_adjoints_with_select(self): def kernel_fn(bvh: wp.uint64): v = wp.vec3(0.0, 0.0, 0.0) bounds_nr = int(0) if True: query_1 = wp.bvh_query_aabb(bvh, v, v) query_2 = wp.bvh_query_ray(bvh, v, v) wp.bvh_query_next(query_1, bounds_nr) wp.bvh_query_next(query_2, bounds_nr) else: query_1 = wp.bvh_query_aabb(bvh, v, v) query_2 = wp.bvh_query_ray(bvh, v, v) wp.bvh_query_next(query_1, bounds_nr) wp.bvh_query_next(query_2, bounds_nr) wp.Kernel(func=kernel_fn) add_function_test(TestBvh, "test_bvh_aabb", test_bvh_query_aabb, devices=devices) add_function_test(TestBvh, "test_bvh_ray", test_bvh_query_ray, devices=devices) if __name__ == "__main__": wp.build.clear_kernel_cache() unittest.main(verbosity=2)
5,050
Python
29.98773
119
0.590099
NVIDIA/warp/warp/thirdparty/dlpack.py
import ctypes _c_str_dltensor = b"dltensor" class DLDeviceType(ctypes.c_int): """The enum that encodes the type of the device where DLTensor memory is allocated. """ kDLCPU = 1 kDLCUDA = 2 kDLCUDAHost = 3 kDLOpenCL = 4 kDLVulkan = 7 kDLMetal = 8 kDLVPI = 9 kDLROCM = 10 kDLROCMHost = 11 kDLCUDAManaged = 13 kDLOneAPI = 14 def __str__(self): return { self.kDLCPU: "CPU", self.kDLCUDA: "CUDA", self.kDLCUDAHost: "CUDAHost", self.kDLOpenCL: "OpenCL", self.kDLVulkan: "Vulkan", self.kDLMetal: "Metal", self.kDLVPI: "VPI", self.kDLROCM: "ROCM", self.kDLROCMHost: "ROMCHost", self.kDLCUDAManaged: "CUDAManaged", self.kDLOneAPI: "oneAPI", }[self.value] class DLDevice(ctypes.Structure): """Represents the device where DLTensor memory is allocated. The device is represented by the pair of fields: device_type: DLDeviceType device_id: c_int """ _fields_ = [ ("device_type", DLDeviceType), ("device_id", ctypes.c_int), ] class DLDataTypeCode(ctypes.c_uint8): """An integer that encodes the category of DLTensor elements' data type.""" kDLInt = 0 kDLUInt = 1 kDLFloat = 2 kDLOpaquePointer = 3 kDLBfloat = 4 kDLComplex = 5 def __str__(self): return { self.kDLInt: "int", self.kDLUInt: "uint", self.kDLFloat: "float", self.kDLBfloat: "bfloat", self.kDLComplex: "complex", self.kDLOpaquePointer: "void_p", }[self.value] class DLDataType(ctypes.Structure): """Descriptor of data type for elements of DLTensor. The data type is described by a triple, `DLDataType.type_code`, `DLDataType.bits`, and `DLDataType.lanes`. The element is understood as packed `lanes` repetitions of elements from `type_code` data-category of width `bits`. """ _fields_ = [ ("type_code", DLDataTypeCode), ("bits", ctypes.c_uint8), ("lanes", ctypes.c_uint16), ] TYPE_MAP = { "bool": (DLDataTypeCode.kDLUInt, 1, 1), "int8": (DLDataTypeCode.kDLInt, 8, 1), "int16": (DLDataTypeCode.kDLInt, 16, 1), "int32": (DLDataTypeCode.kDLInt, 32, 1), "int64": (DLDataTypeCode.kDLInt, 64, 1), "uint8": (DLDataTypeCode.kDLUInt, 8, 1), "uint16": (DLDataTypeCode.kDLUInt, 16, 1), "uint32": (DLDataTypeCode.kDLUInt, 32, 1), "uint64": (DLDataTypeCode.kDLUInt, 64, 1), "float16": (DLDataTypeCode.kDLFloat, 16, 1), "float32": (DLDataTypeCode.kDLFloat, 32, 1), "float64": (DLDataTypeCode.kDLFloat, 64, 1), "complex64": (DLDataTypeCode.kDLComplex, 64, 1), "complex128": (DLDataTypeCode.kDLComplex, 128, 1), } class DLTensor(ctypes.Structure): """Structure describing strided layout of DLTensor. Fields are: data: void pointer device: DLDevice ndim: number of indices needed to reference an element of the tensor dtype: data type descriptor shape: tuple with lengths of the corresponding tensor dimensions strides: tuple of numbers of array elements to step in each dimension when traversing the tensor byte_offset: data + byte_offset gives the address of tensor element with index (0,) * ndim """ _fields_ = [ ("data", ctypes.c_void_p), ("device", DLDevice), ("ndim", ctypes.c_int), ("dtype", DLDataType), ("shape", ctypes.POINTER(ctypes.c_int64)), ("strides", ctypes.POINTER(ctypes.c_int64)), ("byte_offset", ctypes.c_uint64), ] class DLManagedTensor(ctypes.Structure): """Structure storing the pointer to the tensor descriptor, deleter callable for the tensor descriptor, and pointer to some additional data. These are stored in fields `dl_tensor`, `deleter`, and `manager_ctx`.""" _fields_ = [ ("dl_tensor", DLTensor), ("manager_ctx", ctypes.c_void_p), ("deleter", ctypes.CFUNCTYPE(None, ctypes.c_void_p)), ]
4,273
Python
28.680555
79
0.586707
NVIDIA/warp/warp/thirdparty/appdirs.py
# -*- coding: utf-8 -*- # Copyright (c) 2005-2010 ActiveState Software Inc. # Copyright (c) 2013 Eddy Petrișor """Utilities for determining application-specific dirs. See <https://github.com/ActiveState/appdirs> for details and usage. """ # Dev Notes: # - MSDN on where to store app data files: # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html # - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html __version__ = "1.4.4" __version_info__ = tuple(int(segment) for segment in __version__.split(".")) import sys import os PY3 = sys.version_info[0] == 3 if PY3: unicode = str if sys.platform.startswith("java"): import platform os_name = platform.java_ver()[3][0] if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc. system = "win32" elif os_name.startswith("Mac"): # "Mac OS X", etc. system = "darwin" else: # "Linux", "SunOS", "FreeBSD", etc. # Setting this to "linux2" is not ideal, but only Windows or Mac # are actually checked for and the rest of the module expects # *sys.platform* style strings. system = "linux2" else: system = sys.platform def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: Mac OS X: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>". """ if system == "win32": if appauthor is None: appauthor = appname const = "CSIDL_APPDATA" if roaming else "CSIDL_LOCAL_APPDATA" path = os.path.normpath(_get_win_folder(const)) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == "darwin": path = os.path.expanduser("~/Library/Application Support/") if appname: path = os.path.join(path, appname) else: path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical site data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == "darwin": path = os.path.expanduser("/Library/Application Support") if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv("XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"])) pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user config directories are: Mac OS X: ~/Library/Preferences/<AppName> Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/<AppName>". """ if system == "win32": path = user_data_dir(appname, appauthor, None, roaming) elif system == "darwin": path = os.path.expanduser("~/Library/Preferences/") if appname: path = os.path.join(path, appname) else: path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set Typical site config directories are: Mac OS X: same as site_data_dir Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": path = site_data_dir(appname, appauthor) if appname and version: path = os.path.join(path, version) elif system == "darwin": path = os.path.expanduser("/Library/Preferences") if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_CONFIG_DIRS # only first, if multipath is False path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg") pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) if opinion: path = os.path.join(path, "Cache") elif system == "darwin": path = os.path.expanduser("~/Library/Caches") if appname: path = os.path.join(path, appname) else: path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user state directories are: Mac OS X: same as user_data_dir Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined Win *: same as user_data_dir For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv("XDG_STATE_HOME", os.path.expanduser("~/.local/state")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user log directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.join(os.path.expanduser("~/Library/Logs"), appname) elif system == "win32": path = user_data_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path class AppDirs(object): """Convenience wrapper for getting application dirs.""" def __init__(self, appname=None, appauthor=None, version=None, roaming=False, multipath=False): self.appname = appname self.appauthor = appauthor self.version = version self.roaming = roaming self.multipath = multipath @property def user_data_dir(self): return user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_data_dir(self): return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_config_dir(self): return user_config_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) @property def site_config_dir(self): return site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) @property def user_cache_dir(self): return user_cache_dir(self.appname, self.appauthor, version=self.version) @property def user_state_dir(self): return user_state_dir(self.appname, self.appauthor, version=self.version) @property def user_log_dir(self): return user_log_dir(self.appname, self.appauthor, version=self.version) # ---- internal support stuff def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir def _get_win_folder_with_ctypes(csidl_name): import ctypes csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, }[csidl_name] buf = ctypes.create_unicode_buffer(1024) ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in buf: if ord(c) > 255: has_high_char = True break if has_high_char: buf2 = ctypes.create_unicode_buffer(1024) if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): buf = buf2 return buf.value def _get_win_folder_with_jna(csidl_name): import array from com.sun import jna from com.sun.jna.platform import win32 buf_size = win32.WinDef.MAX_PATH * 2 buf = array.zeros("c", buf_size) shell = win32.Shell32.INSTANCE shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) dir = jna.Native.toString(buf.tostring()).rstrip("\0") # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: buf = array.zeros("c", buf_size) kernel = win32.Kernel32.INSTANCE if kernel.GetShortPathName(dir, buf, buf_size): dir = jna.Native.toString(buf.tostring()).rstrip("\0") return dir def _get_win_folder_from_environ(csidl_name): env_var_name = { "CSIDL_APPDATA": "APPDATA", "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE", "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA", }[csidl_name] return os.environ[env_var_name] if system == "win32": try: from ctypes import windll except ImportError: try: import com.sun.jna except ImportError: try: if PY3: import winreg as _winreg else: import _winreg except ImportError: _get_win_folder = _get_win_folder_from_environ else: _get_win_folder = _get_win_folder_from_registry else: _get_win_folder = _get_win_folder_with_jna else: _get_win_folder = _get_win_folder_with_ctypes # ---- self test code if __name__ == "__main__": appname = "MyApp" appauthor = "MyCompany" props = ( "user_data_dir", "user_config_dir", "user_cache_dir", "user_state_dir", "user_log_dir", "site_data_dir", "site_config_dir", ) print("-- app dirs %s --" % __version__) print("-- app dirs (with optional 'version')") dirs = AppDirs(appname, appauthor, version="1.0") for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'version')") dirs = AppDirs(appname, appauthor) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (without optional 'appauthor')") dirs = AppDirs(appname) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop))) print("\n-- app dirs (with disabled 'appauthor')") dirs = AppDirs(appname, appauthor=False) for prop in props: print("%s: %s" % (prop, getattr(dirs, prop)))
24,253
Python
39.490818
122
0.624005
NVIDIA/warp/warp/thirdparty/unittest_parallel.py
# Licensed under the MIT License # https://github.com/craigahobbs/unittest-parallel/blob/main/LICENSE # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: LicenseRef-NvidiaProprietary # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation and any modifications thereto. Any use, reproduction, # disclosure or distribution of this material and related documentation # without an express license agreement from NVIDIA CORPORATION or # its affiliates is strictly prohibited. """ unittest-parallel command-line script main module """ import argparse import concurrent.futures # NVIDIA Modification import multiprocessing import os import sys import tempfile import time import unittest from contextlib import contextmanager from io import StringIO import warp.tests.unittest_suites # NVIDIA Modification from warp.tests.unittest_utils import ( # NVIDIA modification ParallelJunitTestResult, write_junit_results, ) try: import coverage COVERAGE_AVAILABLE = True # NVIDIA Modification except ImportError: COVERAGE_AVAILABLE = False # NVIDIA Modification # The following variables are NVIDIA Modifications START_DIRECTORY = os.path.dirname(__file__) # The directory to start test discovery def main(argv=None): """ unittest-parallel command-line script main entry point """ # Command line arguments parser = argparse.ArgumentParser( prog="unittest-parallel", # NVIDIA Modifications follow: formatter_class=argparse.RawTextHelpFormatter, epilog="""Example usage: python -m warp.tests -s autodetect -p 'test_a*.py' python -m warp.tests -s kit python -m warp.tests -k 'mgpu' -k 'cuda' """, ) # parser.add_argument("-v", "--verbose", action="store_const", const=2, default=1, help="Verbose output") parser.add_argument("-q", "--quiet", dest="verbose", action="store_const", const=0, default=2, help="Quiet output") parser.add_argument("-f", "--failfast", action="store_true", default=False, help="Stop on first fail or error") parser.add_argument( "-b", "--buffer", action="store_true", default=False, help="Buffer stdout and stderr during tests" ) parser.add_argument( "-k", dest="testNamePatterns", action="append", type=_convert_select_pattern, help="Only run tests which match the given substring", ) parser.add_argument( "-p", "--pattern", metavar="PATTERN", default="test*.py", help="'autodetect' suite only: Pattern to match tests ('test*.py' default)", # NVIDIA Modification ) parser.add_argument( "-t", "--top-level-directory", metavar="TOP", help="Top level directory of project (defaults to start directory)", ) parser.add_argument( "--junit-report-xml", metavar="FILE", help="Generate JUnit report format XML file" ) # NVIDIA Modification parser.add_argument( "-s", "--suite", type=str, default="default", choices=["autodetect", "default", "kit"], help="Name of the test suite to run (default is 'default').", ) # NVIDIA Modification group_parallel = parser.add_argument_group("parallelization options") group_parallel.add_argument( "-j", "--jobs", metavar="COUNT", type=int, default=0, help="The number of test processes (default is 0, all cores)", ) group_parallel.add_argument( "-m", "--maxjobs", metavar="MAXCOUNT", type=int, default=8, help="The maximum number of test processes (default is 8)", ) # NVIDIA Modification group_parallel.add_argument( "--level", choices=["module", "class", "test"], default="class", help="Set the test parallelism level (default is 'class')", ) group_parallel.add_argument( "--disable-process-pooling", action="store_true", default=False, help="Do not reuse processes used to run test suites", ) group_parallel.add_argument( "--disable-concurrent-futures", action="store_true", default=False, help="Use multiprocessing instead of concurrent.futures.", ) # NVIDIA Modification group_parallel.add_argument( "--serial-fallback", action="store_true", default=False, help="Run in a single-process (no spawning) mode without multiprocessing or concurrent.futures.", ) # NVIDIA Modification group_coverage = parser.add_argument_group("coverage options") group_coverage.add_argument("--coverage", action="store_true", help="Run tests with coverage") group_coverage.add_argument("--coverage-branch", action="store_true", help="Run tests with branch coverage") group_coverage.add_argument( "--coverage-html", metavar="DIR", help="Generate coverage HTML report", default=os.path.join(START_DIRECTORY, "..", "..", "htmlcov"), ) group_coverage.add_argument("--coverage-xml", metavar="FILE", help="Generate coverage XML report") group_coverage.add_argument( "--coverage-fail-under", metavar="MIN", type=float, help="Fail if coverage percentage under min" ) group_warp = parser.add_argument_group("NVIDIA Warp options") # NVIDIA Modification group_warp.add_argument( "--no-shared-cache", action="store_true", help="Use a separate kernel cache per test process." ) args = parser.parse_args(args=argv) if args.coverage_branch: args.coverage = args.coverage_branch if args.coverage and not COVERAGE_AVAILABLE: parser.exit( status=2, message="--coverage was used, but coverage was not found. Is it installed?\n" ) # NVIDIA Modification process_count = max(0, args.jobs) if process_count == 0: process_count = multiprocessing.cpu_count() process_count = min(process_count, args.maxjobs) # NVIDIA Modification import warp as wp # NVIDIA Modification # Clear the Warp cache (NVIDIA Modification) wp.build.clear_kernel_cache() print("Cleared Warp kernel cache") # Create the temporary directory (for coverage files) with tempfile.TemporaryDirectory() as temp_dir: # Discover tests with _coverage(args, temp_dir): test_loader = unittest.TestLoader() if args.testNamePatterns: test_loader.testNamePatterns = args.testNamePatterns auto_discover_suite = warp.tests.unittest_suites.auto_discover_suite( test_loader, args.pattern ) # NVIDIA Modification # NVIDIA Modification if args.suite != "autodetect": # Print notices for test classes missing from the suite when compared to auto-discovered tests discover_suite = warp.tests.unittest_suites.compare_unittest_suites( test_loader, args.suite, auto_discover_suite ) else: discover_suite = auto_discover_suite # Get the parallelizable test suites if args.level == "test": test_suites = list(_iter_test_cases(discover_suite)) elif args.level == "class": test_suites = list(_iter_class_suites(discover_suite)) else: # args.level == 'module' test_suites = list(_iter_module_suites(discover_suite)) # Don't use more processes than test suites process_count = max(1, min(len(test_suites), process_count)) if not args.serial_fallback: # Report test suites and processes print( f"Running {len(test_suites)} test suites ({discover_suite.countTestCases()} total tests) across {process_count} processes", file=sys.stderr, ) if args.verbose > 1: print(file=sys.stderr) # Create the shared index object used in Warp caches (NVIDIA Modification) manager = multiprocessing.Manager() shared_index = manager.Value("i", -1) # Run the tests in parallel start_time = time.perf_counter() if args.disable_concurrent_futures: multiprocessing_context = multiprocessing.get_context(method="spawn") maxtasksperchild = 1 if args.disable_process_pooling else None with multiprocessing_context.Pool( process_count, maxtasksperchild=maxtasksperchild, initializer=initialize_test_process, initargs=(manager.Lock(), shared_index, args, temp_dir), ) as pool: test_manager = ParallelTestManager(manager, args, temp_dir) results = pool.map(test_manager.run_tests, test_suites) else: # NVIDIA Modification added concurrent.futures with concurrent.futures.ProcessPoolExecutor( max_workers=process_count, mp_context=multiprocessing.get_context(method="spawn"), initializer=initialize_test_process, initargs=(manager.Lock(), shared_index, args, temp_dir), ) as executor: test_manager = ParallelTestManager(manager, args, temp_dir) results = list(executor.map(test_manager.run_tests, test_suites, timeout=7200)) else: # This entire path is an NVIDIA Modification # Report test suites and processes print(f"Running {discover_suite.countTestCases()} total tests (serial fallback)", file=sys.stderr) if args.verbose > 1: print(file=sys.stderr) # Run the tests in serial start_time = time.perf_counter() with multiprocessing.Manager() as manager: test_manager = ParallelTestManager(manager, args, temp_dir) results = [test_manager.run_tests(discover_suite)] stop_time = time.perf_counter() test_duration = stop_time - start_time # Aggregate parallel test run results tests_run = 0 errors = [] failures = [] skipped = 0 expected_failures = 0 unexpected_successes = 0 test_records = [] # NVIDIA Modification for result in results: tests_run += result[0] errors.extend(result[1]) failures.extend(result[2]) skipped += result[3] expected_failures += result[4] unexpected_successes += result[5] test_records += result[6] # NVIDIA Modification is_success = not (errors or failures or unexpected_successes) # Compute test info infos = [] if failures: infos.append(f"failures={len(failures)}") if errors: infos.append(f"errors={len(errors)}") if skipped: infos.append(f"skipped={skipped}") if expected_failures: infos.append(f"expected failures={expected_failures}") if unexpected_successes: infos.append(f"unexpected successes={unexpected_successes}") # Report test errors if errors or failures: print(file=sys.stderr) for error in errors: print(error, file=sys.stderr) for failure in failures: print(failure, file=sys.stderr) elif args.verbose > 0: print(file=sys.stderr) # Test report print(unittest.TextTestResult.separator2, file=sys.stderr) print(f'Ran {tests_run} {"tests" if tests_run > 1 else "test"} in {test_duration:.3f}s', file=sys.stderr) print(file=sys.stderr) print(f'{"OK" if is_success else "FAILED"}{" (" + ", ".join(infos) + ")" if infos else ""}', file=sys.stderr) if test_records and args.junit_report_xml: # NVIDIA modification to report results in Junit XML format write_junit_results( args.junit_report_xml, test_records, tests_run, len(failures) + unexpected_successes, len(errors), skipped, test_duration, ) # Return an error status on failure if not is_success: parser.exit(status=len(errors) + len(failures) + unexpected_successes) # Coverage? if args.coverage: # Combine the coverage files cov_options = {} cov_options["config_file"] = True # Grab configuration from pyproject.toml (must install coverage[toml]) cov = coverage.Coverage(**cov_options) cov.combine(data_paths=[os.path.join(temp_dir, x) for x in os.listdir(temp_dir)]) # Coverage report print(file=sys.stderr) percent_covered = cov.report(ignore_errors=True, file=sys.stderr) print(f"Total coverage is {percent_covered:.2f}%", file=sys.stderr) # HTML coverage report if args.coverage_html: cov.html_report(directory=args.coverage_html, ignore_errors=True) # XML coverage report if args.coverage_xml: cov.xml_report(outfile=args.coverage_xml, ignore_errors=True) # Fail under if args.coverage_fail_under and percent_covered < args.coverage_fail_under: parser.exit(status=2) def _convert_select_pattern(pattern): if "*" not in pattern: return f"*{pattern}*" return pattern @contextmanager def _coverage(args, temp_dir): # Running tests with coverage? if args.coverage: # Generate a random coverage data file name - file is deleted along with containing directory with tempfile.NamedTemporaryFile(dir=temp_dir, delete=False) as coverage_file: pass # Create the coverage object cov_options = { "branch": args.coverage_branch, "data_file": coverage_file.name, # NVIDIA Modification removed unneeded options } cov_options["config_file"] = True # Grab configuration from pyproject.toml (must install coverage[toml]) cov = coverage.Coverage(**cov_options) try: # Start measuring code coverage cov.start() # Yield for unit test running yield cov finally: # Stop measuring code coverage cov.stop() # Save the collected coverage data to the data file cov.save() else: # Not running tests with coverage - yield for unit test running yield None # Iterate module-level test suites - all top-level test suites returned from TestLoader.discover def _iter_module_suites(test_suite): for module_suite in test_suite: if module_suite.countTestCases(): yield module_suite # Iterate class-level test suites - test suites that contains test cases def _iter_class_suites(test_suite): has_cases = any(isinstance(suite, unittest.TestCase) for suite in test_suite) if has_cases: yield test_suite else: for suite in test_suite: yield from _iter_class_suites(suite) # Iterate test cases (methods) def _iter_test_cases(test_suite): if isinstance(test_suite, unittest.TestCase): yield test_suite else: for suite in test_suite: yield from _iter_test_cases(suite) class ParallelTestManager: def __init__(self, manager, args, temp_dir): self.args = args self.temp_dir = temp_dir self.failfast = manager.Event() def run_tests(self, test_suite): # Fail fast? if self.failfast.is_set(): return [0, [], [], 0, 0, 0, []] # NVIDIA Modification # NVIDIA Modification for GitLab import warp.tests.unittest_utils warp.tests.unittest_utils.coverage_enabled = self.args.coverage warp.tests.unittest_utils.coverage_temp_dir = self.temp_dir warp.tests.unittest_utils.coverage_branch = self.args.coverage_branch if self.args.junit_report_xml: resultclass = ParallelJunitTestResult else: resultclass = ParallelTextTestResult # Run unit tests with _coverage(self.args, self.temp_dir): runner = unittest.TextTestRunner( stream=StringIO(), resultclass=resultclass, # NVIDIA Modification verbosity=self.args.verbose, failfast=self.args.failfast, buffer=self.args.buffer, ) result = runner.run(test_suite) # Set failfast, if necessary if result.shouldStop: self.failfast.set() # Return (test_count, errors, failures, skipped_count, expected_failure_count, unexpected_success_count) return ( result.testsRun, [self._format_error(result, error) for error in result.errors], [self._format_error(result, failure) for failure in result.failures], len(result.skipped), len(result.expectedFailures), len(result.unexpectedSuccesses), result.test_record, # NVIDIA modification ) @staticmethod def _format_error(result, error): return "\n".join( [ unittest.TextTestResult.separator1, result.getDescription(error[0]), unittest.TextTestResult.separator2, error[1], ] ) class ParallelTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): stream = type(stream)(sys.stderr) super().__init__(stream, descriptions, verbosity) self.test_record = [] # NVIDIA modification def startTest(self, test): if self.showAll: self.stream.writeln(f"{self.getDescription(test)} ...") self.stream.flush() super(unittest.TextTestResult, self).startTest(test) def _add_helper(self, test, dots_message, show_all_message): if self.showAll: self.stream.writeln(f"{self.getDescription(test)} ... {show_all_message}") elif self.dots: self.stream.write(dots_message) self.stream.flush() def addSuccess(self, test): super(unittest.TextTestResult, self).addSuccess(test) self._add_helper(test, ".", "ok") def addError(self, test, err): super(unittest.TextTestResult, self).addError(test, err) self._add_helper(test, "E", "ERROR") def addFailure(self, test, err): super(unittest.TextTestResult, self).addFailure(test, err) self._add_helper(test, "F", "FAIL") def addSkip(self, test, reason): super(unittest.TextTestResult, self).addSkip(test, reason) self._add_helper(test, "s", f"skipped {reason!r}") def addExpectedFailure(self, test, err): super(unittest.TextTestResult, self).addExpectedFailure(test, err) self._add_helper(test, "x", "expected failure") def addUnexpectedSuccess(self, test): super(unittest.TextTestResult, self).addUnexpectedSuccess(test) self._add_helper(test, "u", "unexpected success") def printErrors(self): pass def initialize_test_process(lock, shared_index, args, temp_dir): """Necessary operations to be executed at the start of every test process. Currently this function can be used to set a separate Warp cache. (NVIDIA modification) If the environment variable `WARP_CACHE_ROOT` is detected, the cache will be placed in the provided path. It also ensures that Warp is initialized prior to running any tests. """ with lock: shared_index.value += 1 worker_index = shared_index.value with _coverage(args, temp_dir): import warp as wp if args.no_shared_cache: from warp.thirdparty import appdirs if "WARP_CACHE_ROOT" in os.environ: cache_root_dir = os.path.join(os.getenv("WARP_CACHE_ROOT"), f"{wp.config.version}-{worker_index:03d}") else: cache_root_dir = appdirs.user_cache_dir( appname="warp", appauthor="NVIDIA", version=f"{wp.config.version}-{worker_index:03d}" ) wp.config.kernel_cache_dir = cache_root_dir wp.build.clear_kernel_cache() else: # Initialize Warp is if hasn't been initialized already wp.init() if __name__ == "__main__": # pragma: no cover main()
20,998
Python
36.232269
139
0.611439
NVIDIA/warp/docs/faq.rst
FAQ === How does Warp relate to other Python projects for GPU programming, e.g.: Numba, Taichi, cuPy, PyTorch, etc.? ------------------------------------------------------------------------------------------------------------ Warp is inspired by many of these projects, and is closely related to Numba and Taichi which both expose kernel programming to Python. These frameworks map to traditional GPU programming models, so many of the high-level concepts are similar, however there are some functionality and implementation differences. Compared to Numba, Warp supports a smaller subset of Python, but offering auto-differentiation of kernel programs, which is useful for machine learning. Compared to Taichi Warp uses C++/CUDA as an intermediate representation, which makes it convenient to implement and expose low-level routines. In addition, we are building in data structures to support geometry processing (meshes, sparse volumes, point clouds, USD data) as first-class citizens that are not exposed in other runtimes. Warp does not offer a full tensor-based programming model like PyTorch and JAX, but is designed to work well with these frameworks through data sharing mechanisms like ``__cuda_array_interface__``. For computations that map well to tensors (e.g.: neural-network inference) it makes sense to use these existing tools. For problems with a lot of e.g.: sparsity, conditional logic, heterogeneous workloads (like the ones we often find in simulation and graphics), then the kernel-based programming model like the one in Warp are often more convenient since users have control over individual threads. Does Warp support all of the Python language? --------------------------------------------- No, Warp supports a subset of Python that maps well to the GPU. Our goal is to not have any performance cliffs so that users can expect consistently good behavior from kernels that is close to native code. Examples of unsupported concepts that don’t map well to the GPU are dynamic types, list comprehensions, exceptions, garbage collection, etc. When should I call ``wp.synchronize()``? ---------------------------------------- One of the common sources of confusion for new users is when calls to ``wp.synchronize()`` are necessary. The answer is “almost never”! Synchronization is quite expensive, and should generally be avoided unless necessary. Warp naturally takes care of synchronization between operations (e.g.: kernel launches, device memory copies). For example, the following requires no manual synchronization, as the conversion to NumPy will automatically synchronize: .. code:: python # run some kernels wp.launch(kernel_1, dim, [array_x, array_y], device="cuda") wp.launch(kernel_2, dim, [array_y, array_z], device="cuda") # bring data back to host (and implicitly synchronize) x = array_z.numpy() The *only* case where manual synchronization is needed is when copies are being performed back to CPU asynchronously, e.g.: .. code:: python # copy data back to cpu from gpu, all copies will happen asynchronously to Python wp.copy(cpu_array_1, gpu_array_1) wp.copy(cpu_array_2, gpu_array_2) wp.copy(cpu_array_3, gpu_array_3) # ensure that the copies have finished wp.synchronize() # return a numpy wrapper around the cpu arrays, note there is no implicit synchronization here a1 = cpu_array_1.numpy() a2 = cpu_array_2.numpy() a3 = cpu_array_3.numpy() For more information about asynchronous operations, please refer to the :doc:`concurrency documentation <modules/concurrency>` and :ref:`synchronization guidance <synchronization_guidance>`. What happens when you differentiate a function like ``wp.abs(x)``? ------------------------------------------------------------------ Non-smooth functions such as ``y=|x|`` do not have a single unique gradient at ``x=0``, rather they have what is known as a ``subgradient``, which is formally the convex hull of directional derivatives at that point. The way that Warp (and most auto-differentiation frameworks) handles these points is to pick an arbitrary gradient from this set, e.g.: for ``wp.abs()``, it will arbitrarily choose the gradient to be 1.0 at the origin. You can find the implementation for these functions in ``warp/native/builtin.h``. Most optimizers (particularly ones that exploit stochasticity), are not sensitive to the choice of which gradient to use from the subgradient, although there are exceptions. Does Warp support multi-GPU programming? ---------------------------------------- Yes! Since version ``0.4.0`` we support allocating, launching, and copying between multiple GPUs in a single process. We follow the naming conventions of PyTorch and use aliases such as ``cuda:0``, ``cuda:1``, ``cpu`` to identify individual devices. Should I switch to Warp over IsaacGym/PhysX? ---------------------------------------------- Warp is not a replacement for IsaacGym, IsaacSim, or PhysX - while Warp does offer some physical simulation capabilities this is primarily aimed at developers who need differentiable physics, rather than a fully featured physics engine. Warp is also integrated with IsaacGym and is great for performing auxiliary tasks such as reward and observation computations for reinforcement learning. Why aren't assignments to Warp arrays aren'supported outside of kernels? ------------------------------------------------------------------------ For best performance, reading and writing data that is living on the GPU can only be performed inside Warp CUDA kernels. Otherwise individual element accesses such as ``array[i] = 1.0`` in Python scope would require prohibitively slow device synchronization and copies. We recommend to either initialize Warp arrays from other native arrays (e.g.: Python list, NumPy array, ...) or by launching a kernel to set its values. For the common use case of wanting to fill an array with a given value, we also support the following forms: - ``wp.full(8, 1.23, dtype=float)``: initializes a new array of 8 float values set to ``1.23``. - ``arr.fill_(1.23)``: sets the content of an existing float array to ``1.23``. - ``arr[:4].fill(1.23)``: sets the four first values of an existing float array to ``1.23``.
6,254
reStructuredText
45.333333
126
0.7181
NVIDIA/warp/docs/installation.rst
Installation ============ Python version 3.9 or newer is recommended. Warp can run on x86-64 and ARMv8 CPUs on Windows, Linux, and macOS. GPU support requires a CUDA-capable NVIDIA GPU and driver (minimum GeForce GTX 9xx). The easiest way to install Warp is from `PyPI <https://pypi.org/project/warp-lang>`_: .. code-block:: sh $ pip install warp-lang Pre-built binary packages are also available on the `Releases <https://github.com/NVIDIA/warp/releases>`_ page. To install in your local Python environment extract the archive and run the following command from the root directory: .. code-block:: sh $ pip install . Dependencies ------------ Warp supports Python versions 3.7 onwards, with 3.9 or newer recommended for full functionality. Note that :ref:`some optional dependencies may not support the latest version of Python<conda>`. `NumPy <https://numpy.org>`_ must be installed. The following optional dependencies are required to support certain features: * `usd-core <https://pypi.org/project/usd-core>`_: Required for some Warp examples, ``warp.sim.parse_usd()``, and ``warp.render.UsdRenderer``. * `JAX <https://jax.readthedocs.io/en/latest/installation.html>`_: Required for JAX interoperability (see :ref:`jax-interop`). * `PyTorch <https://pytorch.org/get-started/locally/>`_: Required for PyTorch interoperability (see :ref:`pytorch-interop`). * `NVTX for Python <https://github.com/NVIDIA/NVTX#python>`_: Required to use :class:`wp.ScopedTimer(use_nvtx=True) <warp.ScopedTimer>`. Building the Warp documentation requires: * `Sphinx <https://www.sphinx-doc.org>`_ * `Furo <https://github.com/pradyunsg/furo>`_ * `Sphinx-copybutton <https://sphinx-copybutton.readthedocs.io/en/latest/index.html>`_ Building from source -------------------- For developers who want to build the library themselves the following tools are required: * Microsoft Visual Studio (Windows), minimum version 2019 * GCC (Linux), minimum version 9.4 * `CUDA Toolkit <https://developer.nvidia.com/cuda-toolkit>`_, minimum version 11.5 * `Git Large File Storage <https://git-lfs.com>`_ After cloning the repository, users should run: .. code-block:: console $ python build_lib.py This will generate the ``warp.dll`` / ``warp.so`` core library respectively. It will search for the CUDA Toolkit in the default install directory. This path can be overridden by setting the ``CUDA_PATH`` environment variable. Alternatively, the path to the CUDA Toolkit can be passed to the build command as ``--cuda_path="..."``. After building, the Warp package should be installed using: .. code-block:: console $ pip install -e . Which ensures that subsequent modifications to the library will be reflected in the Python package. .. _conda: Conda environments ------------------ Some modules, such as ``usd-core``, don't support the latest Python version. To manage running Warp and other projects on different Python versions one can make use of an environment management system such as `Conda <https://docs.conda.io/>`__. **WARNING:** When building and running Warp in a different environment, make sure the build environment has the same C++ runtime library version, or an older one, than the execution environment. Otherwise Warp's shared libraries may end up looking for a newer runtime library version than the one available in the execution environment. For example on Linux this error could occur: ``OSError: <...>/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by <...>/warp/warp/bin/warp.so)`` This can be solved by installing a newer C++ runtime version in the runtime conda environment using ``conda install -c conda-forge libstdcxx-ng=12.1`` or newer. Or, the build environment's C++ toolchain can be downgraded using ``conda install -c conda-forge libstdcxx-ng=8.5``. Or, one can ``activate`` or ``deactivate`` conda environments as needed for building vs. running Warp.
3,915
reStructuredText
41.565217
196
0.739208
NVIDIA/warp/docs/basics.rst
Basics ====== .. currentmodule:: warp Initialization -------------- When calling a Warp function like `wp.launch()` for the first time, Warp will initialize itself and, as a result, will print some startup information about the compute devices available, driver versions, and the location for any generated kernel code, e.g.: .. code:: bat Warp 1.0.0 initialized: CUDA Toolkit: 11.8, Driver: 12.1 Devices: "cpu" | AMD64 Family 25 Model 33 Stepping 0, AuthenticAMD "cuda:0" | NVIDIA GeForce RTX 4080 (sm_89) Kernel cache: C:\Users\mmacklin\AppData\Local\NVIDIA\warp\Cache\1.0.0 It's also possible to explicitly initialize Warp with the ``wp.init()`` method as such:: import warp as wp wp.init() Kernels ------- In Warp, compute kernels are defined as Python functions and annotated with the ``@wp.kernel`` decorator, as follows:: @wp.kernel def simple_kernel(a: wp.array(dtype=wp.vec3), b: wp.array(dtype=wp.vec3), c: wp.array(dtype=float)): # get thread index tid = wp.tid() # load two vec3s x = a[tid] y = b[tid] # compute the dot product between vectors r = wp.dot(x, y) # write result back to memory c[tid] = r Because Warp kernels are compiled to native C++/CUDA code, all the function input arguments must be statically typed. This allows Warp to generate fast code that executes at essentially native speeds. Because kernels may be run on either the CPU or GPU, they cannot access arbitrary global state from the Python environment. Instead they must read and write data through their input parameters such as arrays. Warp kernels functions have a one-to-one correspondence with CUDA kernels. To launch a kernel with 1024 threads, we use :func:`wp.launch() <warp.launch>` as follows:: wp.launch(kernel=simple_kernel, # kernel to launch dim=1024, # number of threads inputs=[a, b, c], # parameters device="cuda") # execution device Inside the kernel, we retrieve the *thread index* of the each thread using the :func:`wp.tid() <tid>` built-in function:: # get thread index i = wp.tid() Kernels can be launched with 1D, 2D, 3D, or 4D grids of threads. To launch a 2D grid of threads to process a 1024x1024 image, we could write:: wp.launch(kernel=compute_image, dim=(1024, 1024), inputs=[img], device="cuda") We retrieve a 2D thread index inside the kernel as follows: .. code-block:: python @wp.kernel def compute_image(pixel_data: wp.array2d(dtype=wp.vec3)): # get thread index i, j = wp.tid() Arrays ------ Memory allocations are exposed via the ``wp.array`` type. Arrays wrap an underlying memory allocation that may live in either host (CPU), or device (GPU) memory. Arrays are strongly typed and store a linear sequence of built-in values (``float``, ``int``, ``vec3``, ``matrix33``, etc). Arrays can be allocated similar to PyTorch:: # allocate an uninitialized array of vec3s v = wp.empty(shape=n, dtype=wp.vec3, device="cuda") # allocate a zero-initialized array of quaternions q = wp.zeros(shape=n, dtype=wp.quat, device="cuda") # allocate and initialize an array from a NumPy array # will be automatically transferred to the specified device a = np.ones((10, 3), dtype=np.float32) v = wp.from_numpy(a, dtype=wp.vec3, device="cuda") By default, Warp arrays that are initialized from external data (e.g.: NumPy, Lists, Tuples) will create a copy the data to new memory for the device specified. However, it is possible for arrays to alias external memory using the ``copy=False`` parameter to the array constructor provided the input is contiguous and on the same device. See the :doc:`/modules/interoperability` section for more details on sharing memory with external frameworks. To read GPU array data back to CPU memory we can use :func:`array.numpy`:: # bring data from device back to host view = device_array.numpy() This will automatically synchronize with the GPU to ensure that any outstanding work has finished, and will copy the array back to CPU memory where it is passed to NumPy. Calling :func:`array.numpy` on a CPU array will return a zero-copy NumPy view onto the Warp data. Please see the :ref:`Arrays Reference <Arrays>` for more details. User Functions -------------- Users can write their own functions using the ``@wp.func`` decorator, for example:: @wp.func def square(x: float): return x*x Kernels can call user functions defined in the same module or defined in a different module. As the example shows, return type hints for user functions are **optional**. Anything that can be done in a Warp kernel can also be done in a user function **with the exception** of :func:`wp.tid() <tid>`. The thread index can be passed in through the arguments of a user function if it is required. Functions can accept arrays and structs as inputs: .. code-block:: python @wp.func def lookup(foos: wp.array(dtype=wp.uint32), index: int): return foos[index] Functions may also return multiple values: .. code-block:: python @wp.func def multi_valued_func(a: wp.float32, b: wp.float32): return a + b, a - b, a * b, a / b @wp.kernel def test_multi_valued_kernel(test_data1: wp.array(dtype=wp.float32), test_data2: wp.array(dtype=wp.float32)): tid = wp.tid() d1, d2 = test_data1[tid], test_data2[tid] a, b, c, d = multi_valued_func(d1, d2) User functions may also be overloaded by defining multiple function signatures with the same function name: .. code-block:: python @wp.func def custom(x: int): return x + 1 @wp.func def custom(x: float): return x + 1.0 @wp.func def custom(x: wp.vec3): return x + wp.vec3(1.0, 0.0, 0.0) See :ref:`Generic Functions` for details on using ``typing.Any`` in user function signatures. See :doc:`modules/differentiability` for details on how to define custom gradient functions, custom replay functions, and custom native functions. User Structs -------------- Users can define their own structures using the ``@wp.struct`` decorator, for example:: @wp.struct class MyStruct: pos: wp.vec3 vel: wp.vec3 active: int indices: wp.array(dtype=int) Structs may be used as a ``dtype`` for ``wp.arrays``, and may be passed to kernels directly as arguments, please see :ref:`Structs Reference <Structs>` for more details. .. note:: As with kernel parameters, all attributes of a struct must have valid type hints at class definition time. Compilation Model ----------------- Warp uses a Python->C++/CUDA compilation model that generates kernel code from Python function definitions. All kernels belonging to a Python module are runtime compiled into dynamic libraries and PTX. The result is then cached between application restarts for fast startup times. Note that compilation is triggered on the first kernel launch for that module. Any kernels registered in the module with ``@wp.kernel`` will be included in the shared library. .. image:: ./img/compiler_pipeline.svg Language Details ---------------- To support GPU computation and differentiability, there are some differences from the CPython runtime. Built-in Types ^^^^^^^^^^^^^^ Warp supports a number of built-in math types similar to high-level shading languages, e.g. ``vec2, vec3, vec4, mat22, mat33, mat44, quat, array``. All built-in types have value semantics so that expressions such as ``a = b`` generate a copy of the variable ``b`` rather than a reference. Strong Typing ^^^^^^^^^^^^^ Unlike Python, in Warp all variables must be typed. Types are inferred from source expressions and function signatures using the Python typing extensions. All kernel parameters must be annotated with the appropriate type, for example:: @wp.kernel def simple_kernel(a: wp.array(dtype=vec3), b: wp.array(dtype=vec3), c: float): Tuple initialization is not supported, instead variables should be explicitly typed:: # invalid a = (1.0, 2.0, 3.0) # valid a = wp.vec3(1.0, 2.0, 3.0) Limitations and Unsupported Features ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See :doc:`limitations` for a list of Warp limitations and unsupported features.
8,483
reStructuredText
32.011673
142
0.685489
NVIDIA/warp/docs/limitations.rst
Limitations =========== .. currentmodule:: warp This section summarizes various limitations and currently unsupported features in Warp. Problems, questions, and feature requests can be opened on `GitHub Issues <https://github.com/NVIDIA/warp/issues>`_. Unsupported Features -------------------- To achieve good performance on GPUs some dynamic language features are not supported: * Lambda functions * List comprehensions * Exceptions * Recursion * Runtime evaluation of expressions, e.g.: eval() * Dynamic structures such as lists, sets, dictionaries, etc. Kernels and User Functions -------------------------- * Strings cannot be passed into kernels. * Short-circuit evaluation is not supported * :func:`wp.atomic_add() <atomic_add>` does not support ``wp.int64``. * :func:`wp.tid() <tid>` cannot be called from user functions. * Modifying the value of a :class:`wp.constant() <constant>` during runtime will not trigger recompilation of the affected kernels if the modules have already been loaded (e.g. through a :func:`wp.launch() <launch>` or a ``wp.load_module()``). * A :class:`wp.constant() <constant>` can suffer precision loss if used with ``wp.float64`` as it is initially assigned to a ``wp.float32`` variable in the generated code. A limitation of Warp is that each dimension of the grid used to launch a kernel must be representable as a 32-bit signed integer. Therefore, no single dimension of a grid should exceed :math:`2^{31}-1`. Warp also currently uses a fixed block size of 256 (CUDA) threads per block. By default, Warp will try to process one element from the Warp grid in one CUDA thread. This is not always possible for kernels launched with multi-dimensional grid bounds, as there are `hardware limitations <https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications-technical-specifications-per-compute-capability>`_ on CUDA block dimensions. Warp will automatically fallback to using `grid-stride loops <https://developer.nvidia.com/blog/cuda-pro-tip-write-flexible-kernels-grid-stride-loops/>`_ when it is not possible for a CUDA thread to process only one element from the Warp grid When this happens, some CUDA threads may process more than one element from the Warp grid. Users can also set the ``max_blocks`` parameter to fine-tune the grid-striding behavior of kernels, even for kernels that are otherwise able to process one Warp-grid element per CUDA thread. Arrays ------ * Arrays can have a maximum of four dimensions. * Each dimension of a Warp array cannot be greater than the maximum value representable by a 32-bit signed integer, :math:`2^{31}-1`. * There are currently no data types that support complex numbers. Structs ------- * Structs cannot have generic members, i.e. of type ``typing.Any``. Volumes ------- * The sparse-volume *topology* cannot be changed after the tiles for the :class:`Volume` have been allocated. Multiple Processes ------------------ * A CUDA context created in the parent process cannot be used in a *forked* child process. Use the spawn start method instead, or avoid creating CUDA contexts in the parent process. * There can be issues with using same user kernel cache directory when running with multiple processes. A workaround is to use a separate cache directory for every process. See the :ref:`Configuration` section for how the cache directory may be changed. Scalar Math Functions --------------------- This section details some limitations and differences from CPython semantics for scalar math functions. Modulus Operator """""""""""""""" Deviation from Python behavior can occur when the modulus operator (``%``) is used with a negative dividend or divisor (also see :func:`wp.mod() <mod>`). The behavior of the modulus operator in a Warp kernel follows that of C++11: The sign of the result follows the sign of *dividend*. In Python, the sign of the result follows the sign of the *divisor*: .. code-block:: python @wp.kernel def modulus_test(): # Kernel-scope behavior: a = -3 % 2 # a is -1 b = 3 % -2 # b is 1 c = 3 % 0 # Undefined behavior # Python-scope behavior: a = -3 % 2 # a is 1 b = 3 % -2 # b is -1 c = 3 % 0 # ZeroDivisionError Power Operator """""""""""""" The power operator (``**``) in Warp kernels only works on floating-point numbers (also see :func:`wp.pow <pow>`). In Python, the power operator can also be used on integers. Inverse Sine and Cosine """"""""""""""""""""""" :func:`wp.asin() <asin>` and :func:`wp.acos() <acos>` automatically clamp the input to fall in the range [-1, 1]. In Python, using :external+python:py:func:`math.asin` or :external+python:py:func:`math.acos` with an input outside [-1, 1] raises a ``ValueError`` exception. Rounding """""""" :func:`wp.round() <round>` rounds halfway cases away from zero, but Python's :external+python:py:func:`round` rounds halfway cases to the nearest even choice (Banker's rounding). Use :func:`wp.rint() <rint>` when Banker's rounding is desired. Unlike Python, the return type in Warp of both of these rounding functions is the same type as the input: .. code-block:: python @wp.kernel def halfway_rounding_test(): # Kernel-scope behavior: a = wp.round(0.5) # a is 1.0 b = wp.rint(0.5) # b is 0.0 c = wp.round(1.5) # c is 2.0 d = wp.rint(1.5) # d is 2.0 # Python-scope behavior: a = round(0.5) # a is 0 c = round(1.5) # c is 2
5,507
reStructuredText
38.625899
176
0.706374
NVIDIA/warp/docs/profiling.rst
Profiling ========= ScopedTimer ----------- ``wp.ScopedTimer`` objects can be used to gain some basic insight into the performance of Warp applications: .. code:: python @wp.kernel def inc_loop(a: wp.array(dtype=float), num_iters: int): i = wp.tid() for j in range(num_iters): a[i] += 1.0 n = 10_000_000 devices = wp.get_cuda_devices() # pre-allocate host arrays for readback host_arrays = [ wp.empty(n, dtype=float, device="cpu", pinned=True) for _ in devices ] # code for profiling with wp.ScopedTimer("Demo"): for i, device in enumerate(devices): a = wp.zeros(n, dtype=float, device=device) wp.launch(inc_loop, dim=n, inputs=[a, 500], device=device) wp.launch(inc_loop, dim=n, inputs=[a, 1000], device=device) wp.launch(inc_loop, dim=n, inputs=[a, 1500], device=device) wp.copy(host_arrays[i], a) The only required argument for the ``ScopedTimer`` constructor is a string label, which can be used to distinguish multiple timed code sections when reading the output. The snippet above will print a message like this: .. code:: console Demo took 0.52 ms By default, ``ScopedTimer`` measures the elapsed time on the CPU and does not introduce any CUDA synchronization. Since most CUDA operations are asynchronous, the result does not include the time spent executing kernels and memory transfers on the CUDA device. It's still a useful measurement, because it shows how long it took to schedule the CUDA operations on the CPU. To get the total amount of time including the device executions time, create the ``ScopedTimer`` with the ``synchronize=True`` flag. This is equivalent to calling ``wp.synchronize()`` before and after the timed section of code. Synchronizing at the beginning ensures that all prior CUDA work has completed prior to starting the timer. Synchronizing at the end ensures that all timed work finishes before stopping the timer. With the example above, the result might look like this: .. code:: console Demo took 4.91 ms The timing values will vary slightly from run to run and will depend on the system hardware and current load. The sample results presented here were obtained on a system with one RTX 4090 GPU, one RTX 3090 GPU, and an AMD Ryzen Threadripper Pro 5965WX CPU. For each GPU, the code allocates and initializes an array with 10 million floating point elements. It then launches the ``inc_loop`` kernel three times on the array. The kernel increments each array element a given number of times - 500, 1000, and 1500. Finally, the code copies the array contents to the CPU. Profiling complex programs with many asynchronous and concurrent operations can be tricky. Profiling tools like `NVIDIA Nsight Systems <https://developer.nvidia.com/nsight-systems>`_ can present the results in a visual way and capture a plethora of timing information for deeper study. For profiling tools capable of visualizing NVTX ranges, ``ScopedTimer`` can be created with the ``use_nvtx=True`` argument. This will mark the CPU execution range on the timeline for easier visual inspection. The color can be customized using the ``color`` argument, as shown below: .. code:: python with wp.ScopedTimer("Demo", use_nvtx=True, color="yellow"): ... To use NVTX integration, you will need to install the `NVIDIA NVTX Python package <https://github.com/NVIDIA/NVTX/tree/release-v3/python>`_. .. code:: pip install nvtx The package allows you to insert custom NVTX ranges into your code (``nvtx.annotate``) and customize the `colors <https://github.com/NVIDIA/NVTX/blob/release-v3/python/nvtx/colors.py>`_. Here is what the demo code looks like in Nsight Systems (click to enlarge the image): .. image:: ./img/profiling_nosync.png :width: 95% :align: center There are a few noteworthy observations we can make from this capture. Scheduling and launching the work on the CPU takes about half a millisecond, as shown in the `NVTX / Start & End` row. This time also includes the allocation of arrays on both CUDA devices. We can see that the execution on each device is asynchronous with respect to the host, since CUDA operations start running before the yellow `Demo` NVTX range finishes. We can also see that the operations on different CUDA devices execute concurrently, including kernels and memory transfers. The kernels run faster on the first CUDA device (RTX 4090) than the second device (RTX 3090). Memory transfers take about the same time on each device. Using pinned CPU arrays for the transfer destinations allows the transfers to run asynchronously without involving the CPU. Check out the :doc:`concurrency documentation <modules/concurrency>` for more information about asynchronous operations. Note that synchronization was not enabled in this run, so the NVTX range only spans the CPU operations used to schedule the CUDA work. When synchronization is enabled, the timer will wait for all CUDA work to complete, so the NVTX range will span the synchronization of both devices: .. code:: python with wp.ScopedTimer("Demo", use_nvtx=True, color="yellow", synchronize=True): ... .. image:: ./img/profiling_sync.png :width: 95% :align: center CUDA Activity Profiling ----------------------- ``ScopedTimer`` supports timing individual CUDA activities like kernels and memory operations. This is done by measuring the time taken between :ref:`CUDA events <cuda_events>` on the device. To get information about CUDA activities, pass the ``cuda_filter`` argument to the ``ScopedTimer`` constructor. The ``cuda_filter`` can be a bitwise combination of the following values: .. list-table:: CUDA profiling flags :widths: 25 50 :header-rows: 0 * - ``wp.TIMING_KERNELS`` - Warp kernels (this includes all kernels written in Python as ``@wp.kernel``) * - ``wp.TIMING_KERNELS_BUILTIN`` - Builtin kernels (this includes kernels used by the Warp library under the hood) * - ``wp.TIMING_MEMCPY`` - CUDA memory transfers (host-to-device, device-to-host, device-to-device, and peer-to-peer) * - ``wp.TIMING_MEMSET`` - CUDA memset operations (e.g., zeroing out memory in ``wp.zeros()``) * - ``wp.TIMING_GRAPH`` - CUDA graph launches * - ``wp.TIMING_ALL`` - Combines all of the above for convenience. When a non-zero ``cuda_filter`` is specified, Warp will inject CUDA events for timing purposes and report the results when the ``ScopeTimer`` finishes. This adds some overhead to the code, so should be used only during profiling. CUDA event timing resolution is about 0.5 microseconds. The reported execution time of short operations will likely be longer than the operations actually took on the device. This is due to the timing resolution and the overhead of added instrumentation code. For more precise analysis of short operations, a tool like Nsight Systems can report more accurate data. Enabling CUDA profiling with the demo code can be done like this: .. code:: python with wp.ScopedTimer("Demo", cuda_filter=wp.TIMING_ALL): ... This adds additional information to the output: .. code:: CUDA timeline: ----------------+---------+------------------------ Time | Device | Activity ----------------+---------+------------------------ 0.021504 ms | cuda:0 | memset 0.163840 ms | cuda:0 | forward kernel inc_loop 0.306176 ms | cuda:0 | forward kernel inc_loop 0.451584 ms | cuda:0 | forward kernel inc_loop 2.455520 ms | cuda:0 | memcpy DtoH 0.051200 ms | cuda:1 | memset 0.374784 ms | cuda:1 | forward kernel inc_loop 0.707584 ms | cuda:1 | forward kernel inc_loop 1.042432 ms | cuda:1 | forward kernel inc_loop 2.136096 ms | cuda:1 | memcpy DtoH CUDA activity summary: ----------------+---------+------------------------ Total time | Count | Activity ----------------+---------+------------------------ 0.072704 ms | 2 | memset 3.046400 ms | 6 | forward kernel inc_loop 4.591616 ms | 2 | memcpy DtoH CUDA device summary: ----------------+---------+------------------------ Total time | Count | Device ----------------+---------+------------------------ 3.398624 ms | 5 | cuda:0 4.312096 ms | 5 | cuda:1 Demo took 0.92 ms The first section is the `CUDA timeline`, which lists all captured activities in issue order. We see a `memset` on device ``cuda:0``, which corresponds to clearing the memory in ``wp.zeros()``. This is followed by three launches of the ``inc_loop`` kernel on ``cuda:0`` and a memory transfer from device to host issued by ``wp.copy()``. The remaining entries repeat similar operations on device ``cuda:1``. The next section is the `CUDA activity summary`, which reports the cumulative time taken by each activity type. Here, the `memsets`, kernel launches, and memory transfer operations are grouped together. This is a good way to see where time is being spent overall. The `memsets` are quite fast. The ``inc_loop`` kernel launches took about three milliseconds of combined GPU time. The memory transfers took the longest, over four milliseconds. The `CUDA device summary` shows the total time taken per device. We see that device ``cuda:0`` took about 3.4 ms to complete the tasks and device ``cuda:1`` took about 4.3 ms. This summary can be used to asses the workload distribution in multi-GPU applications. The final line shows the time taken by the CPU, as with the default ``ScopedTimer`` options (without synchronization in this case). Customizing the output ~~~~~~~~~~~~~~~~~~~~~~ It is possible to customize how the activity timing results are reported. The function :func:`warp.timing_print` is used by default. To use a different reporting function, pass it as the ``report_func`` argument to ``ScopedTimer``. The custom report function should take a list of :class:`warp.TimingResult` objects as the first argument. Each result in the list corresponds to a single activity and the list represents the complete recorded timeline. By manually traversing the list, you can customize the formatting of the output, apply custom sorting rules, and aggregate the results as desired. The second argument is a string indent that should be printed at the beginning of each line. This is for compatibility with ``ScopedTimer`` indenting rules used with nested timers. Here is an example of a custom reporting function, which aggregates the total time spend in forward and backward kernels: .. code:: python def print_custom_report(results, indent=""): forward_time = 0 backward_time = 0 for r in results: # aggregate all forward kernels if r.name.startswith("forward kernel"): forward_time += r.elapsed # aggregate all backward kernels elif r.name.startswith("backward kernel"): backward_time += r.elapsed print(f"{indent}Forward kernels : {forward_time:.6f} ms") print(f"{indent}Backward kernels : {backward_time:.6f} ms") Let's apply it to one of the Warp examples: .. code:: python from warp.examples.optim.example_cloth_throw import Example example = Example(None) example.use_graph = False # disable graphs so we get timings for individual kernels with wp.ScopedTimer("Example", cuda_filter=wp.TIMING_KERNEL, report_func=print_custom_report): for iteration in range(5): example.step() This produces a report like this: .. code:: Forward kernels : 187.098367 ms Backward kernels : 245.070177 ms Using the activity timing functions directly ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is also possible to capture activity timings without using the ``ScopedTimer`` at all. Simply call :func:`warp.timing_begin` to start recording activity timings and :func:`warp.timing_end` to stop and get a list of recorded activities. You can use :func:`warp.timing_print` to print the default activity report or generate your own report from the list of results. .. code:: python wp.timing_begin(cuda_filter=wp.TIMING_ALL) ... results = wp.timing_end() wp.timing_print(results) Limitations ~~~~~~~~~~~ Currently, detailed activity timing is only available for CUDA devices, but support for CPU timing may be added in the future. The activity profiling only records activities initiated using the Warp API. It does not capture CUDA activity initiated by other frameworks. A profiling tool like Nsight Systems can be used to examine whole program activities. Using CUDA Events ----------------- CUDA events can be used for timing purposes outside of the ``ScopedTimer``. Here is an example: .. code:: python with wp.ScopedDevice("cuda:0") as device: # ensure the module is loaded wp.load_module(device=device) # create events with enabled timing e1 = wp.Event(enable_timing=True) e2 = wp.Event(enable_timing=True) n = 10000000 # start timing... wp.record_event(e1) a = wp.zeros(n, dtype=float) wp.launch(inc, dim=n, inputs=[a]) # ...end timing wp.record_event(e2) # get elapsed time between the two events elapsed = wp.get_event_elapsed_time(e1, e2) print(elapsed) The events must be created with the flag ``enable_timing=True``. The first event is recorded at the start of the timed code and the second event is recorded at the end. The function :func:`warp.get_event_elapsed_time()` is used to compute the time difference between the two events. We must ensure that both events have completed on the device before calling :func:`warp.get_event_elapsed_time()`. By default, this function will synchronize on the second event using :func:`warp.synchronize_event()`. If that is not desired, the user may pass the ``synchronize=False`` flag and must use some other means of ensuring that both events have completed prior to calling the function. Note that timing very short operations may yield inflated results, due to the timing resolution of CUDA events and the overhead of the profiling code. In most cases, CUDA activity profiling with ``ScopedTimer`` will have less overhead and better precision. For the most accurate results, a profiling tool such as Nsight Systems should be used. The main benefit of using the manual event timing API is that it allows timing arbitrary sections of code rather than individual activities. Profiling API Reference ----------------------- .. autoclass:: warp.ScopedTimer .. autofunction:: warp.get_event_elapsed_time .. autofunction:: warp.synchronize_event .. autoclass:: warp.TimingResult .. autofunction:: warp.timing_begin .. autofunction:: warp.timing_end .. autofunction:: warp.timing_print
15,040
reStructuredText
53.104316
836
0.697074
NVIDIA/warp/docs/debugging.rst
Debugging ========= Printing Values --------------- Often one of the best debugging methods is to simply print values from kernels. Warp supports printing all built-in types using the ``print()`` function, e.g.:: v = wp.vec3(1.0, 2.0, 3.0) print(v) In addition, formatted C-style printing is available through the ``wp.printf()`` function, e.g.:: x = 1.0 i = 2 wp.printf("A float value %f, an int value: %d", x, i) .. note:: Formatted printing is only available for scalar types (e.g.: ``int`` and ``float``) not vector types. Printing Launches ----------------- For complex applications it can be difficult to understand the order-of-operations that lead to a bug. To help diagnose these issues Warp supports a simple option to print out all launches and arguments to the console:: wp.config.print_launches = True Step-Through Debugging ---------------------- It is possible to attach IDE debuggers such as Visual Studio to Warp processes to step through generated kernel code. Users should first compile the kernels in debug mode by setting:: wp.config.mode = "debug" This setting ensures that line numbers, and debug symbols are generated correctly. After launching the Python process, the debugger should be attached, and a breakpoint inserted into the generated code. .. note:: Generated kernel code is not a 1:1 correspondence with the original Python code, but individual operations can still be replayed and variables inspected. Also see :github:`warp/tests/walkthrough_debug.py` for an example of how to debug Warp kernel code running on the CPU. Generated Code -------------- Occasionally it can be useful to inspect the generated code for debugging or profiling. The generated code for kernels is stored in a central cache location in the user's home directory, the cache location is printed at startup when ``wp.init()`` is called, for example: .. code-block:: console Warp 0.8.1 initialized: CUDA Toolkit: 11.8, Driver: 11.8 Devices: "cpu" | AMD64 Family 25 Model 33 Stepping 0, AuthenticAMD "cuda:0" | NVIDIA GeForce RTX 3090 (sm_86) "cuda:1" | NVIDIA GeForce RTX 2080 Ti (sm_75) Kernel cache: C:\Users\LukasW\AppData\Local\NVIDIA Corporation\warp\Cache\0.8.1 The kernel cache has folders beginning with ``wp_`` that contain the generated C++/CUDA code and the compiled binaries for each module that was compiled at runtime. The name of each folder ends with a hexadecimal hash constructed from the module contents to avoid potential conflicts when using multiple processes and to support the caching of runtime-defined kernels. Bounds Checking --------------- Warp will perform bounds checking in debug build configurations to ensure that all array accesses lie within the defined shape. CUDA Verification ----------------- It is possible to generate out-of-bounds memory access violations through poorly formed kernel code or inputs. In this case the CUDA runtime will detect the violation and put the CUDA context into an error state. Subsequent kernel launches may silently fail which can lead to hard to diagnose issues. If a CUDA error is suspected a simple verification method is to enable:: wp.config.verify_cuda = True This setting will check the CUDA context after every operation to ensure that it is still valid. If an error is encountered it will raise an exception that often helps to narrow down the problematic kernel. .. note:: Verifying CUDA state at each launch requires synchronizing CPU and GPU which has a significant overhead. Users should ensure this setting is only used during debugging.
3,652
reStructuredText
39.588888
178
0.736857
NVIDIA/warp/docs/index.rst
NVIDIA Warp Documentation ========================= Warp is a Python framework for writing high-performance simulation and graphics code. Warp takes regular Python functions and JIT compiles them to efficient kernel code that can run on the CPU or GPU. Warp is designed for spatial computing and comes with a rich set of primitives that make it easy to write programs for physics simulation, perception, robotics, and geometry processing. In addition, Warp kernels are differentiable and can be used as part of machine-learning pipelines with frameworks such as PyTorch and JAX. Below are some examples of simulations implemented using Warp: .. image:: ./img/header.jpg Quickstart ---------- Python version 3.9 or newer is recommended. Warp can run on x86-64 and ARMv8 CPUs on Windows, Linux, and macOS. GPU support requires a CUDA-capable NVIDIA GPU and driver (minimum GeForce GTX 9xx). The easiest way to install Warp is from `PyPI <https://pypi.org/project/warp-lang>`_: .. code-block:: sh $ pip install warp-lang Pre-built binary packages are also available on the `Releases <https://github.com/NVIDIA/warp/releases>`_ page. To install in your local Python environment extract the archive and run the following command from the root directory: .. code-block:: sh $ pip install . Basic Example ------------- An example first program that computes the lengths of random 3D vectors is given below:: import warp as wp import numpy as np num_points = 1024 @wp.kernel def length(points: wp.array(dtype=wp.vec3), lengths: wp.array(dtype=float)): # thread index tid = wp.tid() # compute distance of each point from origin lengths[tid] = wp.length(points[tid]) # allocate an array of 3d points points = wp.array(np.random.rand(num_points, 3), dtype=wp.vec3) lengths = wp.zeros(num_points, dtype=float) # launch kernel wp.launch(kernel=length, dim=len(points), inputs=[points, lengths]) print(lengths) Additional Examples ------------------- The `examples <https://github.com/NVIDIA/warp/tree/main/warp/examples>`_ directory in the Github repository contains a number of scripts that show how to implement different simulation methods using the Warp API. Most examples will generate USD files containing time-sampled animations in the same directory as the example. Before running examples users should ensure that the ``usd-core`` package is installed using:: pip install usd-core Examples can be run from the command-line as follows:: python -m warp.examples.<example_subdir>.<example> Most examples can be run on either the CPU or a CUDA-capable device, but a handful require a CUDA-capable device. These are marked at the top of the example script. USD files can be viewed or rendered inside NVIDIA `Omniverse <https://developer.nvidia.com/omniverse>`_, Pixar's UsdView, and Blender. Note that Preview in macOS is not recommended as it has limited support for time-sampled animations. Built-in unit tests can be run from the command-line as follows:: python -m warp.tests examples/core ^^^^^^^^^^^^^ .. list-table:: :class: gallery * - .. image:: ./img/examples/core_dem.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_dem.py - .. image:: ./img/examples/core_fluid.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_fluid.py - .. image:: ./img/examples/core_graph_capture.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_graph_capture.py - .. image:: ./img/examples/core_marching_cubes.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_marching_cubes.py * - dem - fluid - graph capture - marching cubes * - .. image:: ./img/examples/core_mesh.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_mesh.py - .. image:: ./img/examples/core_nvdb.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_nvdb.py - .. image:: ./img/examples/core_raycast.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_raycast.py - .. image:: ./img/examples/core_raymarch.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_raymarch.py * - mesh - nvdb - raycast - raymarch * - .. image:: ./img/examples/core_sph.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_sph.py - .. image:: ./img/examples/core_torch.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_torch.py - .. image:: ./img/examples/core_wave.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/core/example_wave.py - * - sph - torch - wave - examples/fem ^^^^^^^^^^^^ .. list-table:: :class: gallery * - .. image:: ./img/examples/fem_apic_fluid.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_apic_fluid.py - .. image:: ./img/examples/fem_convection_diffusion.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_convection_diffusion.py - .. image:: ./img/examples/fem_diffusion_3d.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_diffusion_3d.py - .. image:: ./img/examples/fem_diffusion.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_diffusion.py * - apic fluid - convection diffusion - diffusion 3d - diffusion * - .. image:: ./img/examples/fem_mixed_elasticity.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_mixed_elasticity.py - .. image:: ./img/examples/fem_navier_stokes.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_navier_stokes.py - .. image:: ./img/examples/fem_stokes_transfer.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_stokes_transfer.py - .. image:: ./img/examples/fem_stokes.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/fem/example_stokes.py * - mixed elasticity - navier stokes - stokes transfer - stokes examples/optim ^^^^^^^^^^^^^^ .. list-table:: :class: gallery * - .. image:: ./img/examples/optim_bounce.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_bounce.py - .. image:: ./img/examples/optim_cloth_throw.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_cloth_throw.py - .. image:: ./img/examples/optim_diffray.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_diffray.py - .. image:: ./img/examples/optim_drone.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_drone.py * - bounce - cloth throw - diffray - drone * - .. image:: ./img/examples/optim_inverse_kinematics.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_inverse_kinematics.py - .. image:: ./img/examples/optim_spring_cage.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_spring_cage.py - .. image:: ./img/examples/optim_trajectory.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_trajectory.py - .. image:: ./img/examples/optim_walker.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/optim/example_walker.py * - inverse kinematics - spring cage - trajectory - walker examples/sim ^^^^^^^^^^^^ .. list-table:: :class: gallery * - .. image:: ./img/examples/sim_cartpole.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_cartpole.py - .. image:: ./img/examples/sim_cloth.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_cloth.py - .. image:: ./img/examples/sim_granular.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_granular.py - .. image:: ./img/examples/sim_granular_collision_sdf.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_granular_collision_sdf.py * - cartpole - cloth - granular - granular collision sdf * - .. image:: ./img/examples/sim_jacobian_ik.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_jacobian_ik.py - .. image:: ./img/examples/sim_quadruped.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_quadruped.py - .. image:: ./img/examples/sim_rigid_chain.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_rigid_chain.py - .. image:: ./img/examples/sim_rigid_contact.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_rigid_contact.py * - jacobian ik - quadruped - rigid chain - rigid contact * - .. image:: ./img/examples/sim_rigid_force.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_rigid_force.py - .. image:: ./img/examples/sim_rigid_gyroscopic.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_rigid_gyroscopic.py - .. image:: ./img/examples/sim_rigid_soft_contact.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_rigid_soft_contact.py - .. image:: ./img/examples/sim_soft_body.png :target: https://github.com/NVIDIA/warp/tree/main/warp/examples/sim/example_soft_body.py * - rigid force - rigid gyroscopic - rigid soft contact - soft body Omniverse --------- Omniverse extensions for Warp are available in the extension registry inside Omniverse Kit or USD Composer. The ``omni.warp.core`` extension installs Warp into the Omniverse Application's Python environment, which allows users to import the module in their scripts and nodes. The ``omni.warp`` extension provides a collection of OmniGraph nodes and sample scenes demonstrating uses of Warp in OmniGraph. Enabling the ``omni.warp`` extension automatically enables the ``omni.warp.core`` extension. Please see the `Omniverse Warp Documentation <https://docs.omniverse.nvidia.com/extensions/latest/ext_warp.html>`_ for more details on how to use Warp in Omniverse. Learn More ---------- Please see the following resources for additional background on Warp: - `Product Page <https://developer.nvidia.com/warp-python>`_ - `GTC 2022 Presentation <https://www.nvidia.com/en-us/on-demand/session/gtcspring22-s41599>`_ - `GTC 2021 Presentation <https://www.nvidia.com/en-us/on-demand/session/gtcspring21-s31838>`_ - `SIGGRAPH Asia 2021 Differentiable Simulation Course <https://dl.acm.org/doi/abs/10.1145/3476117.3483433>`_ - `GTC 2024 Presentation <https://www.nvidia.com/en-us/on-demand/session/gtc24-s63345>`_ The underlying technology in Warp has been used in a number of research projects at NVIDIA including the following publications: - Accelerated Policy Learning with Parallel Differentiable Simulation - Xu, J., Makoviychuk, V., Narang, Y., Ramos, F., Matusik, W., Garg, A., & Macklin, M. `(2022) <https://short-horizon-actor-critic.github.io>`__ - DiSECt: Differentiable Simulator for Robotic Cutting - Heiden, E., Macklin, M., Narang, Y., Fox, D., Garg, A., & Ramos, F `(2021) <https://github.com/NVlabs/DiSECt>`__ - gradSim: Differentiable Simulation for System Identification and Visuomotor Control - Murthy, J. Krishna, Miles Macklin, Florian Golemo, Vikram Voleti, Linda Petrini, Martin Weiss, Breandan Considine et al. `(2021) <https://gradsim.github.io>`__ Support ------- Problems, questions, and feature requests can be opened on `GitHub Issues <https://github.com/NVIDIA/warp/issues>`_. The Warp team also monitors the **#warp** channel on the public `Omniverse Discord <https://discord.com/invite/nvidiaomniverse>`_ server, come chat to us! Versioning ---------- Versions take the format X.Y.Z, similar to `Python itself <https://devguide.python.org/developer-workflow/development-cycle/#devcycle>`_: * Increments in X are reserved for major reworks of the project causing disruptive incompatibility (or reaching the 1.0 milestone). * Increments in Y are for regular releases with a new set of features. * Increments in Z are for bug fixes. In principle there are no new features. Can be omitted if 0 or not relevant. This is similar to `Semantic Versioning <https://semver.org/>`_ but less strict around backward compatibility. Like with Python, some breaking changes can be present between minor versions if well documented and gradually introduced. Note that prior to 0.11.0 this schema was not strictly adhered to. License ------- Warp is provided under the NVIDIA Software License, please see `LICENSE.md <https://github.com/NVIDIA/warp/blob/main/LICENSE.md>`_ for the full license text. Contributing ------------ Contributions and pull requests from the community are welcome and are taken under the terms described in the **9. Feedback** section of the `license <https://github.com/NVIDIA/warp/blob/main/LICENSE.md>`_. `CONTRIBUTING.md <https://github.com/NVIDIA/warp/blob/main/CONTRIBUTING.md>`_. provides additional information on how to open a pull request for Warp. Citing ------ If you use Warp in your research please use the following citation: .. code:: bibtex @misc{warp2022, title= {Warp: A High-performance Python Framework for GPU Simulation and Graphics}, author = {Miles Macklin}, month = {March}, year = {2022}, note= {NVIDIA GPU Technology Conference (GTC)}, howpublished = {\url{https://github.com/nvidia/warp}} } Full Table of Contents ---------------------- .. toctree:: :maxdepth: 2 :caption: User's Guide installation basics modules/devices modules/differentiability modules/generics modules/interoperability configuration debugging limitations faq .. toctree:: :maxdepth: 2 :caption: Advanced Topics modules/allocators modules/concurrency profiling .. toctree:: :maxdepth: 2 :caption: Core Reference modules/runtime modules/functions .. toctree:: :maxdepth: 2 :caption: Simulation Reference modules/sim modules/sparse modules/fem modules/render .. toctree:: :hidden: :caption: Project Links GitHub <https://github.com/NVIDIA/warp> PyPI <https://pypi.org/project/warp-lang> Discord <https://discord.com/channels/827959428476174346/953756751977648148> :ref:`Full Index <genindex>`
15,243
reStructuredText
38.187661
196
0.685954
NVIDIA/warp/docs/configuration.rst
.. _Configuration: Configuration ============= Warp has settings at the global, module, and kernel level that can be used to fine-tune the compilation and verbosity of Warp programs. In cases in which a setting can be changed at multiple levels (e.g.: ``enable_backward``), the setting at the more-specific scope takes precedence. Global Settings --------------- To change a setting, prepend ``wp.config.`` to the name of the variable and assign a value to it. Some settings may be changed on the fly, while others need to be set prior to calling ``wp.init()`` to take effect. For example, the location of the user kernel cache can be changed with: .. code-block:: python import os import warp as wp example_dir = os.path.dirname(os.path.realpath(__file__)) # set default cache directory before wp.init() wp.config.kernel_cache_dir = os.path.join(example_dir, "tmp", "warpcache1") wp.init() Basic Global Settings ^^^^^^^^^^^^^^^^^^^^^ +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ | Field | Type |Default Value| Description | +================================================+=========+=============+==========================================================================+ |``verify_fp`` | Boolean | ``False`` | If ``True``, Warp will check that inputs and outputs are finite before | | | | | and/or after various operations. **Has performance implications.** | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``verify_cuda`` | Boolean | ``False`` | If ``True``, Warp will check for CUDA errors after every launch and | | | | | memory operation. CUDA error verification cannot be used during graph | | | | | capture. **Has performance implications.** | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``print_launches`` | Boolean | ``False`` | If ``True``, Warp will print details of every kernel launch to standard | | | | | out (e.g. launch dimensions, inputs, outputs, device, etc.). | | | | | **Has performance implications.** | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``mode`` | String |``"release"``| Controls whether to compile Warp kernels in debug or release mode. | | | | | Valid choices are ``"release"`` or ``"debug"``. | | | | | **Has performance implications.** | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``max_unroll`` | Integer | Global | The maximum fixed-size loop to unroll. Note that ``max_unroll`` does not | | | | setting | consider the total number of iterations in nested loops. This can result | | | | | in a large amount of automatically generated code if each nested loop is | | | | | below the ``max_unroll`` threshold. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``verbose`` | Boolean | ``False`` | If ``True``, additional information will be printed to standard out | | | | | during code generation, compilation, etc. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``verbose_warnings`` | Boolean | ``False`` | If ``True``, Warp warnings will include extra information such as | | | | | the source file and line number. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``quiet`` | Boolean | ``False`` | If ``True``, Warp module initialization messages will be disabled. | | | | | This setting does not affect error messages and warnings. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``kernel_cache_dir`` | String | ``None`` | The path to the directory used for the user kernel cache. Subdirectories | | | | | beginning with ``wp_`` will be created in this directory. If ``None``, | | | | | a directory will be automatically determined using the value of the | | | | | environment variable ``WARP_CACHE_PATH`` or the | | | | | `appdirs.user_cache_directory <https://github.com/ActiveState/appdirs>`_ | | | | | if ``WARP_CACHE_PATH`` is also not set. ``kernel_cache_dir`` will be | | | | | updated to reflect the location of the cache directory used. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``enable_backward`` | Boolean | ``True`` | If ``True``, backward passes of kernels will be compiled by default. | | | | | Disabling this setting can reduce kernel compilation times. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``enable_graph_capture_module_load_by_default`` | Boolean | ``True`` | If ``True``, ``wp.capture_begin()`` will call ``wp.force_load()`` to | | | | | compile and load Warp kernels from all imported modules before graph | | | | | capture if the ``force_module_load`` argument is not explicitly provided | | | | | to ``wp.capture_begin()``. This setting is ignored if the CUDA driver | | | | | supports CUDA 12.3 or newer. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ |``enable_mempools_at_init`` | Boolean | ``False`` | If ``True``, ``wp.init()`` will enable pooled allocators on all CUDA | | | | | devices that support memory pools. | | | | | Pooled allocators are generally faster and can be used during CUDA graph | | | | | capture. For the caveats, see CUDA Pooled Allocators documentation. | +------------------------------------------------+---------+-------------+--------------------------------------------------------------------------+ Advanced Global Settings ^^^^^^^^^^^^^^^^^^^^^^^^ +--------------------+---------+-------------+--------------------------------------------------------------------------+ | Field | Type |Default Value| Description | +====================+=========+=============+==========================================================================+ |``cache_kernels`` | Boolean | ``True`` | If ``True``, kernels that have already been compiled from previous | | | | | application launches will not be recompiled. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``cuda_output`` | String | ``None`` | The preferred CUDA output format for kernels. Valid choices are ``None``,| | | | | ``"ptx"``, and ``"cubin"``. If ``None``, a format will be determined | | | | | automatically. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``ptx_target_arch`` | Integer | 70 | The target architecture for PTX generation. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``llvm_cuda`` | Boolean | ``False`` | If ``True``, Clang/LLVM will be used to compile CUDA code instead of | | | | | NVTRC. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ Module Settings --------------- Module-level settings to control runtime compilation and code generation may be changed by passing a dictionary of option pairs to ``wp.set_module_options()``. For example, compilation of backward passes for the kernel in an entire module can be disabled with: .. code:: python wp.set_module_options({"enable_backward": False}) The options for a module can also be queried using ``wp.get_module_options()``. +--------------------+---------+-------------+--------------------------------------------------------------------------+ | Field | Type |Default Value| Description | +====================+=========+=============+==========================================================================+ |``mode`` | String | Global | Controls whether to compile the module's kernels in debug or release | | | | setting | mode by default. Valid choices are ``"release"`` or ``"debug"``. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``max_unroll`` | Integer | Global | The maximum fixed-size loop to unroll. Note that ``max_unroll`` does not | | | | setting | consider the total number of iterations in nested loops. This can result | | | | | in a large amount of automatically generated code if each nested loop is | | | | | below the ``max_unroll`` threshold. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``enable_backward`` | Boolean | Global | If ``True``, backward passes of kernels will be compiled by default. | | | | setting | Valid choices are ``"release"`` or ``"debug"``. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``fast_math`` | Boolean | ``False`` | If ``True``, CUDA kernels will be compiled with the ``--use_fast_math`` | | | | | compiler option, which enables some fast math operations that are faster | | | | | but less accurate. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ |``cuda_output`` | String | ``None`` | The preferred CUDA output format for kernels. Valid choices are ``None``,| | | | | ``"ptx"``, and ``"cubin"``. If ``None``, a format will be determined | | | | | automatically. The module-level setting takes precedence over the global | | | | | setting. | +--------------------+---------+-------------+--------------------------------------------------------------------------+ Kernel Settings --------------- ``enable_backward`` is currently the only setting that can also be configured on a per-kernel level. Backward-pass compilation can be disabled by passing an argument into the ``@wp.kernel`` decorator as in the following example: .. code-block:: python @wp.kernel(enable_backward=False) def scale_2( x: wp.array(dtype=float), y: wp.array(dtype=float), ): y[0] = x[0] ** 2.0
14,673
reStructuredText
88.475609
163
0.321679
NVIDIA/warp/docs/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys from datetime import date sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import warp as wp # noqa: E402 # -- Project information ----------------------------------------------------- project = "Warp" copyright = f"2022-{date.today().year}, NVIDIA" author = "NVIDIA" version = wp.__version__ release = version # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", # Convert docstrings to reStructuredText "sphinx.ext.intersphinx", "sphinx.ext.autosummary", "sphinx.ext.extlinks", # Markup to shorten external links "sphinx.ext.githubpages", # Third-party extensions: "sphinx_copybutton", # 'sphinx_tabs.tabs', # 'autodocsumm' ] # put type hints inside the description instead of the signature (easier to read) autodoc_typehints = "description" # document class *and* __init__ methods autoclass_content = "both" autodoc_member_order = "bysource" # autodoc_typehints_format # add_module_names = False intersphinx_mapping = { "python": ("https://docs.python.org/3", None), "numpy": ("https://numpy.org/doc/stable", None), "jax": ("https://jax.readthedocs.io/en/latest", None), "pytorch": ("https://pytorch.org/docs/stable", None), } extlinks = { "github": ("https://github.com/NVIDIA/warp/blob/main/%s", "%s"), } # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # sphinx_copybutton settings copybutton_prompt_text = r">>> |\.\.\. |\$ " copybutton_prompt_is_regexp = True # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "furo" html_title = f"Warp {version}" html_show_sphinx = False # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] html_css_files = ["custom.css"] html_theme_options = { "top_of_page_button": None, "light_css_variables": { "admonition-title-font-size": "100%", "admonition-font-size": "100%", "color-api-pre-name": "#4e9a06", # "#76b900", "color-api-name": "#4e9a06", # "#76b900", "color-admonition-title--seealso": "#ffffff", "color-admonition-title-background--seealso": "#448aff", "color-admonition-title-background--note": "#76b900", "color-admonition-title--note": "#ffffff", }, "dark_css_variables": { "color-admonition-title-background--note": "#76b900", "color-admonition-title--note": "#ffffff", }, "light_logo": "logo-light-mode.png", "dark_logo": "logo-dark-mode.png", "footer_icons": [ { "name": "GitHub", "url": "https://github.com/NVIDIA/warp", "html": """ <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path> </svg> """, "class": "", }, ], }
4,711
Python
37
624
0.615156
NVIDIA/warp/docs/modules/generics.rst
Generics ======== Warp supports writing generic kernels and functions, which act as templates that can be instantiated with different concrete types. This allows you to write code once and reuse it with multiple data types. The concepts discussed on this page also apply to :ref:`Runtime Kernel Creation`. Generic Kernels --------------- Generic kernel definition syntax is the same as regular kernels, but you can use ``typing.Any`` in place of concrete types: .. code:: python from typing import Any # generic kernel definition using Any as a placeholder for concrete types @wp.kernel def scale(x: wp.array(dtype=Any), s: Any): i = wp.tid() x[i] = s * x[i] data = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = len(data) x16 = wp.array(data, dtype=wp.float16) x32 = wp.array(data, dtype=wp.float32) x64 = wp.array(data, dtype=wp.float64) # run the generic kernel with different data types wp.launch(scale, dim=n, inputs=[x16, wp.float16(3)]) wp.launch(scale, dim=n, inputs=[x32, wp.float32(3)]) wp.launch(scale, dim=n, inputs=[x64, wp.float64(3)]) print(x16) print(x32) print(x64) Under the hood, Warp will automatically generate new instances of the generic kernel to match the given argument types. Type Inference ~~~~~~~~~~~~~~ When a generic kernel is being launched, Warp infers the concrete types from the arguments. ``wp.launch()`` handles generic kernels without any special syntax, but we should be mindful of the data types passed as arguments to make sure that the correct types are inferred. - Scalars can be passed as regular Python numeric values (e.g., ``42`` or ``0.5``). Python integers are interpreted as ``wp.int32`` and Python floating point values are interpreted as ``wp.float32``. To specify a different data type and to avoid ambiguity, Warp data types should be used instead (e.g., ``wp.int64(42)`` or ``wp.float16(0.5)``). - Vectors and matrices should be passed as Warp types rather than tuples or lists (e.g., ``wp.vec3f(1.0, 2.0, 3.0)`` or ``wp.mat22h([[1.0, 0.0], [0.0, 1.0]])``). - Warp arrays and structs can be passed normally. .. _implicit_instantiation: Implicit Instantiation ~~~~~~~~~~~~~~~~~~~~~~ When you launch a generic kernel with a new set of data types, Warp automatically creates a new instance of this kernel with the given types. This is convenient, but there are some downsides to this implicit instantiation. Consider these three generic kernel launches: .. code:: python wp.launch(scale, dim=n, inputs=[x16, wp.float16(3)]) wp.launch(scale, dim=n, inputs=[x32, wp.float32(3)]) wp.launch(scale, dim=n, inputs=[x64, wp.float64(3)]) During each one of these launches, a new kernel instance is being generated, which forces the module to be reloaded. You might see something like this in the output: .. code:: text Module __main__ load on device 'cuda:0' took 170.37 ms Module __main__ load on device 'cuda:0' took 171.43 ms Module __main__ load on device 'cuda:0' took 179.49 ms This leads to a couple of potential problems: - The overhead of repeatedly rebuilding the modules can impact the overall performance of the program. - Module reloading during graph capture is not allowed on older CUDA drivers, which will cause captures to fail. Explicit instantiation can be used to overcome these issues. .. _explicit_instantiation: Explicit Instantiation ~~~~~~~~~~~~~~~~~~~~~~ Warp allows explicitly declaring instances of generic kernels with different types. One way is to use the ``@wp.overload`` decorator: .. code:: python @wp.overload def scale(x: wp.array(dtype=wp.float16), s: wp.float16): ... @wp.overload def scale(x: wp.array(dtype=wp.float32), s: wp.float32): ... @wp.overload def scale(x: wp.array(dtype=wp.float64), s: wp.float64): ... wp.launch(scale, dim=n, inputs=[x16, wp.float16(3)]) wp.launch(scale, dim=n, inputs=[x32, wp.float32(3)]) wp.launch(scale, dim=n, inputs=[x64, wp.float64(3)]) The ``@wp.overload`` decorator allows re-declaring generic kernels without repeating the kernel code. The kernel body is just replaced with the ellipsis (``...``). Warp keeps track of known overloads for each kernel, so if an overload exists it will not be instantiated again. If all the overloads are declared prior to kernel launches, the module will only load once with all the kernel instances in place. We can also use ``wp.overload()`` as a function for a slightly more concise syntax. We just need to specify the generic kernel and a list of concrete argument types: .. code:: python wp.overload(scale, [wp.array(dtype=wp.float16), wp.float16]) wp.overload(scale, [wp.array(dtype=wp.float32), wp.float32]) wp.overload(scale, [wp.array(dtype=wp.float64), wp.float64]) Instead of an argument list, a dictionary can also be provided: .. code:: python wp.overload(scale, {"x": wp.array(dtype=wp.float16), "s": wp.float16}) wp.overload(scale, {"x": wp.array(dtype=wp.float32), "s": wp.float32}) wp.overload(scale, {"x": wp.array(dtype=wp.float64), "s": wp.float64}) A dictionary might be preferred for readability. With dictionaries, only generic arguments need to be specified, which can be even more concise when overloading kernels where some of the arguments are not generic. We can easily create overloads in a single loop, like this: .. code:: python for T in [wp.float16, wp.float32, wp.float64]: wp.overload(scale, [wp.array(dtype=T), T]) Finally, the ``wp.overload()`` function returns the concrete kernel instance, which can be saved in a variable: .. code:: python scale_f16 = wp.overload(scale, [wp.array(dtype=wp.float16), wp.float16]) scale_f32 = wp.overload(scale, [wp.array(dtype=wp.float32), wp.float32]) scale_f64 = wp.overload(scale, [wp.array(dtype=wp.float64), wp.float64]) These instances are treated as regular kernels, not generic. This means that launches should be faster, because Warp doesn't need to infer data types from the arguments like it does when launching generic kernels. The typing requirements for kernel arguments are also more relaxed than with generic kernels, because Warp can convert scalars, vectors, and matrices to the known required types. .. code:: python # launch concrete kernel instances wp.launch(scale_f16, dim=n, inputs=[x16, 3]) wp.launch(scale_f32, dim=n, inputs=[x32, 3]) wp.launch(scale_f64, dim=n, inputs=[x64, 3]) .. _Generic Functions: Generic Functions ----------------- Like Warp kernels, we can also define generic Warp functions: .. code:: python # generic function @wp.func def f(x: Any): return x * x # use generic function in a regular kernel @wp.kernel def square_float(a: wp.array(dtype=float)): i = wp.tid() a[i] = f(a[i]) # use generic function in a generic kernel @wp.kernel def square_any(a: wp.array(dtype=Any)): i = wp.tid() a[i] = f(a[i]) data = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = len(data) af = wp.array(data, dtype=float) ai = wp.array(data, dtype=int) # launch regular kernel wp.launch(square_float, dim=n, inputs=[af]) # launch generic kernel wp.launch(square_any, dim=n, inputs=[af]) wp.launch(square_any, dim=n, inputs=[ai]) A generic function can be used in regular and generic kernels. It's not necessary to explicitly overload generic functions. All required function overloads are generated automatically when those functions are used in kernels. type() Operator --------------- Consider the following generic function: .. code:: python @wp.func def triple(x: Any): return 3 * x Using numeric literals like ``3`` is problematic in generic expressions due to Warp's strict typing rules. Operands in arithmetic expressions must have the same data types, but integer literals are always treated as ``wp.int32``. This function will fail to compile if ``x`` has a data type other than ``wp.int32``, which means that it's not generic at all. The ``type()`` operator comes to the rescue here. The ``type()`` operator returns the type of its argument, which is handy in generic functions or kernels where the data types are not known in advance. We can rewrite the function like this to make it work with a wider range of types: .. code:: python @wp.func def triple(x: Any): return type(x)(3) * x The ``type()`` operator is useful for type conversions in Warp kernels and functions. For example, here is a simple generic ``arange()`` kernel: .. code:: python @wp.kernel def arange(a: wp.array(dtype=Any)): i = wp.tid() a[i] = type(a[0])(i) n = 10 ai = wp.empty(n, dtype=wp.int32) af = wp.empty(n, dtype=wp.float32) wp.launch(arange, dim=n, inputs=[ai]) wp.launch(arange, dim=n, inputs=[af]) ``wp.tid()`` returns an integer, but the value gets converted to the array's data type before storing it in the array. Alternatively, we could write our ``arange()`` kernel like this: .. code:: python @wp.kernel def arange(a: wp.array(dtype=Any)): i = wp.tid() a[i] = a.dtype(i) This variant uses the ``array.dtype()`` operator, which returns the type of the array's contents. Limitations and Rough Edges --------------------------- Warp generics are still in development and there are some limitations. Module Reloading Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~ As mentioned in the :ref:`implicit instantiation <implicit_instantiation>` section, launching new kernel overloads triggers the recompilation of the kernel module. This adds overhead and doesn't play well with Warp's current kernel caching strategy. Kernel caching relies on hashing the contents of the module, which includes all the concrete kernels and functions encountered in the Python program so far. Whenever a new kernel or a new instance of a generic kernel is added, the module needs to be reloaded. Re-running the Python program leads to the same sequence of kernels being added to the module, which means that implicit instantiation of generic kernels will trigger the same module reloading on every run. This is clearly not ideal, and we intend to improve this behavior in the future. Using :ref:`explicit instantiation <explicit_instantiation>` is usually a good workaround for this, as long as the overloads are added in the same order before any kernel launches. Note that this issue is not specific to generic kernels. Adding new regular kernels to a module can also trigger repetitive module reloading if the kernel definitions are intermixed with kernel launches. For example: .. code:: python @wp.kernel def foo(x: float): wp.print(x) wp.launch(foo, dim=1, inputs=[17]) @wp.kernel def bar(x: float): wp.print(x) wp.launch(bar, dim=1, inputs=[42]) This code will also trigger module reloading during each kernel launch, even though it doesn't use generics at all: .. code:: text Module __main__ load on device 'cuda:0' took 155.73 ms 17 Module __main__ load on device 'cuda:0' took 164.83 ms 42 Graph Capture ~~~~~~~~~~~~~ Module reloading is not allowed during graph capture in CUDA 12.2 or older. Kernel instantiation can trigger module reloading, which will cause graph capture to fail on drivers that don't support newer versions of CUDA. The workaround, again, is to explicitly declare the required overloads before capture begins. Type Variables ~~~~~~~~~~~~~~ Warp's ``type()`` operator is similar in principle to Python's ``type()`` function, but it's currently not possible to use types as variables in Warp kernels and functions. For example, the following is currently `not` allowed: .. code:: python @wp.func def triple(x: Any): # TODO: T = type(x) return T(3) * x Kernel Overloading Restrictions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's currently not possible to define multiple kernels with the same name but different argument counts, but this restriction may be lifted in the future.
12,174
reStructuredText
38.65798
802
0.695499
NVIDIA/warp/docs/modules/sparse.rst
warp.sparse =============================== .. currentmodule:: warp.sparse .. .. toctree:: :maxdepth: 2 Warp includes a sparse linear algebra module ``warp.sparse`` that implements some common sparse matrix operations that arise in simulation. Sparse Matrices ------------------------- Currently `warp.sparse` supports Block Sparse Row (BSR) matrices, the BSR format can also be used to represent Compressed Sparse Row (CSR) matrices as a special case with a 1x1 block size. .. automodule:: warp.sparse :members: Iterative Linear Solvers ------------------------ .. currentmodule:: warp.optim.linear Warp provides a few common iterative linear solvers (:func:`cg`, :func:`cr`, :func:`bicgstab`, :func:`gmres`) with optional preconditioning. .. note:: While primarily intended to work with sparse matrices, those solvers also accept dense linear operators provided as 2D Warp arrays. It is also possible to provide custom operators, see :class:`LinearOperator`. .. automodule:: warp.optim.linear :members:
1,037
reStructuredText
30.454545
188
0.690453
NVIDIA/warp/docs/modules/sim.rst
warp.sim ==================== .. currentmodule:: warp.sim .. .. toctree:: :maxdepth: 2 Warp includes a simulation module ``warp.sim`` that includes many common physical simulation models, and integrators for explicit and implicit time-stepping. .. note:: The simulation model is under construction and should be expected to change rapidly, please treat this section as work in progress. Model ----- .. autoclass:: ModelBuilder :members: .. autoclass:: Model :members: .. autoclass:: ModelShapeMaterials :members: .. autoclass:: ModelShapeGeometry :members: .. autoclass:: JointAxis :members: .. autoclass:: Mesh :members: .. autoclass:: SDF :members: .. _Joint types: Joint types ^^^^^^^^^^^^^^ .. data:: JOINT_PRISMATIC Prismatic (slider) joint .. data:: JOINT_REVOLUTE Revolute (hinge) joint .. data:: JOINT_BALL Ball (spherical) joint with quaternion state representation .. data:: JOINT_FIXED Fixed (static) joint .. data:: JOINT_FREE Free (floating) joint .. data:: JOINT_COMPOUND Compound joint with 3 rotational degrees of freedom .. data:: JOINT_UNIVERSAL Universal joint with 2 rotational degrees of freedom .. data:: JOINT_DISTANCE Distance joint that keeps two bodies at a distance within its joint limits (only supported in :class:`XPBDIntegrator` at the moment) .. data:: JOINT_D6 Generic D6 joint with up to 3 translational and 3 rotational degrees of freedom .. _Joint modes: Joint control modes ^^^^^^^^^^^^^^^^^^^ Joint modes control the behavior of how the joint control input :attr:`Control.joint_act` affects the torque applied at a given joint axis. By default, it behaves as a direct force application via :data:`JOINT_MODE_FORCE`. Other modes can be used to implement joint position or velocity drives: .. data:: JOINT_MODE_FORCE This is the default control mode where the control input is the torque :math:`\tau` applied at the joint axis. .. data:: JOINT_MODE_TARGET_POSITION The control input is the target position :math:`\mathbf{q}_{\text{target}}` which is achieved via PD control of torque :math:`\tau` where the proportional and derivative gains are set by :attr:`Model.joint_target_ke` and :attr:`Model.joint_target_kd`: .. math:: \tau = k_e (\mathbf{q}_{\text{target}} - \mathbf{q}) - k_d \mathbf{\dot{q}} .. data:: JOINT_MODE_TARGET_VELOCITY The control input is the target velocity :math:`\mathbf{\dot{q}}_{\text{target}}` which is achieved via a controller of torque :math:`\tau` that brings the velocity at the joint axis to the target through proportional gain :attr:`Model.joint_target_ke`: .. math:: \tau = k_e (\mathbf{\dot{q}}_{\text{target}} - \mathbf{\dot{q}}) State -------------- .. autoclass:: State :members: Control -------------- .. autoclass:: Control :members: .. _FK-IK: Forward / Inverse Kinematics ---------------------------- Articulated rigid-body mechanisms are kinematically described by the joints that connect the bodies as well as the relative relative transform from the parent and child body to the respective anchor frames of the joint in the parent and child body: .. image:: /img/joint_transforms.png :width: 400 :align: center .. list-table:: Variable names in the kernels from articulation.py :widths: 10 90 :header-rows: 1 * - Symbol - Description * - x_wp - World transform of the parent body (stored at :attr:`State.body_q`) * - x_wc - World transform of the child body (stored at :attr:`State.body_q`) * - x_pj - Transform from the parent body to the joint parent anchor frame (defined by :attr:`Model.joint_X_p`) * - x_cj - Transform from the child body to the joint child anchor frame (defined by :attr:`Model.joint_X_c`) * - x_j - Joint transform from the joint parent anchor frame to the joint child anchor frame In the forward kinematics, the joint transform is determined by the joint coordinates (generalized joint positions :attr:`State.joint_q` and velocities :attr:`State.joint_qd`). Given the parent body's world transform :math:`x_{wp}` and the joint transform :math:`x_{j}`, the child body's world transform :math:`x_{wc}` is computed as: .. math:: x_{wc} = x_{wp} \cdot x_{pj} \cdot x_{j} \cdot x_{cj}^{-1}. .. autofunction:: eval_fk .. autofunction:: eval_ik Integrators -------------- .. autoclass:: Integrator :members: .. autoclass:: SemiImplicitIntegrator :members: .. autoclass:: XPBDIntegrator :members: .. autoclass:: FeatherstoneIntegrator :members: Importers -------------- Warp sim supports the loading of simulation models from URDF, MuJoCo (MJCF), and USD Physics files. .. autofunction:: parse_urdf .. autofunction:: parse_mjcf .. autofunction:: parse_usd .. autofunction:: resolve_usd_from_url Utility functions ------------------ Common utility functions used in simulators. .. autofunction:: velocity_at_point .. autofunction:: quat_to_euler .. autofunction:: quat_from_euler .. autofunction:: load_mesh
5,086
reStructuredText
24.691919
258
0.679709
NVIDIA/warp/docs/modules/functions.rst
.. Autogenerated File - Do not edit. Run build_docs.py to generate. .. functions: .. currentmodule:: warp Kernel Reference ================ Scalar Types ------------ .. class:: int8 .. class:: uint8 .. class:: int16 .. class:: uint16 .. class:: int32 .. class:: uint32 .. class:: int64 .. class:: uint64 .. class:: float16 .. class:: float32 .. class:: float64 .. class:: bool Vector Types ------------ .. class:: vec2b .. class:: vec2ub .. class:: vec2s .. class:: vec2us .. class:: vec2i .. class:: vec2ui .. class:: vec2l .. class:: vec2ul .. class:: vec2h .. class:: vec2f .. class:: vec2d .. class:: vec3b .. class:: vec3ub .. class:: vec3s .. class:: vec3us .. class:: vec3i .. class:: vec3ui .. class:: vec3l .. class:: vec3ul .. class:: vec3h .. class:: vec3f .. class:: vec3d .. class:: vec4b .. class:: vec4ub .. class:: vec4s .. class:: vec4us .. class:: vec4i .. class:: vec4ui .. class:: vec4l .. class:: vec4ul .. class:: vec4h .. class:: vec4f .. class:: vec4d .. class:: mat22h .. class:: mat22f .. class:: mat22d .. class:: mat33h .. class:: mat33f .. class:: mat33d .. class:: mat44h .. class:: mat44f .. class:: mat44d .. class:: quath .. class:: quatf .. class:: quatd .. class:: transformh .. class:: transformf .. class:: transformd .. class:: spatial_vectorh .. class:: spatial_vectorf .. class:: spatial_vectord .. class:: spatial_matrixh .. class:: spatial_matrixf .. class:: spatial_matrixd Generic Types ------------- .. class:: Int .. class:: Float .. class:: Scalar .. class:: Vector .. class:: Matrix .. class:: Quaternion .. class:: Transformation .. class:: Array Query Types ------------- .. autoclass:: bvh_query_t .. autoclass:: hash_grid_query_t .. autoclass:: mesh_query_aabb_t .. autoclass:: mesh_query_point_t .. autoclass:: mesh_query_ray_t Scalar Math --------------- .. py:function:: min(x: Scalar, y: Scalar) -> Scalar Return the minimum of two scalars. .. py:function:: min(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: Return the element-wise minimum of two vectors. .. py:function:: min(v: Vector[Any,Scalar]) -> Scalar :noindex: :nocontentsentry: Return the minimum element of a vector ``v``. .. py:function:: max(x: Scalar, y: Scalar) -> Scalar Return the maximum of two scalars. .. py:function:: max(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: Return the element-wise maximum of two vectors. .. py:function:: max(v: Vector[Any,Scalar]) -> Scalar :noindex: :nocontentsentry: Return the maximum element of a vector ``v``. .. py:function:: clamp(x: Scalar, a: Scalar, b: Scalar) -> Scalar Clamp the value of ``x`` to the range [a, b]. .. py:function:: abs(x: Scalar) -> Scalar Return the absolute value of ``x``. .. py:function:: sign(x: Scalar) -> Scalar Return -1 if ``x`` < 0, return 1 otherwise. .. py:function:: step(x: Scalar) -> Scalar Return 1.0 if ``x`` < 0.0, return 0.0 otherwise. .. py:function:: nonzero(x: Scalar) -> Scalar Return 1.0 if ``x`` is not equal to zero, return 0.0 otherwise. .. py:function:: sin(x: Float) -> Float Return the sine of ``x`` in radians. .. py:function:: cos(x: Float) -> Float Return the cosine of ``x`` in radians. .. py:function:: acos(x: Float) -> Float Return arccos of ``x`` in radians. Inputs are automatically clamped to [-1.0, 1.0]. .. py:function:: asin(x: Float) -> Float Return arcsin of ``x`` in radians. Inputs are automatically clamped to [-1.0, 1.0]. .. py:function:: sqrt(x: Float) -> Float Return the square root of ``x``, where ``x`` is positive. .. py:function:: cbrt(x: Float) -> Float Return the cube root of ``x``. .. py:function:: tan(x: Float) -> Float Return the tangent of ``x`` in radians. .. py:function:: atan(x: Float) -> Float Return the arctangent of ``x`` in radians. .. py:function:: atan2(y: Float, x: Float) -> Float Return the 2-argument arctangent, atan2, of the point ``(x, y)`` in radians. .. py:function:: sinh(x: Float) -> Float Return the sinh of ``x``. .. py:function:: cosh(x: Float) -> Float Return the cosh of ``x``. .. py:function:: tanh(x: Float) -> Float Return the tanh of ``x``. .. py:function:: degrees(x: Float) -> Float Convert ``x`` from radians into degrees. .. py:function:: radians(x: Float) -> Float Convert ``x`` from degrees into radians. .. py:function:: log(x: Float) -> Float Return the natural logarithm (base-e) of ``x``, where ``x`` is positive. .. py:function:: log2(x: Float) -> Float Return the binary logarithm (base-2) of ``x``, where ``x`` is positive. .. py:function:: log10(x: Float) -> Float Return the common logarithm (base-10) of ``x``, where ``x`` is positive. .. py:function:: exp(x: Float) -> Float Return the value of the exponential function :math:`e^x`. .. py:function:: pow(x: Float, y: Float) -> Float Return the result of ``x`` raised to power of ``y``. .. py:function:: round(x: Float) -> Float Return the nearest integer value to ``x``, rounding halfway cases away from zero. This is the most intuitive form of rounding in the colloquial sense, but can be slower than other options like :func:`warp.rint()`. Differs from :func:`numpy.round()`, which behaves the same way as :func:`numpy.rint()`. .. py:function:: rint(x: Float) -> Float Return the nearest integer value to ``x``, rounding halfway cases to nearest even integer. It is generally faster than :func:`warp.round()`. Equivalent to :func:`numpy.rint()`. .. py:function:: trunc(x: Float) -> Float Return the nearest integer that is closer to zero than ``x``. In other words, it discards the fractional part of ``x``. It is similar to casting ``float(int(x))``, but preserves the negative sign when x is in the range [-0.0, -1.0). Equivalent to :func:`numpy.trunc()` and :func:`numpy.fix()`. .. py:function:: floor(x: Float) -> Float Return the largest integer that is less than or equal to ``x``. .. py:function:: ceil(x: Float) -> Float Return the smallest integer that is greater than or equal to ``x``. .. py:function:: frac(x: Float) -> Float Retrieve the fractional part of x. In other words, it discards the integer part of x and is equivalent to ``x - trunc(x)``. .. py:function:: isfinite(x: Scalar) -> bool Return ``True`` if x is a finite number, otherwise return ``False``. .. py:function:: isfinite(x: Vector[Any,Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if all elements of the vector ``x`` are finite, otherwise return ``False``. .. py:function:: isfinite(x: Quaternion[Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if all elements of the quaternion ``x`` are finite, otherwise return ``False``. .. py:function:: isfinite(m: Matrix[Any,Any,Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if all elements of the matrix ``m`` are finite, otherwise return ``False``. .. py:function:: isnan(x: Scalar) -> bool Return ``True`` if ``x`` is NaN, otherwise return ``False``. .. py:function:: isnan(x: Vector[Any,Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if any element of the vector ``x`` is NaN, otherwise return ``False``. .. py:function:: isnan(x: Quaternion[Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if any element of the quaternion ``x`` is NaN, otherwise return ``False``. .. py:function:: isnan(m: Matrix[Any,Any,Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if any element of the matrix ``m`` is NaN, otherwise return ``False``. .. py:function:: isinf(x: Scalar) -> bool Return ``True`` if x is positive or negative infinity, otherwise return ``False``. .. py:function:: isinf(x: Vector[Any,Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if any element of the vector ``x`` is positive or negative infinity, otherwise return ``False``. .. py:function:: isinf(x: Quaternion[Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if any element of the quaternion ``x`` is positive or negative infinity, otherwise return ``False``. .. py:function:: isinf(m: Matrix[Any,Any,Scalar]) -> bool :noindex: :nocontentsentry: Return ``True`` if any element of the matrix ``m`` is positive or negative infinity, otherwise return ``False``. Vector Math --------------- .. py:function:: dot(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Scalar Compute the dot product between two vectors. .. py:function:: dot(x: Quaternion[Float], y: Quaternion[Float]) -> Scalar :noindex: :nocontentsentry: Compute the dot product between two quaternions. .. py:function:: ddot(x: Matrix[Any,Any,Scalar], y: Matrix[Any,Any,Scalar]) -> Scalar Compute the double dot product between two matrices. .. py:function:: argmin(v: Vector[Any,Scalar]) -> uint32 Return the index of the minimum element of a vector ``v``. [1]_ .. py:function:: argmax(v: Vector[Any,Scalar]) -> uint32 Return the index of the maximum element of a vector ``v``. [1]_ .. py:function:: outer(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Matrix[Any,Any,Scalar] Compute the outer product ``x*y^T`` for two vectors. .. py:function:: cross(x: Vector[3,Scalar], y: Vector[3,Scalar]) -> Vector[3,Scalar] Compute the cross product of two 3D vectors. .. py:function:: skew(x: Vector[3,Scalar]) Compute the skew-symmetric 3x3 matrix for a 3D vector ``x``. .. py:function:: length(x: Vector[Any,Float]) -> Scalar Compute the length of a floating-point vector ``x``. .. py:function:: length(x: Quaternion[Float]) -> Scalar :noindex: :nocontentsentry: Compute the length of a quaternion ``x``. .. py:function:: length_sq(x: Vector[Any,Scalar]) -> Scalar Compute the squared length of a vector ``x``. .. py:function:: length_sq(x: Quaternion[Scalar]) -> Scalar :noindex: :nocontentsentry: Compute the squared length of a quaternion ``x``. .. py:function:: normalize(x: Vector[Any,Float]) -> Vector[Any,Scalar] Compute the normalized value of ``x``. If ``length(x)`` is 0 then the zero vector is returned. .. py:function:: normalize(x: Quaternion[Float]) -> Quaternion[Scalar] :noindex: :nocontentsentry: Compute the normalized value of ``x``. If ``length(x)`` is 0, then the zero quaternion is returned. .. py:function:: transpose(m: Matrix[Any,Any,Scalar]) Return the transpose of the matrix ``m``. .. py:function:: inverse(m: Matrix[2,2,Float]) -> Matrix[Any,Any,Float] Return the inverse of a 2x2 matrix ``m``. .. py:function:: inverse(m: Matrix[3,3,Float]) -> Matrix[Any,Any,Float] :noindex: :nocontentsentry: Return the inverse of a 3x3 matrix ``m``. .. py:function:: inverse(m: Matrix[4,4,Float]) -> Matrix[Any,Any,Float] :noindex: :nocontentsentry: Return the inverse of a 4x4 matrix ``m``. .. py:function:: determinant(m: Matrix[2,2,Float]) -> Scalar Return the determinant of a 2x2 matrix ``m``. .. py:function:: determinant(m: Matrix[3,3,Float]) -> Scalar :noindex: :nocontentsentry: Return the determinant of a 3x3 matrix ``m``. .. py:function:: determinant(m: Matrix[4,4,Float]) -> Scalar :noindex: :nocontentsentry: Return the determinant of a 4x4 matrix ``m``. .. py:function:: trace(m: Matrix[Any,Any,Scalar]) -> Scalar Return the trace of the matrix ``m``. .. py:function:: diag(d: Vector[Any,Scalar]) -> Matrix[Any,Any,Scalar] Returns a matrix with the components of the vector ``d`` on the diagonal. .. py:function:: get_diag(m: Matrix[Any,Any,Scalar]) -> Vector[Any,Scalar] Returns a vector containing the diagonal elements of the square matrix ``m``. .. py:function:: cw_mul(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] Component-wise multiplication of two vectors. .. py:function:: cw_mul(x: Matrix[Any,Any,Scalar], y: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: Component-wise multiplication of two matrices. .. py:function:: cw_div(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] Component-wise division of two vectors. .. py:function:: cw_div(x: Matrix[Any,Any,Scalar], y: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: Component-wise division of two matrices. .. py:function:: vector(w: Vector[3,Float], v: Vector[3,Float]) Construct a 6D screw vector from two 3D vectors. .. py:function:: vector(*arg_types: Scalar, length: int32, dtype: Scalar) -> Vector[Any,Scalar] :noindex: :nocontentsentry: Construct a vector of with given length and dtype. .. py:function:: matrix(pos: Vector[3,Float], rot: Quaternion[Float], scale: Vector[3,Float]) -> Matrix[4,4,Float] Construct a 4x4 transformation matrix that applies the transformations as Translation(pos)*Rotation(rot)*Scale(scale) when applied to column vectors, i.e.: y = (TRS)*x .. py:function:: matrix(*arg_types: Scalar, shape: Tuple[int, int], dtype: Scalar) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: Construct a matrix. If the positional ``arg_types`` are not given, then matrix will be zero-initialized. .. py:function:: identity(n: int32, dtype: Scalar) -> Matrix[Any,Any,Scalar] Create an identity matrix with shape=(n,n) with the type given by ``dtype``. .. py:function:: svd3(A: Matrix[3,3,Float], U: Matrix[3,3,Float], sigma: Vector[3,Float], V: Matrix[3,3,Scalar]) -> None Compute the SVD of a 3x3 matrix ``A``. The singular values are returned in ``sigma``, while the left and right basis vectors are returned in ``U`` and ``V``. .. py:function:: qr3(A: Matrix[3,3,Float], Q: Matrix[3,3,Float], R: Matrix[3,3,Float]) -> None Compute the QR decomposition of a 3x3 matrix ``A``. The orthogonal matrix is returned in ``Q``, while the upper triangular matrix is returned in ``R``. .. py:function:: eig3(A: Matrix[3,3,Float], Q: Matrix[3,3,Float], d: Vector[3,Float]) -> None Compute the eigendecomposition of a 3x3 matrix ``A``. The eigenvectors are returned as the columns of ``Q``, while the corresponding eigenvalues are returned in ``d``. Quaternion Math --------------- .. py:function:: quaternion() -> Quaternion[Float] Construct a zero-initialized quaternion. Quaternions are laid out as [ix, iy, iz, r], where ix, iy, iz are the imaginary part, and r the real part. .. py:function:: quaternion(x: Float, y: Float, z: Float, w: Float) -> Quaternion[Float] :noindex: :nocontentsentry: Create a quaternion using the supplied components (type inferred from component type). .. py:function:: quaternion(i: Vector[3,Float], r: Float) -> Quaternion[Float] :noindex: :nocontentsentry: Create a quaternion using the supplied vector/scalar (type inferred from scalar type). .. py:function:: quaternion(q: Quaternion[Float]) :noindex: :nocontentsentry: Construct a quaternion of type dtype from another quaternion of a different dtype. .. py:function:: quat_identity() -> quatf Construct an identity quaternion with zero imaginary part and real part of 1.0 .. py:function:: quat_from_axis_angle(axis: Vector[3,Float], angle: Float) -> Quaternion[Scalar] Construct a quaternion representing a rotation of angle radians around the given axis. .. py:function:: quat_to_axis_angle(q: Quaternion[Float], axis: Vector[3,Float], angle: Float) -> None Extract the rotation axis and angle radians a quaternion represents. .. py:function:: quat_from_matrix(m: Matrix[3,3,Float]) -> Quaternion[Scalar] Construct a quaternion from a 3x3 matrix. .. py:function:: quat_rpy(roll: Float, pitch: Float, yaw: Float) -> Quaternion[Scalar] Construct a quaternion representing a combined roll (z), pitch (x), yaw rotations (y) in radians. .. py:function:: quat_inverse(q: Quaternion[Float]) -> Quaternion[Scalar] Compute quaternion conjugate. .. py:function:: quat_rotate(q: Quaternion[Float], p: Vector[3,Float]) -> Vector[3,Scalar] Rotate a vector by a quaternion. .. py:function:: quat_rotate_inv(q: Quaternion[Float], p: Vector[3,Float]) -> Vector[3,Scalar] Rotate a vector by the inverse of a quaternion. .. py:function:: quat_slerp(q0: Quaternion[Float], q1: Quaternion[Float], t: Float) -> Quaternion[Scalar] Linearly interpolate between two quaternions. .. py:function:: quat_to_matrix(q: Quaternion[Float]) -> Matrix[3,3,Scalar] Convert a quaternion to a 3x3 rotation matrix. Transformations --------------- .. py:function:: transformation(p: Vector[3,Float], q: Quaternion[Float]) -> Transformation[Scalar] Construct a rigid-body transformation with translation part ``p`` and rotation ``q``. .. py:function:: transform_identity() -> transformf Construct an identity transform with zero translation and identity rotation. .. py:function:: transform_get_translation(t: Transformation[Float]) -> Vector[3,Scalar] Return the translational part of a transform ``t``. .. py:function:: transform_get_rotation(t: Transformation[Float]) -> Quaternion[Scalar] Return the rotational part of a transform ``t``. .. py:function:: transform_multiply(a: Transformation[Float], b: Transformation[Float]) -> Transformation[Scalar] Multiply two rigid body transformations together. .. py:function:: transform_point(t: Transformation[Scalar], p: Vector[3,Scalar]) -> Vector[3,Scalar] Apply the transform to a point ``p`` treating the homogeneous coordinate as w=1 (translation and rotation). .. py:function:: transform_point(m: Matrix[4,4,Scalar], p: Vector[3,Scalar]) -> Vector[3,Scalar] :noindex: :nocontentsentry: Apply the transform to a point ``p`` treating the homogeneous coordinate as w=1. The transformation is applied treating ``p`` as a column vector, e.g.: ``y = M*p``. Note this is in contrast to some libraries, notably USD, which applies transforms to row vectors, ``y^T = p^T*M^T``. If the transform is coming from a library that uses row-vectors, then users should transpose the transformation matrix before calling this method. .. py:function:: transform_vector(t: Transformation[Scalar], v: Vector[3,Scalar]) -> Vector[3,Scalar] Apply the transform to a vector ``v`` treating the homogeneous coordinate as w=0 (rotation only). .. py:function:: transform_vector(m: Matrix[4,4,Scalar], v: Vector[3,Scalar]) -> Vector[3,Scalar] :noindex: :nocontentsentry: Apply the transform to a vector ``v`` treating the homogeneous coordinate as w=0. The transformation is applied treating ``v`` as a column vector, e.g.: ``y = M*v`` note this is in contrast to some libraries, notably USD, which applies transforms to row vectors, ``y^T = v^T*M^T``. If the transform is coming from a library that uses row-vectors, then users should transpose the transformation matrix before calling this method. .. py:function:: transform_inverse(t: Transformation[Float]) -> Transformation[Float] Compute the inverse of the transformation ``t``. Spatial Math --------------- .. py:function:: spatial_adjoint(r: Matrix[3,3,Float], s: Matrix[3,3,Float]) -> Matrix[6,6,Scalar] Construct a 6x6 spatial inertial matrix from two 3x3 diagonal blocks. .. py:function:: spatial_dot(a: Vector[6,Float], b: Vector[6,Float]) -> Scalar Compute the dot product of two 6D screw vectors. .. py:function:: spatial_cross(a: Vector[6,Float], b: Vector[6,Float]) -> Vector[6,Float] Compute the cross product of two 6D screw vectors. .. py:function:: spatial_cross_dual(a: Vector[6,Float], b: Vector[6,Float]) -> Vector[6,Float] Compute the dual cross product of two 6D screw vectors. .. py:function:: spatial_top(a: Vector[6,Float]) Return the top (first) part of a 6D screw vector. .. py:function:: spatial_bottom(a: Vector[6,Float]) Return the bottom (second) part of a 6D screw vector. .. py:function:: spatial_jacobian(S: Array[Vector[6,Float]], joint_parents: Array[int32], joint_qd_start: Array[int32], joint_start: int32, joint_count: int32, J_start: int32, J_out: Array[Float]) -> None .. py:function:: spatial_mass(I_s: Array[Matrix[6,6,Float]], joint_start: int32, joint_count: int32, M_start: int32, M: Array[Float]) -> None Utility --------------- .. py:function:: mlp(weights: Array[float32], bias: Array[float32], activation: Callable, index: int32, x: Array[float32], out: Array[float32]) -> None Evaluate a multi-layer perceptron (MLP) layer in the form: ``out = act(weights*x + bias)``. :param weights: A layer's network weights with dimensions ``(m, n)``. :param bias: An array with dimensions ``(n)``. :param activation: A ``wp.func`` function that takes a single scalar float as input and returns a scalar float as output :param index: The batch item to process, typically each thread will process one item in the batch, in which case index should be ``wp.tid()`` :param x: The feature matrix with dimensions ``(n, b)`` :param out: The network output with dimensions ``(m, b)`` :note: Feature and output matrices are transposed compared to some other frameworks such as PyTorch. All matrices are assumed to be stored in flattened row-major memory layout (NumPy default). .. py:function:: printf() -> None Allows printing formatted strings using C-style format specifiers. .. py:function:: print(value: Any) -> None Print variable to stdout .. py:function:: breakpoint() -> None Debugger breakpoint .. py:function:: tid() -> int Return the current thread index for a 1D kernel launch. Note that this is the *global* index of the thread in the range [0, dim) where dim is the parameter passed to kernel launch. This function may not be called from user-defined Warp functions. .. py:function:: tid() -> Tuple[int, int] :noindex: :nocontentsentry: Return the current thread indices for a 2D kernel launch. Use ``i,j = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid. This function may not be called from user-defined Warp functions. .. py:function:: tid() -> Tuple[int, int, int] :noindex: :nocontentsentry: Return the current thread indices for a 3D kernel launch. Use ``i,j,k = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid. This function may not be called from user-defined Warp functions. .. py:function:: tid() -> Tuple[int, int, int, int] :noindex: :nocontentsentry: Return the current thread indices for a 4D kernel launch. Use ``i,j,k,l = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid. This function may not be called from user-defined Warp functions. .. py:function:: select(cond: bool, arg1: Any, arg2: Any) Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: int8, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: uint8, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: int16, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: uint16, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: int32, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: uint32, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: int64, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(cond: uint64, arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2`` .. py:function:: select(arr: Array[Any], arg1: Any, arg2: Any) :noindex: :nocontentsentry: Select between two arguments, if ``arr`` is null then return ``arg1``, otherwise return ``arg2`` .. py:function:: atomic_add(a: Array[Any], i: int32, value: Any) Atomically add ``value`` onto ``a[i]``. .. py:function:: atomic_add(a: Array[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j]``. .. py:function:: atomic_add(a: Array[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j,k]``. .. py:function:: atomic_add(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j,k,l]``. .. py:function:: atomic_add(a: FabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i]``. .. py:function:: atomic_add(a: FabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j]``. .. py:function:: atomic_add(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j,k]``. .. py:function:: atomic_add(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j,k,l]``. .. py:function:: atomic_add(a: IndexedFabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i]``. .. py:function:: atomic_add(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j]``. .. py:function:: atomic_add(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j,k]``. .. py:function:: atomic_add(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Atomically add ``value`` onto ``a[i,j,k,l]``. .. py:function:: atomic_sub(a: Array[Any], i: int32, value: Any) Atomically subtract ``value`` onto ``a[i]``. .. py:function:: atomic_sub(a: Array[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j]``. .. py:function:: atomic_sub(a: Array[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j,k]``. .. py:function:: atomic_sub(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j,k,l]``. .. py:function:: atomic_sub(a: FabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i]``. .. py:function:: atomic_sub(a: FabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j]``. .. py:function:: atomic_sub(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j,k]``. .. py:function:: atomic_sub(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j,k,l]``. .. py:function:: atomic_sub(a: IndexedFabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i]``. .. py:function:: atomic_sub(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j]``. .. py:function:: atomic_sub(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j,k]``. .. py:function:: atomic_sub(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Atomically subtract ``value`` onto ``a[i,j,k,l]``. .. py:function:: atomic_min(a: Array[Any], i: int32, value: Any) Compute the minimum of ``value`` and ``a[i]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: Array[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: Array[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: FabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: FabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: IndexedFabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_min(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: Array[Any], i: int32, value: Any) Compute the maximum of ``value`` and ``a[i]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: Array[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: Array[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: FabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: FabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: IndexedFabricArray[Any], i: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: atomic_max(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any) :noindex: :nocontentsentry: Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array. .. note:: The operation is only atomic on a per-component basis for vectors and matrices. .. py:function:: lerp(a: Float, b: Float, t: Float) -> Float Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t`` .. py:function:: lerp(a: Vector[Any,Float], b: Vector[Any,Float], t: Float) -> Vector[Any,Float] :noindex: :nocontentsentry: Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t`` .. py:function:: lerp(a: Matrix[Any,Any,Float], b: Matrix[Any,Any,Float], t: Float) -> Matrix[Any,Any,Float] :noindex: :nocontentsentry: Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t`` .. py:function:: lerp(a: Quaternion[Float], b: Quaternion[Float], t: Float) -> Quaternion[Float] :noindex: :nocontentsentry: Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t`` .. py:function:: lerp(a: Transformation[Float], b: Transformation[Float], t: Float) -> Transformation[Float] :noindex: :nocontentsentry: Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t`` .. py:function:: smoothstep(edge0: Float, edge1: Float, x: Float) -> Float Smoothly interpolate between two values ``edge0`` and ``edge1`` using a factor ``x``, and return a result between 0 and 1 using a cubic Hermite interpolation after clamping. .. py:function:: expect_near(arg1: Float, arg2: Float, tolerance: Float) -> None Prints an error to stdout if ``arg1`` and ``arg2`` are not closer than tolerance in magnitude .. py:function:: expect_near(arg1: vec3f, arg2: vec3f, tolerance: float32) -> None :noindex: :nocontentsentry: Prints an error to stdout if any element of ``arg1`` and ``arg2`` are not closer than tolerance in magnitude Geometry --------------- .. py:function:: bvh_query_aabb(id: uint64, lower: vec3f, upper: vec3f) -> bvh_query_t Construct an axis-aligned bounding box query against a BVH object. This query can be used to iterate over all bounds inside a BVH. :param id: The BVH identifier :param lower: The lower bound of the bounding box in BVH space :param upper: The upper bound of the bounding box in BVH space .. py:function:: bvh_query_ray(id: uint64, start: vec3f, dir: vec3f) -> bvh_query_t Construct a ray query against a BVH object. This query can be used to iterate over all bounds that intersect the ray. :param id: The BVH identifier :param start: The start of the ray in BVH space :param dir: The direction of the ray in BVH space .. py:function:: bvh_query_next(query: bvh_query_t, index: int32) -> bool Move to the next bound returned by the query. The index of the current bound is stored in ``index``, returns ``False`` if there are no more overlapping bound. .. py:function:: mesh_query_point(id: uint64, point: vec3f, max_dist: float32) -> mesh_query_point_t Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space. Identifies the sign of the distance using additional ray-casts to determine if the point is inside or outside. This method is relatively robust, but does increase computational cost. See below for additional sign determination methods. :param id: The mesh identifier :param point: The point in space to query :param max_dist: Mesh faces above this distance will not be considered by the query .. py:function:: mesh_query_point_no_sign(id: uint64, point: vec3f, max_dist: float32) -> mesh_query_point_t Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space. This method does not compute the sign of the point (inside/outside) which makes it faster than other point query methods. :param id: The mesh identifier :param point: The point in space to query :param max_dist: Mesh faces above this distance will not be considered by the query .. py:function:: mesh_query_furthest_point_no_sign(id: uint64, point: vec3f, min_dist: float32) -> mesh_query_point_t Computes the furthest point on the mesh with identifier `id` to the given point in space. This method does not compute the sign of the point (inside/outside). :param id: The mesh identifier :param point: The point in space to query :param min_dist: Mesh faces below this distance will not be considered by the query .. py:function:: mesh_query_point_sign_normal(id: uint64, point: vec3f, max_dist: float32, epsilon: float32) -> mesh_query_point_t Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space. Identifies the sign of the distance (inside/outside) using the angle-weighted pseudo normal. This approach to sign determination is robust for well conditioned meshes that are watertight and non-self intersecting. It is also comparatively fast to compute. :param id: The mesh identifier :param point: The point in space to query :param max_dist: Mesh faces above this distance will not be considered by the query :param epsilon: Epsilon treating distance values as equal, when locating the minimum distance vertex/face/edge, as a fraction of the average edge length, also for treating closest point as being on edge/vertex default 1e-3 .. py:function:: mesh_query_point_sign_winding_number(id: uint64, point: vec3f, max_dist: float32, accuracy: float32, threshold: float32) -> mesh_query_point_t Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given point in space. Identifies the sign using the winding number of the mesh relative to the query point. This method of sign determination is robust for poorly conditioned meshes and provides a smooth approximation to sign even when the mesh is not watertight. This method is the most robust and accurate of the sign determination meshes but also the most expensive. .. note:: The :class:`Mesh` object must be constructed with ``support_winding_number=True`` for this method to return correct results. :param id: The mesh identifier :param point: The point in space to query :param max_dist: Mesh faces above this distance will not be considered by the query :param accuracy: Accuracy for computing the winding number with fast winding number method utilizing second-order dipole approximation, default 2.0 :param threshold: The threshold of the winding number to be considered inside, default 0.5 .. py:function:: mesh_query_ray(id: uint64, start: vec3f, dir: vec3f, max_t: float32) -> mesh_query_ray_t Computes the closest ray hit on the :class:`Mesh` with identifier ``id``. :param id: The mesh identifier :param start: The start point of the ray :param dir: The ray direction (should be normalized) :param max_t: The maximum distance along the ray to check for intersections .. py:function:: mesh_query_aabb(id: uint64, lower: vec3f, upper: vec3f) -> mesh_query_aabb_t Construct an axis-aligned bounding box query against a :class:`Mesh`. This query can be used to iterate over all triangles inside a volume. :param id: The mesh identifier :param lower: The lower bound of the bounding box in mesh space :param upper: The upper bound of the bounding box in mesh space .. py:function:: mesh_query_aabb_next(query: mesh_query_aabb_t, index: int32) -> bool Move to the next triangle overlapping the query bounding box. The index of the current face is stored in ``index``, returns ``False`` if there are no more overlapping triangles. .. py:function:: mesh_eval_position(id: uint64, face: int32, bary_u: float32, bary_v: float32) -> vec3f Evaluates the position on the :class:`Mesh` given a face index and barycentric coordinates. .. py:function:: mesh_eval_velocity(id: uint64, face: int32, bary_u: float32, bary_v: float32) -> vec3f Evaluates the velocity on the :class:`Mesh` given a face index and barycentric coordinates. .. py:function:: hash_grid_query(id: uint64, point: vec3f, max_dist: float32) -> hash_grid_query_t Construct a point query against a :class:`HashGrid`. This query can be used to iterate over all neighboring point within a fixed radius from the query point. .. py:function:: hash_grid_query_next(query: hash_grid_query_t, index: int32) -> bool Move to the next point in the hash grid query. The index of the current neighbor is stored in ``index``, returns ``False`` if there are no more neighbors. .. py:function:: hash_grid_point_id(id: uint64, index: int32) -> int Return the index of a point in the :class:`HashGrid`. This can be used to reorder threads such that grid traversal occurs in a spatially coherent order. Returns -1 if the :class:`HashGrid` has not been reserved. .. py:function:: intersect_tri_tri(v0: vec3f, v1: vec3f, v2: vec3f, u0: vec3f, u1: vec3f, u2: vec3f) -> int Tests for intersection between two triangles (v0, v1, v2) and (u0, u1, u2) using Moller's method. Returns > 0 if triangles intersect. .. py:function:: mesh_get(id: uint64) -> Mesh Retrieves the mesh given its index. [1]_ .. py:function:: mesh_eval_face_normal(id: uint64, face: int32) -> vec3f Evaluates the face normal the mesh given a face index. .. py:function:: mesh_get_point(id: uint64, index: int32) -> vec3f Returns the point of the mesh given a index. .. py:function:: mesh_get_velocity(id: uint64, index: int32) -> vec3f Returns the velocity of the mesh given a index. .. py:function:: mesh_get_index(id: uint64, index: int32) -> int Returns the point-index of the mesh given a face-vertex index. .. py:function:: closest_point_edge_edge(p1: vec3f, q1: vec3f, p2: vec3f, q2: vec3f, epsilon: float32) -> vec3f Finds the closest points between two edges. Returns barycentric weights to the points on each edge, as well as the closest distance between the edges. :param p1: First point of first edge :param q1: Second point of first edge :param p2: First point of second edge :param q2: Second point of second edge :param epsilon: Zero tolerance for determining if points in an edge are degenerate. :param out: vec3 output containing (s,t,d), where `s` in [0,1] is the barycentric weight for the first edge, `t` is the barycentric weight for the second edge, and `d` is the distance between the two edges at these two closest points. Volumes --------------- .. py:function:: volume_sample(id: uint64, uvw: vec3f, sampling_mode: int32, dtype: Any) Sample the volume of type `dtype` given by ``id`` at the volume local-space point ``uvw``. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.` .. py:function:: volume_sample_grad(id: uint64, uvw: vec3f, sampling_mode: int32, grad: Any, dtype: Any) Sample the volume given by ``id`` and its gradient at the volume local-space point ``uvw``. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.` .. py:function:: volume_lookup(id: uint64, i: int32, j: int32, k: int32, dtype: Any) Returns the value of voxel with coordinates ``i``, ``j``, ``k`` for a volume of type type `dtype`. If the voxel at this index does not exist, this function returns the background value. .. py:function:: volume_store(id: uint64, i: int32, j: int32, k: int32, value: Any) Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``. .. py:function:: volume_sample_f(id: uint64, uvw: vec3f, sampling_mode: int32) -> float Sample the volume given by ``id`` at the volume local-space point ``uvw``. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.` .. py:function:: volume_sample_grad_f(id: uint64, uvw: vec3f, sampling_mode: int32, grad: vec3f) -> float Sample the volume and its gradient given by ``id`` at the volume local-space point ``uvw``. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.` .. py:function:: volume_lookup_f(id: uint64, i: int32, j: int32, k: int32) -> float Returns the value of voxel with coordinates ``i``, ``j``, ``k``. If the voxel at this index does not exist, this function returns the background value .. py:function:: volume_store_f(id: uint64, i: int32, j: int32, k: int32, value: float32) -> None Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``. .. py:function:: volume_sample_v(id: uint64, uvw: vec3f, sampling_mode: int32) -> vec3f Sample the vector volume given by ``id`` at the volume local-space point ``uvw``. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.` .. py:function:: volume_lookup_v(id: uint64, i: int32, j: int32, k: int32) -> vec3f Returns the vector value of voxel with coordinates ``i``, ``j``, ``k``. If the voxel at this index does not exist, this function returns the background value. .. py:function:: volume_store_v(id: uint64, i: int32, j: int32, k: int32, value: vec3f) -> None Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``. .. py:function:: volume_sample_i(id: uint64, uvw: vec3f) -> int Sample the :class:`int32` volume given by ``id`` at the volume local-space point ``uvw``. .. py:function:: volume_lookup_i(id: uint64, i: int32, j: int32, k: int32) -> int Returns the :class:`int32` value of voxel with coordinates ``i``, ``j``, ``k``. If the voxel at this index does not exist, this function returns the background value. .. py:function:: volume_store_i(id: uint64, i: int32, j: int32, k: int32, value: int32) -> None Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``. .. py:function:: volume_sample_index(id: uint64, uvw: vec3f, sampling_mode: int32, voxel_data: Array[Any], background: Any) Sample the volume given by ``id`` at the volume local-space point ``uvw``. Values for allocated voxels are read from the ``voxel_data`` array, and `background` is used as the value of non-existing voxels. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR`. This function is available for both index grids and classical volumes. .. py:function:: volume_sample_grad_index(id: uint64, uvw: vec3f, sampling_mode: int32, voxel_data: Array[Any], background: Any, grad: Any) Sample the volume given by ``id`` and its gradient at the volume local-space point ``uvw``. Values for allocated voxels are read from the ``voxel_data`` array, and `background` is used as the value of non-existing voxels. Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR`. This function is available for both index grids and classical volumes. .. py:function:: volume_lookup_index(id: uint64, i: int32, j: int32, k: int32) -> int32 Returns the index associated to the voxel with coordinates ``i``, ``j``, ``k``. If the voxel at this index does not exist, this function returns -1. This function is available for both index grids and classical volumes. .. py:function:: volume_index_to_world(id: uint64, uvw: vec3f) -> vec3f Transform a point ``uvw`` defined in volume index space to world space given the volume's intrinsic affine transformation. .. py:function:: volume_world_to_index(id: uint64, xyz: vec3f) -> vec3f Transform a point ``xyz`` defined in volume world space to the volume's index space given the volume's intrinsic affine transformation. .. py:function:: volume_index_to_world_dir(id: uint64, uvw: vec3f) -> vec3f Transform a direction ``uvw`` defined in volume index space to world space given the volume's intrinsic affine transformation. .. py:function:: volume_world_to_index_dir(id: uint64, xyz: vec3f) -> vec3f Transform a direction ``xyz`` defined in volume world space to the volume's index space given the volume's intrinsic affine transformation. Random --------------- .. py:function:: rand_init(seed: int32) -> uint32 Initialize a new random number generator given a user-defined seed. Returns a 32-bit integer representing the RNG state. .. py:function:: rand_init(seed: int32, offset: int32) -> uint32 :noindex: :nocontentsentry: Initialize a new random number generator given a user-defined seed and an offset. This alternative constructor can be useful in parallel programs, where a kernel as a whole should share a seed, but each thread should generate uncorrelated values. In this case usage should be ``r = rand_init(seed, tid)`` .. py:function:: randi(state: uint32) -> int Return a random integer in the range [0, 2^32). .. py:function:: randi(state: uint32, min: int32, max: int32) -> int :noindex: :nocontentsentry: Return a random integer between [min, max). .. py:function:: randf(state: uint32) -> float Return a random float between [0.0, 1.0). .. py:function:: randf(state: uint32, min: float32, max: float32) -> float :noindex: :nocontentsentry: Return a random float between [min, max). .. py:function:: randn(state: uint32) -> float Sample a normal distribution. .. py:function:: sample_cdf(state: uint32, cdf: Array[float32]) -> int Inverse-transform sample a cumulative distribution function. .. py:function:: sample_triangle(state: uint32) -> vec2f Uniformly sample a triangle. Returns sample barycentric coordinates. .. py:function:: sample_unit_ring(state: uint32) -> vec2f Uniformly sample a ring in the xy plane. .. py:function:: sample_unit_disk(state: uint32) -> vec2f Uniformly sample a disk in the xy plane. .. py:function:: sample_unit_sphere_surface(state: uint32) -> vec3f Uniformly sample a unit sphere surface. .. py:function:: sample_unit_sphere(state: uint32) -> vec3f Uniformly sample a unit sphere. .. py:function:: sample_unit_hemisphere_surface(state: uint32) -> vec3f Uniformly sample a unit hemisphere surface. .. py:function:: sample_unit_hemisphere(state: uint32) -> vec3f Uniformly sample a unit hemisphere. .. py:function:: sample_unit_square(state: uint32) -> vec2f Uniformly sample a unit square. .. py:function:: sample_unit_cube(state: uint32) -> vec3f Uniformly sample a unit cube. .. py:function:: poisson(state: uint32, lam: float32) -> uint32 Generate a random sample from a Poisson distribution. :param state: RNG state :param lam: The expected value of the distribution .. py:function:: noise(state: uint32, x: float32) -> float Non-periodic Perlin-style noise in 1D. .. py:function:: noise(state: uint32, xy: vec2f) -> float :noindex: :nocontentsentry: Non-periodic Perlin-style noise in 2D. .. py:function:: noise(state: uint32, xyz: vec3f) -> float :noindex: :nocontentsentry: Non-periodic Perlin-style noise in 3D. .. py:function:: noise(state: uint32, xyzt: vec4f) -> float :noindex: :nocontentsentry: Non-periodic Perlin-style noise in 4D. .. py:function:: pnoise(state: uint32, x: float32, px: int32) -> float Periodic Perlin-style noise in 1D. .. py:function:: pnoise(state: uint32, xy: vec2f, px: int32, py: int32) -> float :noindex: :nocontentsentry: Periodic Perlin-style noise in 2D. .. py:function:: pnoise(state: uint32, xyz: vec3f, px: int32, py: int32, pz: int32) -> float :noindex: :nocontentsentry: Periodic Perlin-style noise in 3D. .. py:function:: pnoise(state: uint32, xyzt: vec4f, px: int32, py: int32, pz: int32, pt: int32) -> float :noindex: :nocontentsentry: Periodic Perlin-style noise in 4D. .. py:function:: curlnoise(state: uint32, xy: vec2f, octaves: uint32, lacunarity: float32, gain: float32) -> vec2f Divergence-free vector field based on the gradient of a Perlin noise function. [1]_ .. py:function:: curlnoise(state: uint32, xyz: vec3f, octaves: uint32, lacunarity: float32, gain: float32) -> vec3f :noindex: :nocontentsentry: Divergence-free vector field based on the curl of three Perlin noise functions. [1]_ .. py:function:: curlnoise(state: uint32, xyzt: vec4f, octaves: uint32, lacunarity: float32, gain: float32) -> vec3f :noindex: :nocontentsentry: Divergence-free vector field based on the curl of three Perlin noise functions. [1]_ Other --------------- .. py:function:: lower_bound(arr: Array[Scalar], value: Scalar) -> int Search a sorted array ``arr`` for the closest element greater than or equal to ``value``. .. py:function:: lower_bound(arr: Array[Scalar], arr_begin: int32, arr_end: int32, value: Scalar) -> int :noindex: :nocontentsentry: Search a sorted array ``arr`` in the range [arr_begin, arr_end) for the closest element greater than or equal to ``value``. .. py:function:: bit_and(x: Int, y: Int) -> Int .. py:function:: bit_or(x: Int, y: Int) -> Int .. py:function:: bit_xor(x: Int, y: Int) -> Int .. py:function:: lshift(x: Int, y: Int) -> Int .. py:function:: rshift(x: Int, y: Int) -> Int .. py:function:: invert(x: Int) -> Int Operators --------------- .. py:function:: add(x: Scalar, y: Scalar) -> Scalar .. py:function:: add(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: add(x: Quaternion[Scalar], y: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: add(x: Matrix[Any,Any,Scalar], y: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: add(x: Transformation[Scalar], y: Transformation[Scalar]) -> Transformation[Scalar] :noindex: :nocontentsentry: .. py:function:: sub(x: Scalar, y: Scalar) -> Scalar .. py:function:: sub(x: Vector[Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: sub(x: Matrix[Any,Any,Scalar], y: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: sub(x: Quaternion[Scalar], y: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: sub(x: Transformation[Scalar], y: Transformation[Scalar]) -> Transformation[Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Scalar, y: Scalar) -> Scalar .. py:function:: mul(x: Vector[Any,Scalar], y: Scalar) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Scalar, y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Quaternion[Scalar], y: Scalar) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Scalar, y: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Quaternion[Scalar], y: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Scalar, y: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Matrix[Any,Any,Scalar], y: Scalar) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Matrix[Any,Any,Scalar], y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Vector[Any,Scalar], y: Matrix[Any,Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Matrix[Any,Any,Scalar], y: Matrix[Any,Any,Scalar]) :noindex: :nocontentsentry: .. py:function:: mul(x: Transformation[Scalar], y: Transformation[Scalar]) -> Transformation[Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Scalar, y: Transformation[Scalar]) -> Transformation[Scalar] :noindex: :nocontentsentry: .. py:function:: mul(x: Transformation[Scalar], y: Scalar) -> Transformation[Scalar] :noindex: :nocontentsentry: .. py:function:: mod(x: Scalar, y: Scalar) -> Scalar .. py:function:: div(x: Scalar, y: Scalar) -> Scalar .. py:function:: div(x: Vector[Any,Scalar], y: Scalar) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: div(x: Scalar, y: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: div(x: Matrix[Any,Any,Scalar], y: Scalar) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: div(x: Scalar, y: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: div(x: Quaternion[Scalar], y: Scalar) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: div(x: Scalar, y: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: floordiv(x: Scalar, y: Scalar) -> Scalar .. py:function:: pos(x: Scalar) -> Scalar .. py:function:: pos(x: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: pos(x: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: pos(x: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: neg(x: Scalar) -> Scalar .. py:function:: neg(x: Vector[Any,Scalar]) -> Vector[Any,Scalar] :noindex: :nocontentsentry: .. py:function:: neg(x: Quaternion[Scalar]) -> Quaternion[Scalar] :noindex: :nocontentsentry: .. py:function:: neg(x: Matrix[Any,Any,Scalar]) -> Matrix[Any,Any,Scalar] :noindex: :nocontentsentry: .. py:function:: unot(b: bool) -> bool .. py:function:: unot(b: int8) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: uint8) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: int16) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: uint16) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: int32) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: uint32) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: int64) -> bool :noindex: :nocontentsentry: .. py:function:: unot(b: uint64) -> bool :noindex: :nocontentsentry: .. py:function:: unot(a: Array[Any]) -> bool :noindex: :nocontentsentry: .. rubric:: Footnotes .. [1] Function gradients have not been implemented for backpropagation.
63,036
reStructuredText
28.224386
238
0.669316
NVIDIA/warp/docs/modules/runtime.rst
Runtime Reference ================= .. currentmodule:: warp This section describes the Warp Python runtime API, how to manage memory, launch kernels, and high-level functionality for dealing with objects such as meshes and volumes. The APIs described in this section are intended to be used at the *Python Scope* and run inside the CPython interpreter. For a comprehensive list of functions available at the *Kernel Scope*, please see the :doc:`functions` section. Kernels ------- Kernels are launched with the :func:`wp.launch() <launch>` function on a specific device (CPU/GPU):: wp.launch(simple_kernel, dim=1024, inputs=[a, b, c], device="cuda") Kernels may be launched with multi-dimensional grid bounds. In this case threads are not assigned a single index, but a coordinate in an n-dimensional grid, e.g.:: wp.launch(complex_kernel, dim=(128, 128, 3), ...) Launches a 3D grid of threads with dimension 128 x 128 x 3. To retrieve the 3D index for each thread use the following syntax:: i,j,k = wp.tid() .. note:: Currently kernels launched on CPU devices will be executed in serial. Kernels launched on CUDA devices will be launched in parallel with a fixed block-size. .. note:: Note that all the kernel inputs must live on the target device, or a runtime exception will be raised. .. autofunction:: launch .. _Runtime Kernel Creation: Runtime Kernel Creation ####################### It is often desirable to specialize kernels for different types, constants, or functions at runtime. We can achieve this through the use of runtime kernel specialization using Python closures. For example, we might require a variety of kernels that execute particular functions for each item in an array. We might also want this function call to be valid for a variety of data types. Making use of closure and generics, we can generate these kernels using a single kernel definition:: def make_kernel(func, dtype): def closure_kernel_fn(data: wp.array(dtype=dtype), out: wp.array(dtype=dtype)): tid = wp.tid() out[tid] = func(data[tid]) return wp.Kernel(closure_kernel_fn) In practice, we might use our kernel generator, ``make_kernel()`` as follows:: @wp.func def sqr(x: Any) -> Any: return x * x @wp.func def cube(x: Any) -> Any: return sqr(x) * x sqr_float = make_kernel(sqr, wp.float32) cube_double = make_kernel(cube, wp.float64) arr = [1.0, 2.0, 3.0] N = len(arr) data_float = wp.array(arr, dtype=wp.float32, device=device) data_double = wp.array(arr, dtype=wp.float64, device=device) out_float = wp.zeros(N, dtype=wp.float32, device=device) out_double = wp.zeros(N, dtype=wp.float64, device=device) wp.launch(sqr_float, dim=N, inputs=[data_float], outputs=[out_float], device=device) wp.launch(cube_double, dim=N, inputs=[data_double], outputs=[out_double], device=device) We can specialize kernel definitions over Warp constants similarly. The following generates kernels that add a specified constant to a generic-typed array value:: def make_add_kernel(key, constant): def closure_kernel_fn(data: wp.array(dtype=Any), out: wp.array(dtype=Any)): tid = wp.tid() out[tid] = data[tid] + constant return wp.Kernel(closure_kernel_fn, key=key) add_ones_int = make_add_kernel("add_one", wp.constant(1)) add_ones_vec3 = make_add_kernel("add_ones_vec3", wp.constant(wp.vec3(1.0, 1.0, 1.0))) a = wp.zeros(2, dtype=int) b = wp.zeros(2, dtype=wp.vec3) a_out = wp.zeros_like(a) b_out = wp.zeros_like(b) wp.launch(add_ones_int, dim=a.size, inputs=[a], outputs=[a_out], device=device) wp.launch(add_ones_vec3, dim=b.size, inputs=[b], outputs=[b_out], device=device) .. _Arrays: Arrays ------ Arrays are the fundamental memory abstraction in Warp; they are created through the following global constructors: :: wp.empty(shape=1024, dtype=wp.vec3, device="cpu") wp.zeros(shape=1024, dtype=float, device="cuda") wp.full(shape=1024, value=10, dtype=int, device="cuda") Arrays can also be constructed directly from ``numpy`` ndarrays as follows: :: r = np.random.rand(1024) # copy to Warp owned array a = wp.array(r, dtype=float, device="cpu") # return a Warp array wrapper around the NumPy data (zero-copy) a = wp.array(r, dtype=float, copy=False, device="cpu") # return a Warp copy of the array data on the GPU a = wp.array(r, dtype=float, device="cuda") Note that for multi-dimensional data the ``dtype`` parameter must be specified explicitly, e.g.: :: r = np.random.rand((1024, 3)) # initialize as an array of vec3 objects a = wp.array(r, dtype=wp.vec3, device="cuda") If the shapes are incompatible, an error will be raised. Warp arrays can also be constructed from objects that define the ``__cuda_array_interface__`` attribute. For example: :: import cupy import warp as wp device = wp.get_cuda_device() r = cupy.arange(10) # return a Warp array wrapper around the cupy data (zero-copy) a = wp.array(r, device=device) Arrays can be moved between devices using the ``array.to()`` method: :: host_array = wp.array(a, dtype=float, device="cpu") # allocate and copy to GPU device_array = host_array.to("cuda") Additionally, arrays can be copied directly between memory spaces: :: src_array = wp.array(a, dtype=float, device="cpu") dest_array = wp.empty_like(host_array) # copy from source CPU buffer to GPU wp.copy(dest_array, src_array) .. autoclass:: array :members: :undoc-members: :exclude-members: vars Multi-dimensional Arrays ######################## Multi-dimensional arrays can be constructed by passing a tuple of sizes for each dimension, e.g.: the following constructs a 2d array of size 1024x16:: wp.zeros(shape=(1024, 16), dtype=float, device="cuda") When passing multi-dimensional arrays to kernels users must specify the expected array dimension inside the kernel signature, e.g. to pass a 2d array to a kernel the number of dims is specified using the ``ndim=2`` parameter:: @wp.kernel def test(input: wp.array(dtype=float, ndim=2)): Type-hint helpers are provided for common array sizes, e.g.: ``array2d()``, ``array3d()``, which are equivalent to calling ``array(..., ndim=2)```, etc. To index a multi-dimensional array use a the following kernel syntax:: # returns a float from the 2d array value = input[i,j] To create an array slice use the following syntax, where the number of indices is less than the array dimensions:: # returns an 1d array slice representing a row of the 2d array row = input[i] Slice operators can be concatenated, e.g.: ``s = array[i][j][k]``. Slices can be passed to ``wp.func`` user functions provided the function also declares the expected array dimension. Currently only single-index slicing is supported. .. note:: Currently Warp limits arrays to 4 dimensions maximum. This is in addition to the contained datatype, which may be 1-2 dimensional for vector and matrix types such as ``vec3``, and ``mat33``. The following construction methods are provided for allocating zero-initialized and empty (non-initialized) arrays: .. autofunction:: zeros .. autofunction:: zeros_like .. autofunction:: ones .. autofunction:: ones_like .. autofunction:: full .. autofunction:: full_like .. autofunction:: empty .. autofunction:: empty_like .. autofunction:: copy .. autofunction:: clone Matrix Multiplication ##################### Warp 2D array multiplication is built on NVIDIA's `CUTLASS <https://github.com/NVIDIA/cutlass>`_ library, which enables fast matrix multiplication of large arrays on the GPU. If no GPU is detected, matrix multiplication falls back to Numpy's implementation on the CPU. Matrix multiplication is fully differentiable, and can be recorded on the tape like so:: tape = wp.Tape() with tape: wp.matmul(A, B, C, D, device=device) wp.launch(loss_kernel, dim=(m, n), inputs=[D, loss], device=device) tape.backward(loss=loss) A_grad = A.grad.numpy() Using the ``@`` operator (``D = A @ B``) will default to the same CUTLASS algorithm used in ``wp.matmul``. .. autofunction:: matmul .. autofunction:: batched_matmul Data Types ---------- Scalar Types ############ The following scalar storage types are supported for array structures: +---------+------------------------+ | bool | boolean | +---------+------------------------+ | int8 | signed byte | +---------+------------------------+ | uint8 | unsigned byte | +---------+------------------------+ | int16 | signed short | +---------+------------------------+ | uint16 | unsigned short | +---------+------------------------+ | int32 | signed integer | +---------+------------------------+ | uint32 | unsigned integer | +---------+------------------------+ | int64 | signed long integer | +---------+------------------------+ | uint64 | unsigned long integer | +---------+------------------------+ | float16 | half-precision float | +---------+------------------------+ | float32 | single-precision float | +---------+------------------------+ | float64 | double-precision float | +---------+------------------------+ Warp supports ``float`` and ``int`` as aliases for ``wp.float32`` and ``wp.int32`` respectively. .. _vec: Vectors ####### Warp provides built-in math and geometry types for common simulation and graphics problems. A full reference for operators and functions for these types is available in the :doc:`/modules/functions`. Warp supports vectors of numbers with an arbitrary length/numeric type. The built-in concrete types are as follows: +-----------------------+------------------------------------------------+ | vec2 vec3 vec4 | 2D, 3D, 4D vector of single-precision floats | +-----------------------+------------------------------------------------+ | vec2b vec3b vec4b | 2D, 3D, 4D vector of signed bytes | +-----------------------+------------------------------------------------+ | vec2ub vec3ub vec4ub | 2D, 3D, 4D vector of unsigned bytes | +-----------------------+------------------------------------------------+ | vec2s vec3s vec4s | 2D, 3D, 4D vector of signed shorts | +-----------------------+------------------------------------------------+ | vec2us vec3us vec4us | 2D, 3D, 4D vector of unsigned shorts | +-----------------------+------------------------------------------------+ | vec2i vec3i vec4i | 2D, 3D, 4D vector of signed integers | +-----------------------+------------------------------------------------+ | vec2ui vec3ui vec4ui | 2D, 3D, 4D vector of unsigned integers | +-----------------------+------------------------------------------------+ | vec2l vec3l vec4l | 2D, 3D, 4D vector of signed long integers | +-----------------------+------------------------------------------------+ | vec2ul vec3ul vec4ul | 2D, 3D, 4D vector of unsigned long integers | +-----------------------+------------------------------------------------+ | vec2h vec3h vec4h | 2D, 3D, 4D vector of half-precision floats | +-----------------------+------------------------------------------------+ | vec2f vec3f vec4f | 2D, 3D, 4D vector of single-precision floats | +-----------------------+------------------------------------------------+ | vec2d vec3d vec4d | 2D, 3D, 4D vector of double-precision floats | +-----------------------+------------------------------------------------+ | spatial_vector | 6D vector of single-precision floats | +-----------------------+------------------------------------------------+ | spatial_vectorf | 6D vector of single-precision floats | +-----------------------+------------------------------------------------+ | spatial_vectord | 6D vector of double-precision floats | +-----------------------+------------------------------------------------+ | spatial_vectorh | 6D vector of half-precision floats | +-----------------------+------------------------------------------------+ Vectors support most standard linear algebra operations, e.g.: :: @wp.kernel def compute( ... ): # basis vectors a = wp.vec3(1.0, 0.0, 0.0) b = wp.vec3(0.0, 1.0, 0.0) # take the cross product c = wp.cross(a, b) # compute r = wp.dot(c, c) ... It's possible to declare additional vector types with different lengths and data types. This is done in outside of kernels in *Python scope* using ``warp.types.vector()``, for example: :: # declare a new vector type for holding 5 double precision floats: vec5d = wp.types.vector(length=5, dtype=wp.float64) Once declared, the new type can be used when allocating arrays or inside kernels: :: # create an array of vec5d arr = wp.zeros(10, dtype=vec5d) # use inside a kernel @wp.kernel def compute( ... ): # zero initialize a custom named vector type v = vec5d() ... # component-wise initialize a named vector type v = vec5d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0), wp.float64(4.0), wp.float64(5.0)) ... In addition, it's possible to directly create *anonymously* typed instances of these vectors without declaring their type in advance. In this case the type will be inferred by the constructor arguments. For example: :: @wp.kernel def compute( ... ): # zero initialize vector of 5 doubles: v = wp.vector(dtype=wp.float64, length=5) # scalar initialize a vector of 5 doubles to the same value: v = wp.vector(wp.float64(1.0), length=5) # component-wise initialize a vector of 5 doubles v = wp.vector(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0), wp.float64(4.0), wp.float64(5.0)) These can be used with all the standard vector arithmetic operators, e.g.: ``+``, ``-``, scalar multiplication, and can also be transformed using matrices with compatible dimensions, potentially returning vectors with a different length. .. _mat: Matrices ######## Matrices with arbitrary shapes/numeric types are also supported. The built-in concrete matrix types are as follows: +--------------------------+-------------------------------------------------+ | mat22 mat33 mat44 | 2x2, 3x3, 4x4 matrix of single-precision floats | +--------------------------+-------------------------------------------------+ | mat22f mat33f mat44f | 2x2, 3x3, 4x4 matrix of single-precision floats | +--------------------------+-------------------------------------------------+ | mat22d mat33d mat44d | 2x2, 3x3, 4x4 matrix of double-precision floats | +--------------------------+-------------------------------------------------+ | mat22h mat33h mat44h | 2x2, 3x3, 4x4 matrix of half-precision floats | +--------------------------+-------------------------------------------------+ | spatial_matrix | 6x6 matrix of single-precision floats | +--------------------------+-------------------------------------------------+ | spatial_matrixf | 6x6 matrix of single-precision floats | +--------------------------+-------------------------------------------------+ | spatial_matrixd | 6x6 matrix of double-precision floats | +--------------------------+-------------------------------------------------+ | spatial_matrixh | 6x6 matrix of half-precision floats | +--------------------------+-------------------------------------------------+ Matrices are stored in row-major format and support most standard linear algebra operations: :: @wp.kernel def compute( ... ): # initialize matrix m = wp.mat22(1.0, 2.0, 3.0, 4.0) # compute inverse minv = wp.inverse(m) # transform vector v = minv * wp.vec2(0.5, 0.3) ... In a similar manner to vectors, it's possible to declare new matrix types with arbitrary shapes and data types using ``wp.types.matrix()``, for example: :: # declare a new 3x2 half precision float matrix type: mat32h = wp.types.matrix(shape=(3,2), dtype=wp.float64) # create an array of this type a = wp.zeros(10, dtype=mat32h) These can be used inside a kernel:: @wp.kernel def compute( ... ): ... # initialize a mat32h matrix m = mat32h(wp.float16(1.0), wp.float16(2.0), wp.float16(3.0), wp.float16(4.0), wp.float16(5.0), wp.float16(6.0)) # declare a 2 component half precision vector v2 = wp.vec2h(wp.float16(1.0), wp.float16(1.0)) # multiply by the matrix, returning a 3 component vector: v3 = m * v2 ... It's also possible to directly create anonymously typed instances inside kernels where the type is inferred from constructor arguments as follows:: @wp.kernel def compute( ... ): ... # create a 3x2 half precision matrix from components (row major ordering): m = wp.matrix( wp.float16(1.0), wp.float16(2.0), wp.float16(1.0), wp.float16(2.0), wp.float16(1.0), wp.float16(2.0), shape=(3,2)) # zero initialize a 3x2 half precision matrix: m = wp.matrix(wp.float16(0.0),shape=(3,2)) # create a 5x5 double precision identity matrix: m = wp.identity(n=5, dtype=wp.float64) As with vectors, you can do standard matrix arithmetic with these variables, along with multiplying matrices with compatible shapes and potentially returning a matrix with a new shape. .. _quat: Quaternions ########### Warp supports quaternions with the layout ``i, j, k, w`` where ``w`` is the real part. Here are the built-in concrete quaternion types: +-----------------+--------------------------------------------+ | quat | Single-precision floating point quaternion | +-----------------+--------------------------------------------+ | quatf | Single-precision floating point quaternion | +-----------------+--------------------------------------------+ | quatd | Double-precision floating point quaternion | +-----------------+--------------------------------------------+ | quath | Half-precision floating point quaternion | +-----------------+--------------------------------------------+ Quaternions can be used to transform vectors as follows:: @wp.kernel def compute( ... ): ... # construct a 30 degree rotation around the x-axis q = wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), wp.degrees(30.0)) # rotate an axis by this quaternion v = wp.quat_rotate(q, wp.vec3(0.0, 1.0, 0.0)) As with vectors and matrices, you can declare quaternion types with an arbitrary numeric type like so:: quatd = wp.types.quaternion(dtype=wp.float64) You can also create identity quaternion and anonymously typed instances inside a kernel like so:: @wp.kernel def compute( ... ): ... # create a double precision identity quaternion: qd = wp.quat_identity(dtype=wp.float64) # precision defaults to wp.float32 so this creates a single precision identity quaternion: qf = wp.quat_identity() # create a half precision quaternion from components, or a vector/scalar: qh = wp.quaternion(wp.float16(0.0), wp.float16(0.0), wp.float16(0.0), wp.float16(1.0)) qh = wp.quaternion( wp.vector(wp.float16(0.0),wp.float16(0.0),wp.float16(0.0)), wp.float16(1.0)) .. _transform: Transforms ########## Transforms are 7D vectors of floats representing a spatial rigid body transformation in format (p, q) where p is a 3D vector, and q is a quaternion. +-----------------+--------------------------------------------+ | transform | Single-precision floating point transform | +-----------------+--------------------------------------------+ | transformf | Single-precision floating point transform | +-----------------+--------------------------------------------+ | transformd | Double-precision floating point transform | +-----------------+--------------------------------------------+ | transformh | Half-precision floating point transform | +-----------------+--------------------------------------------+ Transforms can be constructed inside kernels from translation and rotation parts:: @wp.kernel def compute( ... ): ... # create a transform from a vector/quaternion: t = wp.transform( wp.vec3(1.0, 2.0, 3.0), wp.quat_from_axis_angle(wp.vec3(0.0, 1.0, 0.0), wp.degrees(30.0))) # transform a point p = wp.transform_point(t, wp.vec3(10.0, 0.5, 1.0)) # transform a vector (ignore translation) p = wp.transform_vector(t, wp.vec3(10.0, 0.5, 1.0)) As with vectors and matrices, you can declare transform types with an arbitrary numeric type using ``wp.types.transformation()``, for example:: transformd = wp.types.transformation(dtype=wp.float64) You can also create identity transforms and anonymously typed instances inside a kernel like so:: @wp.kernel def compute( ... ): # create double precision identity transform: qd = wp.transform_identity(dtype=wp.float64) .. _Structs: Structs ####### Users can define custom structure types using the ``@wp.struct`` decorator as follows:: @wp.struct class MyStruct: param1: int param2: float param3: wp.array(dtype=wp.vec3) Struct attributes must be annotated with their respective type. They can be constructed in Python scope and then passed to kernels as arguments:: @wp.kernel def compute(args: MyStruct): tid = wp.tid() print(args.param1) print(args.param2) print(args.param3[tid]) # construct an instance of the struct in Python s = MyStruct() s.param1 = 10 s.param2 = 2.5 s.param3 = wp.zeros(shape=10, dtype=wp.vec3) # pass to our compute kernel wp.launch(compute, dim=10, inputs=[s]) An array of structs can be zero-initialized as follows:: a = wp.zeros(shape=10, dtype=MyStruct) An array of structs can also be initialized from a list of struct objects:: a = wp.array([MyStruct(), MyStruct(), MyStruct()], dtype=MyStruct) Example: Using a struct in gradient computation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python import numpy as np import warp as wp @wp.struct class TestStruct: x: wp.vec3 a: wp.array(dtype=wp.vec3) b: wp.array(dtype=wp.vec3) @wp.kernel def test_kernel(s: TestStruct): tid = wp.tid() s.b[tid] = s.a[tid] + s.x @wp.kernel def loss_kernel(s: TestStruct, loss: wp.array(dtype=float)): tid = wp.tid() v = s.b[tid] wp.atomic_add(loss, 0, float(tid + 1) * (v[0] + 2.0 * v[1] + 3.0 * v[2])) # create struct ts = TestStruct() # set members ts.x = wp.vec3(1.0, 2.0, 3.0) ts.a = wp.array(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), dtype=wp.vec3, requires_grad=True) ts.b = wp.zeros(2, dtype=wp.vec3, requires_grad=True) loss = wp.zeros(1, dtype=float, requires_grad=True) tape = wp.Tape() with tape: wp.launch(test_kernel, dim=2, inputs=[ts]) wp.launch(loss_kernel, dim=2, inputs=[ts, loss]) tape.backward(loss) print(loss) print(ts.a) Type Conversions ################ Warp is particularly strict regarding type conversions and does not perform *any* implicit conversion between numeric types. The user is responsible for ensuring types for most arithmetic operators match, e.g.: ``x = float(0.0) + int(4)`` will result in an error. This can be surprising for users that are accustomed to C-style conversions but avoids a class of common bugs that result from implicit conversions. .. note:: Warp does not currently perform implicit type conversions between numeric types. Users should explicitly cast variables to compatible types using constructors like ``int()``, ``float()``, ``wp.float16()``, ``wp.uint8()``, etc. Constants --------- In general, Warp kernels cannot access variables in the global Python interpreter state. One exception to this is for compile-time constants, which may be declared globally (or as class attributes) and folded into the kernel definition. Constants are defined using the ``wp.constant()`` function. An example is shown below:: TYPE_SPHERE = wp.constant(0) TYPE_CUBE = wp.constant(1) TYPE_CAPSULE = wp.constant(2) @wp.kernel def collide(geometry: wp.array(dtype=int)): t = geometry[wp.tid()] if (t == TYPE_SPHERE): print("sphere") if (t == TYPE_CUBE): print("cube") if (t == TYPE_CAPSULE): print("capsule") .. autoclass:: constant Predefined Constants #################### For convenience, Warp has a number of predefined mathematical constants that may be used both inside and outside Warp kernels. The constants in the following table also have lowercase versions defined, e.g. ``wp.E`` and ``wp.e`` are equivalent. ================ ========================= Name Value ================ ========================= wp.E 2.71828182845904523536 wp.LOG2E 1.44269504088896340736 wp.LOG10E 0.43429448190325182765 wp.LN2 0.69314718055994530942 wp.LN10 2.30258509299404568402 wp.PHI 1.61803398874989484820 wp.PI 3.14159265358979323846 wp.HALF_PI 1.57079632679489661923 wp.TAU 6.28318530717958647692 wp.INF math.inf wp.NAN float('nan') ================ ========================= The ``wp.NAN`` constant may only be used with floating-point types. Comparisons involving ``wp.NAN`` follow the IEEE 754 standard, e.g. ``wp.float32(wp.NAN) == wp.float32(wp.NAN)`` returns ``False``. The :func:`wp.isnan() <isnan>` built-in function can be used to determine whether a value is a NaN (or if a vector, matrix, or quaternion contains a NaN entry). The following example shows how positive and negative infinity can be used with floating-point types in Warp using the ``wp.inf`` constant: .. code-block:: python @wp.kernel def test_infinity(outputs: wp.array(dtype=wp.float32)): outputs[0] = wp.float32(wp.inf) # inf outputs[1] = wp.float32(-wp.inf) # -inf outputs[2] = wp.float32(2.0 * wp.inf) # inf outputs[3] = wp.float32(-2.0 * wp.inf) # -inf outputs[4] = wp.float32(2.0 / 0.0) # inf outputs[5] = wp.float32(-2.0 / 0.0) # -inf Operators ---------- Boolean Operators ################# +--------------+--------------------------------------+ | a and b | True if a and b are True | +--------------+--------------------------------------+ | a or b | True if a or b is True | +--------------+--------------------------------------+ | not a | True if a is False, otherwise False | +--------------+--------------------------------------+ .. note:: Expressions such as ``if (a and b):`` currently do not perform short-circuit evaluation. In this case ``b`` will also be evaluated even when ``a`` is ``False``. Users should take care to ensure that secondary conditions are safe to evaluate (e.g.: do not index out of bounds) in all cases. Comparison Operators #################### +----------+---------------------------------------+ | a > b | True if a strictly greater than b | +----------+---------------------------------------+ | a < b | True if a strictly less than b | +----------+---------------------------------------+ | a >= b | True if a greater than or equal to b | +----------+---------------------------------------+ | a <= b | True if a less than or equal to b | +----------+---------------------------------------+ | a == b | True if a equals b | +----------+---------------------------------------+ | a != b | True if a not equal to b | +----------+---------------------------------------+ Arithmetic Operators #################### +-----------+--------------------------+ | a + b | Addition | +-----------+--------------------------+ | a - b | Subtraction | +-----------+--------------------------+ | a * b | Multiplication | +-----------+--------------------------+ | a / b | Floating point division | +-----------+--------------------------+ | a // b | Floored division | +-----------+--------------------------+ | a ** b | Exponentiation | +-----------+--------------------------+ | a % b | Modulus | +-----------+--------------------------+ .. note:: Since implicit conversions are not performed arguments types to operators should match. Users should use type constructors, e.g.: ``float()``, ``int()``, ``wp.int64()``, etc. to cast variables to the correct type. Also note that the multiplication expression ``a * b`` is used to represent scalar multiplication and matrix multiplication. The ``@`` operator is not currently supported. Graphs ----------- Launching kernels from Python introduces significant additional overhead compared to C++ or native programs. To address this, Warp exposes the concept of `CUDA graphs <https://developer.nvidia.com/blog/cuda-graphs/>`_ to allow recording large batches of kernels and replaying them with very little CPU overhead. To record a series of kernel launches use the :func:`wp.capture_begin() <capture_begin>` and :func:`wp.capture_end() <capture_end>` API as follows: .. code:: python # begin capture wp.capture_begin(device="cuda") try: # record launches for i in range(100): wp.launch(kernel=compute1, inputs=[a, b], device="cuda") finally: # end capture and return a graph object graph = wp.capture_end(device="cuda") We strongly recommend the use of the the try-finally pattern when capturing graphs because the `finally` statement will ensure :func:`wp.capture_end <capture_end>` gets called, even if an exception occurs during capture, which would otherwise trap the stream in a capturing state. Once a graph has been constructed it can be executed: :: wp.capture_launch(graph) The :class:`wp.ScopedCapture <ScopedCapture>` context manager can be used to simplify the code and ensure that :func:`wp.capture_end <capture_end>` is called regardless of exceptions: .. code:: python with wp.ScopedCapture(device="cuda") as capture: # record launches for i in range(100): wp.launch(kernel=compute1, inputs=[a, b], device="cuda") wp.capture_launch(capture.graph) Note that only launch calls are recorded in the graph, any Python executed outside of the kernel code will not be recorded. Typically it is only beneficial to use CUDA graphs when the graph will be reused or launched multiple times. .. autofunction:: capture_begin .. autofunction:: capture_end .. autofunction:: capture_launch .. autoclass:: ScopedCapture :members: Meshes ------ Warp provides a ``wp.Mesh`` class to manage triangle mesh data. To create a mesh users provide a points, indices and optionally a velocity array:: mesh = wp.Mesh(points, indices, velocities) .. note:: Mesh objects maintain references to their input geometry buffers. All buffers should live on the same device. Meshes can be passed to kernels using their ``id`` attribute which uniquely identifies the mesh by a unique ``uint64`` value. Once inside a kernel you can perform geometric queries against the mesh such as ray-casts or closest point lookups:: @wp.kernel def raycast(mesh: wp.uint64, ray_origin: wp.array(dtype=wp.vec3), ray_dir: wp.array(dtype=wp.vec3), ray_hit: wp.array(dtype=wp.vec3)): tid = wp.tid() t = float(0.0) # hit distance along ray u = float(0.0) # hit face barycentric u v = float(0.0) # hit face barycentric v sign = float(0.0) # hit face sign n = wp.vec3() # hit face normal f = int(0) # hit face index color = wp.vec3() # ray cast against the mesh if wp.mesh_query_ray(mesh, ray_origin[tid], ray_dir[tid], 1.e+6, t, u, v, sign, n, f): # if we got a hit then set color to the face normal color = n*0.5 + wp.vec3(0.5, 0.5, 0.5) ray_hit[tid] = color Users may update mesh vertex positions at runtime simply by modifying the points buffer. After modifying point locations users should call ``Mesh.refit()`` to rebuild the bounding volume hierarchy (BVH) structure and ensure that queries work correctly. .. note:: Updating Mesh topology (indices) at runtime is not currently supported. Users should instead recreate a new Mesh object. .. autoclass:: Mesh :members: Hash Grids ---------- Many particle-based simulation methods such as the Discrete Element Method (DEM), or Smoothed Particle Hydrodynamics (SPH), involve iterating over spatial neighbors to compute force interactions. Hash grids are a well-established data structure to accelerate these nearest neighbor queries, and particularly well-suited to the GPU. To support spatial neighbor queries Warp provides a ``HashGrid`` object that may be created as follows:: grid = wp.HashGrid(dim_x=128, dim_y=128, dim_z=128, device="cuda") grid.build(points=p, radius=r) ``p`` is an array of ``wp.vec3`` point positions, and ``r`` is the radius to use when building the grid. Neighbors can then be iterated over inside the kernel code using :func:`wp.hash_grid_query() <hash_grid_query>` and :func:`wp.hash_grid_query_next() <hash_grid_query_next>` as follows: .. code:: python @wp.kernel def sum(grid : wp.uint64, points: wp.array(dtype=wp.vec3), output: wp.array(dtype=wp.vec3), radius: float): tid = wp.tid() # query point p = points[tid] # create grid query around point query = wp.hash_grid_query(grid, p, radius) index = int(0) sum = wp.vec3() while(wp.hash_grid_query_next(query, index)): neighbor = points[index] # compute distance to neighbor point dist = wp.length(p-neighbor) if (dist <= radius): sum += neighbor output[tid] = sum .. note:: The ``HashGrid`` query will give back all points in *cells* that fall inside the query radius. When there are hash conflicts it means that some points outside of query radius will be returned, and users should check the distance themselves inside their kernels. The reason the query doesn't do the check itself for each returned point is because it's common for kernels to compute the distance themselves, so it would redundant to check/compute the distance twice. .. autoclass:: HashGrid :members: Volumes ------- Sparse volumes are incredibly useful for representing grid data over large domains, such as signed distance fields (SDFs) for complex objects, or velocities for large-scale fluid flow. Warp supports reading sparse volumetric grids stored using the `NanoVDB <https://developer.nvidia.com/nanovdb>`_ standard. Users can access voxels directly or use built-in closest-point or trilinear interpolation to sample grid data from world or local space. Volume objects can be created directly from Warp arrays containing a NanoVDB grid, from the contents of a standard ``.nvdb`` file using :func:`load_from_nvdb() <warp.Volume.load_from_nvdb>`, from an uncompressed in-memory buffer using :func:`load_from_address() <warp.Volume.load_from_address>`, or from a dense 3D NumPy array using :func:`load_from_numpy() <warp.Volume.load_from_numpy>`. Volumes can also be created using :func:`allocate() <warp.Volume.allocate>`, :func:`allocate_by_tiles() <warp.Volume.allocate_by_tiles>` or :func:`allocate_by_voxels() <warp.Volume.allocate_by_voxels>`. The values for a Volume object can be modified in a Warp kernel using :func:`wp.volume_store() <warp.volume_store>`. .. note:: Warp does not currently support modifying the topology of sparse volumes at runtime. Below we give an example of creating a Volume object from an existing NanoVDB file:: # open NanoVDB file on disk file = open("mygrid.nvdb", "rb") # create Volume object volume = wp.Volume.load_from_nvdb(file, device="cpu") .. note:: Files written by the NanoVDB library, commonly marked by the ``.nvdb`` extension, can contain multiple grids with various compression methods, but a :class:`Volume` object represents a single NanoVDB grid. The first grid is loaded by default, then Warp volumes corresponding to the other grids in the file can be created using repeated calls to :func:`load_next_grid() <warp.Volume.load_next_grid>`. NanoVDB's uncompressed and zip-compressed file formats are supported out-of-the-box, blosc compressed files require the `blosc` Python package to be installed. To sample the volume inside a kernel we pass a reference to it by ID, and use the built-in sampling modes:: @wp.kernel def sample_grid(volume: wp.uint64, points: wp.array(dtype=wp.vec3), samples: wp.array(dtype=float)): tid = wp.tid() # load sample point in world-space p = points[tid] # transform position to the volume's local-space q = wp.volume_world_to_index(volume, p) # sample volume with trilinear interpolation f = wp.volume_sample(volume, q, wp.Volume.LINEAR, dtype=float) # write result samples[tid] = f Warp also supports NanoVDB index grids, which provide a memory-efficient linearization of voxel indices that can refer to values in arbitrarily shaped arrays:: @wp.kernel def sample_index_grid(volume: wp.uint64, points: wp.array(dtype=wp.vec3), voxel_values: wp.array(dtype=Any)): tid = wp.tid() # load sample point in world-space p = points[tid] # transform position to the volume's local-space q = wp.volume_world_to_index(volume, p) # sample volume with trilinear interpolation background_value = voxel_values.dtype(0.0) f = wp.volume_sample_index(volume, q, wp.Volume.LINEAR, voxel_values, background_value) The coordinates of all indexable voxels can be recovered using :func:`get_voxels() <warp.Volume.get_voxels>`. NanoVDB grids may also contains embedded *blind* data arrays; those can be accessed with the :func:`feature_array() <warp.Volume.feature_array>` function. .. autoclass:: Volume :members: :undoc-members: .. seealso:: `Reference <functions.html#volumes>`__ for the volume functions available in kernels. Bounding Value Hierarchies (BVH) -------------------------------- The :class:`wp.Bvh <Bvh>` class can be used to create a BVH for a group of bounding volumes. This object can then be traversed to determine which parts are intersected by a ray using :func:`bvh_query_ray` and which parts are fully contained within a certain bounding volume using :func:`bvh_query_aabb`. The following snippet demonstrates how to create a :class:`wp.Bvh <Bvh>` object from 100 random bounding volumes: .. code:: python rng = np.random.default_rng(123) num_bounds = 100 lowers = rng.random(size=(num_bounds, 3)) * 5.0 uppers = lowers + rng.random(size=(num_bounds, 3)) * 5.0 device_lowers = wp.array(lowers, dtype=wp.vec3, device="cuda:0") device_uppers = wp.array(uppers, dtype=wp.vec3, device="cuda:0") bvh = wp.Bvh(device_lowers, device_uppers) .. autoclass:: Bvh :members: Example: BVH Ray Traversal ########################## An example of performing a ray traversal on the data structure is as follows: .. code:: python @wp.kernel def bvh_query_ray( bvh_id: wp.uint64, start: wp.vec3, dir: wp.vec3, bounds_intersected: wp.array(dtype=wp.bool), ): query = wp.bvh_query_ray(bvh_id, start, dir) bounds_nr = wp.int32(0) while wp.bvh_query_next(query, bounds_nr): # The ray intersects the volume with index bounds_nr bounds_intersected[bounds_nr] = True bounds_intersected = wp.zeros(shape=(num_bounds), dtype=wp.bool, device="cuda:0") query_start = wp.vec3(0.0, 0.0, 0.0) query_dir = wp.normalize(wp.vec3(1.0, 1.0, 1.0)) wp.launch( kernel=bvh_query_ray, dim=1, inputs=[bvh.id, query_start, query_dir, bounds_intersected], device="cuda:0", ) The Warp kernel ``bvh_query_ray`` is launched with a single thread, provided the unique :class:`uint64` identifier of the :class:`wp.Bvh <Bvh>` object, parameters describing the ray, and an array to store the results. In ``bvh_query_ray``, :func:`wp.bvh_query_ray() <bvh_query_ray>` is called once to obtain an object that is stored in the variable ``query``. An integer is also allocated as ``bounds_nr`` to store the volume index of the traversal. A while statement is used for the actual traversal using :func:`wp.bvh_query_next() <bvh_query_next>`, which returns ``True`` as long as there are intersecting bounds. Example: BVH Volume Traversal ############################# Similar to the ray-traversal example, we can perform volume traversal to find the volumes that are fully contained within a specified bounding box. .. code:: python @wp.kernel def bvh_query_aabb( bvh_id: wp.uint64, lower: wp.vec3, upper: wp.vec3, bounds_intersected: wp.array(dtype=wp.bool), ): query = wp.bvh_query_aabb(bvh_id, lower, upper) bounds_nr = wp.int32(0) while wp.bvh_query_next(query, bounds_nr): # The volume with index bounds_nr is fully contained # in the (lower,upper) bounding box bounds_intersected[bounds_nr] = True bounds_intersected = wp.zeros(shape=(num_bounds), dtype=wp.bool, device="cuda:0") query_lower = wp.vec3(4.0, 4.0, 4.0) query_upper = wp.vec3(6.0, 6.0, 6.0) wp.launch( kernel=bvh_query_aabb, dim=1, inputs=[bvh.id, query_lower, query_upper, bounds_intersected], device="cuda:0", ) The kernel is nearly identical to the ray-traversal example, except we obtain ``query`` using :func:`wp.bvh_query_aabb() <bvh_query_aabb>`. Marching Cubes -------------- The :class:`wp.MarchingCubes <MarchingCubes>` class can be used to extract a 2-D mesh approximating an isosurface of a 3-D scalar field. The resulting triangle mesh can be saved to a USD file using the :class:`warp.renderer.UsdRenderer`. See :github:`warp/examples/core/example_marching_cubes.py` for a usage example. .. autoclass:: MarchingCubes :members: Profiling --------- ``wp.ScopedTimer`` objects can be used to gain some basic insight into the performance of Warp applications: .. code:: python with wp.ScopedTimer("grid build"): self.grid.build(self.x, self.point_radius) This results in a printout at runtime to the standard output stream like: .. code:: console grid build took 0.06 ms See :doc:`../profiling` documentation for more information. .. autoclass:: warp.ScopedTimer :noindex:
44,063
reStructuredText
35.997481
331
0.594172
NVIDIA/warp/docs/modules/differentiability.rst
Differentiability ================= .. currentmodule:: warp By default, Warp generates a forward and backward (adjoint) version of each kernel definition. The backward version of a kernel can be used to compute gradients of loss functions that can be back propagated to machine learning frameworks like PyTorch. Arrays that participate in the chain of computation which require gradients should be created with ``requires_grad=True``, for example:: a = wp.zeros(1024, dtype=wp.vec3, device="cuda", requires_grad=True) The ``wp.Tape`` class can then be used to record kernel launches, and replay them to compute the gradient of a scalar loss function with respect to the kernel inputs:: tape = wp.Tape() # forward pass with tape: wp.launch(kernel=compute1, inputs=[a, b], device="cuda") wp.launch(kernel=compute2, inputs=[c, d], device="cuda") wp.launch(kernel=loss, inputs=[d, l], device="cuda") # reverse pass tape.backward(l) After the backward pass has completed, the gradients with respect to the inputs are available from the ``array.grad`` attribute:: # gradient of loss with respect to input a print(a.grad) Note that gradients are accumulated on the participating buffers, so if you wish to reuse the same buffers for multiple backward passes you should first zero the gradients:: tape.zero() .. note:: Warp uses a source-code transformation approach to auto-differentiation. In this approach, the backwards pass must keep a record of intermediate values computed during the forward pass. This imposes some restrictions on what kernels can do and still be differentiable: * Dynamic loops should not mutate any previously declared local variable. This means the loop must be side-effect free. A simple way to ensure this is to move the loop body into a separate function. Static loops that are unrolled at compile time do not have this restriction and can perform any computation. * Kernels should not overwrite any previously used array values except to perform simple linear add/subtract operations (e.g. via :func:`wp.atomic_add() <atomic_add>`) .. autoclass:: Tape :members: Jacobians ######### To compute the Jacobian matrix :math:`J\in\mathbb{R}^{m\times n}` of a multi-valued function :math:`f: \mathbb{R}^n \to \mathbb{R}^m`, we can evaluate an entire row of the Jacobian in parallel by finding the Jacobian-vector product :math:`J^\top \mathbf{e}`. The vector :math:`\mathbf{e}\in\mathbb{R}^m` selects the indices in the output buffer to differentiate with respect to. In Warp, instead of passing a scalar loss buffer to the ``tape.backward()`` method, we pass a dictionary ``grads`` mapping from the function output array to the selection vector :math:`\mathbf{e}` having the same type:: # compute the Jacobian for a function of single output jacobian = np.empty((output_dim, input_dim), dtype=np.float32) # record computation tape = wp.Tape() with tape: output_buffer = launch_kernels_to_be_differentiated(input_buffer) # compute each row of the Jacobian for output_index in range(output_dim): # select which row of the Jacobian we want to compute select_index = np.zeros(output_dim) select_index[output_index] = 1.0 e = wp.array(select_index, dtype=wp.float32) # pass input gradients to the output buffer to apply selection tape.backward(grads={output_buffer: e}) q_grad_i = tape.gradients[input_buffer] jacobian[output_index, :] = q_grad_i.numpy() # zero gradient arrays for next row tape.zero() When we run simulations independently in parallel, the Jacobian corresponding to the entire system dynamics is a block-diagonal matrix. In this case, we can compute the Jacobian in parallel for all environments by choosing a selection vector that has the output indices active for all environment copies. For example, to get the first rows of the Jacobians of all environments, :math:`\mathbf{e}=[\begin{smallmatrix}1 & 0 & 0 & \dots & 1 & 0 & 0 & \dots\end{smallmatrix}]^\top`, to compute the second rows, :math:`\mathbf{e}=[\begin{smallmatrix}0 & 1 & 0 & \dots & 0 & 1 & 0 & \dots\end{smallmatrix}]^\top`, etc.:: # compute the Jacobian for a function over multiple environments in parallel jacobians = np.empty((num_envs, output_dim, input_dim), dtype=np.float32) # record computation tape = wp.Tape() with tape: output_buffer = launch_kernels_to_be_differentiated(input_buffer) # compute each row of the Jacobian for output_index in range(output_dim): # select which row of the Jacobian we want to compute select_index = np.zeros(output_dim) select_index[output_index] = 1.0 # assemble selection vector for all environments (can be precomputed) e = wp.array(np.tile(select_index, num_envs), dtype=wp.float32) tape.backward(grads={output_buffer: e}) q_grad_i = tape.gradients[input_buffer] jacobians[:, output_index, :] = q_grad_i.numpy().reshape(num_envs, input_dim) tape.zero() Custom Gradient Functions ######################### Warp supports custom gradient function definitions for user-defined Warp functions. This allows users to define code that should replace the automatically generated derivatives. To differentiate a function :math:`h(x) = f(g(x))` that has a nested call to function :math:`g(x)`, the chain rule is evaluated in the automatic differentiation of :math:`h(x)`: .. math:: h^\prime(x) = f^\prime({\color{green}{\underset{\textrm{replay}}{g(x)}}}) {\color{blue}{\underset{\textrm{grad}}{g^\prime(x)}}} This implies that a function to be compatible with the autodiff engine needs to provide an implementation of its forward version :math:`\color{green}{g(x)}`, which we refer to as "replay" function (that matches the original function definition by default), and its derivative :math:`\color{blue}{g^\prime(x)}`, referred to as "grad". Both the replay and the grad implementations can be customized by the user. They are defined as follows: .. list-table:: Customizing the replay and grad versions of function ``myfunc`` :widths: 100 :header-rows: 0 * - Forward Function * - .. code-block:: python @wp.func def myfunc(in1: InType1, ..., inN: InTypeN) -> OutType1, ..., OutTypeM: return out1, ..., outM * - Custom Replay Function * - .. code-block:: python @wp.func_replay(myfunc) def replay_myfunc(in1: InType1, ..., inN: InTypeN) -> OutType1, ..., OutTypeM: # Custom forward computations to be executed in the backward pass of a # function calling `myfunc` go here # Ensure the output variables match the original forward definition return out1, ..., outM * - Custom Grad Function * - .. code-block:: python @wp.func_grad(myfunc) def adj_myfunc(in1: InType1, ..., inN: InTypeN, adj_out1: OutType1, ..., adj_outM: OutTypeM): # Custom adjoint code goes here # Update the partial derivatives for the inputs as follows: wp.adjoint[in1] += ... ... wp.adjoint[inN] += ... .. note:: It is currently not possible to define custom replay or grad functions for functions that have generic arguments, e.g. ``Any`` or ``wp.array(dtype=Any)``. Replay or grad functions that themselves use generic arguments are also not yet supported. Example 1: Custom Grad Function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the following, we define a Warp function ``safe_sqrt`` that computes the square root of a number:: @wp.func def safe_sqrt(x: float): return wp.sqrt(x) To evaluate this function, we define a kernel that applies ``safe_sqrt`` to an array of input values:: @wp.kernel def run_safe_sqrt(xs: wp.array(dtype=float), output: wp.array(dtype=float)): i = wp.tid() output[i] = safe_sqrt(xs[i]) Calling the kernel for an array of values ``[1.0, 2.0, 0.0]`` yields the expected outputs, the gradients are finite except for the zero input:: xs = wp.array([1.0, 2.0, 0.0], dtype=wp.float32, requires_grad=True) ys = wp.zeros_like(xs) tape = wp.Tape() with tape: wp.launch(run_safe_sqrt, dim=len(xs), inputs=[xs], outputs=[ys]) tape.backward(grads={ys: wp.array(np.ones(len(xs)), dtype=wp.float32)}) print("ys ", ys) print("xs.grad", xs.grad) # ys [1. 1.4142135 0. ] # xs.grad [0.5 0.35355338 inf] It is often desired to catch nonfinite gradients in the computation graph as they may cause the entire gradient computation to be nonfinite. To do so, we can define a custom gradient function that replaces the adjoint function for ``safe_sqrt`` which is automatically generated by decorating the custom gradient code via ``@wp.func_grad(safe_sqrt)``:: @wp.func_grad(safe_sqrt) def adj_safe_sqrt(x: float, adj_ret: float): if x > 0.0: wp.adjoint[x] += 1.0 / (2.0 * wp.sqrt(x)) * adj_ret .. note:: The function signature of the custom grad code consists of the input arguments of the forward function plus the adjoint variables of the forward function outputs. To access and modify the partial derivatives of the input arguments, we use the ``wp.adjoint`` dictionary. The keys of this dictionary are the input arguments of the forward function, and the values are the partial derivatives of the forward function output with respect to the input argument. Example 2: Custom Replay Function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the following, we increment an array index in each thread via :func:`wp.atomic_add() <atomic_add>` and compute the square root of an input array at the incremented index:: @wp.kernel def test_add(counter: wp.array(dtype=int), input: wp.array(dtype=float), output: wp.array(dtype=float)): idx = wp.atomic_add(counter, 0, 1) output[idx] = wp.sqrt(input[idx]) def main(): dim = 16 use_reversible_increment = False input = wp.array(np.arange(1, dim + 1), dtype=wp.float32, requires_grad=True) counter = wp.zeros(1, dtype=wp.int32) thread_ids = wp.zeros(dim, dtype=wp.int32) output = wp.zeros(dim, dtype=wp.float32, requires_grad=True) tape = wp.Tape() with tape: if use_reversible_increment: wp.launch(test_add_diff, dim, inputs=[counter, thread_ids, input], outputs=[output]) else: wp.launch(test_add, dim, inputs=[counter, input], outputs=[output]) print("counter: ", counter.numpy()) print("thread_ids: ", thread_ids.numpy()) print("input: ", input.numpy()) print("output: ", output.numpy()) tape.backward(grads={ output: wp.array(np.ones(dim), dtype=wp.float32) }) print("input.grad: ", input.grad.numpy()) if __name__ == "__main__": main() The output of the above code is: .. code-block:: js counter: [8] thread_ids: [0 0 0 0 0 0 0 0] input: [1. 2. 3. 4. 5. 6. 7. 8.] output: [1. 1.4142135 1.7320508 2. 2.236068 2.4494898 2.6457512 2.828427] input.grad: [4. 0. 0. 0. 0. 0. 0. 0.] The gradient of the input is incorrect because the backward pass involving the atomic operation ``wp.atomic_add()`` does not know which thread ID corresponds to which input value. The index returned by the adjoint of ``wp.atomic_add()`` is always zero so that the gradient the first entry of the input array, i.e. :math:`\frac{1}{2\sqrt{1}} = 0.5`, is accumulated ``dim`` times (hence ``input.grad[0] == 4.0`` and all other entries zero). To fix this, we define a new Warp function ``reversible_increment()`` with a custom *replay* definition that stores the thread ID in a separate array:: @wp.func def reversible_increment( buf: wp.array(dtype=int), buf_index: int, value: int, thread_values: wp.array(dtype=int), tid: int ): next_index = wp.atomic_add(buf, buf_index, value) # store which thread ID corresponds to which index for the backward pass thread_values[tid] = next_index return next_index @wp.func_replay(reversible_increment) def replay_reversible_increment( buf: wp.array(dtype=int), buf_index: int, value: int, thread_values: wp.array(dtype=int), tid: int ): return thread_values[tid] Instead of running ``reversible_increment()``, the custom replay code in ``replay_reversible_increment()`` is now executed during forward phase in the backward pass of the function calling ``reversible_increment()``. We first stored the array index to each thread ID in the forward pass, and now we retrieve the array index for each thread ID in the backward pass. That way, the backward pass can reproduce the same addition operation as in the forward pass with exactly the same operands per thread. .. warning:: The function signature of the custom replay code must match the forward function signature. To use our function we write the following kernel:: @wp.kernel def test_add_diff( counter: wp.array(dtype=int), thread_ids: wp.array(dtype=int), input: wp.array(dtype=float), output: wp.array(dtype=float) ): tid = wp.tid() idx = reversible_increment(counter, 0, 1, thread_ids, tid) output[idx] = wp.sqrt(input[idx]) Running the ``test_add_diff`` kernel via the previous ``main`` function with ``use_reversible_increment = True``, we now compute correct gradients for the input array: .. code-block:: js counter: [8] thread_ids: [0 1 2 3 4 5 6 7] input: [1. 2. 3. 4. 5. 6. 7. 8.] output: [1. 1.4142135 1.7320508 2. 2.236068 2.4494898 2.6457512 2.828427 ] input.grad: [0.5 0.35355338 0.28867513 0.25 0.2236068 0.20412414 0.18898225 0.17677669] Custom Native Functions ####################### Users may insert native C++/CUDA code in Warp kernels using ``@func_native`` decorated functions. These accept native code as strings that get compiled after code generation, and are called within ``@wp.kernel`` functions. For example:: snippet = """ __shared__ int sum[128]; sum[tid] = arr[tid]; __syncthreads(); for (int stride = 64; stride > 0; stride >>= 1) { if (tid < stride) { sum[tid] += sum[tid + stride]; } __syncthreads(); } if (tid == 0) { out[0] = sum[0]; } """ @wp.func_native(snippet) def reduce(arr: wp.array(dtype=int), out: wp.array(dtype=int), tid: int): ... @wp.kernel def reduce_kernel(arr: wp.array(dtype=int), out: wp.array(dtype=int)): tid = wp.tid() reduce(arr, out, tid) N = 128 x = wp.array(np.arange(N, dtype=int), dtype=int, device=device) out = wp.zeros(1, dtype=int, device=device) wp.launch(kernel=reduce_kernel, dim=N, inputs=[x, out], device=device) Notice the use of shared memory here: the Warp library does not expose shared memory as a feature, but the CUDA compiler will readily accept the above snippet. This means CUDA features not exposed in Warp are still accessible in Warp scripts. Warp kernels meant for the CPU won't be able to leverage CUDA features of course, but this same mechanism supports pure C++ snippets as well. Please bear in mind the following: the thread index in your snippet should be computed in a ``@wp.kernel`` and passed to your snippet, as in the above example. This means your ``@wp.func_native`` function signature should include the variables used in your snippet, as well as a thread index of type ``int``. The function body itself should be stubbed with ``...`` (the snippet will be inserted during compilation). Should you wish to record your native function on the tape and then subsequently rewind the tape, you must include an adjoint snippet alongside your snippet as an additional input to the decorator, as in the following example:: snippet = """ out[tid] = a * x[tid] + y[tid]; """ adj_snippet = """ adj_a += x[tid] * adj_out[tid]; adj_x[tid] += a * adj_out[tid]; adj_y[tid] += adj_out[tid]; """ @wp.func_native(snippet, adj_snippet) def saxpy( a: wp.float32, x: wp.array(dtype=wp.float32), y: wp.array(dtype=wp.float32), out: wp.array(dtype=wp.float32), tid: int, ): ... @wp.kernel def saxpy_kernel( a: wp.float32, x: wp.array(dtype=wp.float32), y: wp.array(dtype=wp.float32), out: wp.array(dtype=wp.float32) ): tid = wp.tid() saxpy(a, x, y, out, tid) N = 128 a = 2.0 x = wp.array(np.arange(N, dtype=np.float32), dtype=wp.float32, device=device, requires_grad=True) y = wp.zeros_like(x1) out = wp.array(np.arange(N, dtype=np.float32), dtype=wp.float32, device=device) adj_out = wp.array(np.ones(N, dtype=np.float32), dtype=wp.float32, device=device) tape = wp.Tape() with tape: wp.launch(kernel=saxpy_kernel, dim=N, inputs=[a, x, y], outputs=[out], device=device) tape.backward(grads={out: adj_out}) You may also include a custom replay snippet, to be executed as part of the adjoint (see `Custom Gradient Functions`_ for a full explanation). Consider the following example:: def test_custom_replay_grad(): num_threads = 8 counter = wp.zeros(1, dtype=wp.int32) thread_values = wp.zeros(num_threads, dtype=wp.int32) inputs = wp.array(np.arange(num_threads, dtype=np.float32), requires_grad=True) outputs = wp.zeros_like(inputs) snippet = """ int next_index = atomicAdd(counter, 1); thread_values[tid] = next_index; """ replay_snippet = "" @wp.func_native(snippet, replay_snippet=replay_snippet) def reversible_increment( counter: wp.array(dtype=int), thread_values: wp.array(dtype=int), tid: int ): ... @wp.kernel def run_atomic_add( input: wp.array(dtype=float), counter: wp.array(dtype=int), thread_values: wp.array(dtype=int), output: wp.array(dtype=float), ): tid = wp.tid() reversible_increment(counter, thread_values, tid) idx = thread_values[tid] output[idx] = input[idx] ** 2.0 tape = wp.Tape() with tape: wp.launch( run_atomic_add, dim=num_threads, inputs=[inputs, counter, thread_values], outputs=[outputs] ) tape.backward(grads={outputs: wp.array(np.ones(num_threads, dtype=np.float32))}) By default, ``snippet`` would be called in the backward pass, but in this case, we have a custom replay snippet defined, which is called instead. In this case, ``replay_snippet`` is a no-op, which is all that we require, since ``thread_values`` are cached in the forward pass. If we did not have a ``replay_snippet`` defined, ``thread_values`` would be overwritten with counter values that exceed the input array size in the backward pass. A native snippet may also include a return statement. If this is the case, you must specify the return type in the native function definition, as in the following example:: snippet = """ float sq = x * x; return sq; """ adj_snippet = """ adj_x += 2.f * x * adj_ret; """ @wp.func_native(snippet, adj_snippet) def square(x: float) -> float: ... @wp.kernel def square_kernel(input: wp.array(dtype=Any), output: wp.array(dtype=Any)): tid = wp.tid() x = input[tid] output[tid] = square(x) N = 5 x = wp.array(np.arange(N, dtype=float), dtype=float, requires_grad=True) y = wp.zeros_like(x) tape = wp.Tape() with tape: wp.launch(kernel=square_kernel, dim=N, inputs=[x, y]) tape.backward(grads={y: wp.ones(N, dtype=float)}) Debugging Gradients ################### .. note:: We are expanding the debugging section to provide tools to help users debug gradient computations in the next Warp release. Visualizing Computation Graphs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Computing gradients via automatic differentiation can be error-prone, where arrays sometimes miss the ``requires_grad`` setting, or the wrong arrays are passed between kernels. To help debug gradient computations, Warp provides a ``tape.visualize()`` method that generates a graph visualization of the kernel launches recorded on the tape in the `GraphViz <https://graphviz.org/>`_ dot format. The visualization shows how the Warp arrays are used as inputs and outputs of the kernel launches. Example usage:: import warp as wp @wp.kernel def add(a: wp.array(dtype=float), b: wp.array(dtype=float), c: wp.array(dtype=float)): tid = wp.tid() c[tid] = a[tid] + b[tid] tape = wp.Tape() a = wp.array([2.0], dtype=wp.float32) b = wp.array([3.0], dtype=wp.float32, requires_grad=True) c = wp.array([4.0], dtype=wp.float32) d = c e = wp.array([5.0], dtype=wp.float32, requires_grad=True) result = wp.zeros(1, dtype=wp.float32, requires_grad=True) with tape: wp.launch(add, dim=1, inputs=[b, e], outputs=[a]) # ScopedTimer registers itself as a scope on the tape with wp.ScopedTimer("Adder"): # we can also manually record scopes tape.record_scope_begin("Custom Scope") wp.launch(add, dim=1, inputs=[a, b], outputs=[c]) tape.record_scope_end() wp.launch(add, dim=1, inputs=[d, a], outputs=[result]) tape.visualize( filename="tape.dot", array_labels={a: "a", b: "b", c: "c", e: "e", result: "result"}, ) This will generate a file `tape.dot` that can be visualized using the `GraphViz <https://graphviz.org/>`_ toolset: .. code-block:: bash dot -Tsvg tape.dot -o tape.svg The resulting SVG image can be rendered in a web browser: .. image:: ../img/tape.svg The graph visualization shows the kernel launches as grey boxes with the ports below them indicating the input and output arguments. Arrays are shown as ellipses, where gray ellipses indicate arrays that do not require gradients, and green ellipses indicate arrays that do not have ``requires_grad=True``. In the example above we can see that the array ``c`` does not have its ``requires_grad`` flag set, which means gradients will not be propagated through this path. .. note:: Arrays can be labeled with custom names using the ``array_labels`` argument to the ``tape.visualize()`` method.
22,938
reStructuredText
40.183124
614
0.65276
NVIDIA/warp/docs/modules/devices.rst
Devices ======= Warp assigns unique string aliases to all supported compute devices in the system. There is currently a single CPU device exposed as ``"cpu"``. Each CUDA-capable GPU gets an alias of the form ``"cuda:i"``, where ``i`` is the CUDA device ordinal. This convention should be familiar to users of other popular frameworks like PyTorch. It is possible to explicitly target a specific device with each Warp API call using the ``device`` argument:: a = wp.zeros(n, device="cpu") wp.launch(kernel, dim=a.size, inputs=[a], device="cpu") b = wp.zeros(n, device="cuda:0") wp.launch(kernel, dim=b.size, inputs=[b], device="cuda:0") c = wp.zeros(n, device="cuda:1") wp.launch(kernel, dim=c.size, inputs=[c], device="cuda:1") .. note:: A Warp CUDA device (``"cuda:i"``) corresponds to the primary CUDA context of device ``i``. This is compatible with frameworks like PyTorch and other software that uses the CUDA Runtime API. It makes interoperability easy because GPU resources like memory can be shared with Warp. .. autoclass:: warp.context.Device :members: :exclude-members: init_streams Default Device -------------- To simplify writing code, Warp has the concept of **default device**. When the ``device`` argument is omitted from a Warp API call, the default device will be used. During Warp initialization, the default device is set to be ``"cuda:0"`` if CUDA is available. Otherwise, the default device is ``"cpu"``. The function ``wp.set_device()`` can be used to change the default device:: wp.set_device("cpu") a = wp.zeros(n) wp.launch(kernel, dim=a.size, inputs=[a]) wp.set_device("cuda:0") b = wp.zeros(n) wp.launch(kernel, dim=b.size, inputs=[b]) wp.set_device("cuda:1") c = wp.zeros(n) wp.launch(kernel, dim=c.size, inputs=[c]) .. note:: For CUDA devices, ``wp.set_device()`` does two things: it sets the Warp default device and it makes the device's CUDA context current. This helps to minimize the number of CUDA context switches in blocks of code targeting a single device. For PyTorch users, this function is similar to ``torch.cuda.set_device()``. It is still possible to specify a different device in individual API calls, like in this snippet:: # set default device wp.set_device("cuda:0") # use default device a = wp.zeros(n) # use explicit devices b = wp.empty(n, device="cpu") c = wp.empty(n, device="cuda:1") # use default device wp.launch(kernel, dim=a.size, inputs=[a]) wp.copy(b, a) wp.copy(c, a) Scoped Devices -------------- Another way to manage the default device is using ``wp.ScopedDevice`` objects. They can be arbitrarily nested and restore the previous default device on exit:: with wp.ScopedDevice("cpu"): # alloc and launch on "cpu" a = wp.zeros(n) wp.launch(kernel, dim=a.size, inputs=[a]) with wp.ScopedDevice("cuda:0"): # alloc on "cuda:0" b = wp.zeros(n) with wp.ScopedDevice("cuda:1"): # alloc and launch on "cuda:1" c = wp.zeros(n) wp.launch(kernel, dim=c.size, inputs=[c]) # launch on "cuda:0" wp.launch(kernel, dim=b.size, inputs=[b]) .. note:: For CUDA devices, ``wp.ScopedDevice`` makes the device's CUDA context current and restores the previous CUDA context on exit. This is handy when running Warp scripts as part of a bigger pipeline, because it avoids any side effects of changing the CUDA context in the enclosed code. Example: Using ``wp.ScopedDevice`` with multiple GPUs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to allocate arrays and launch kernels on all available CUDA devices. .. code:: python import warp as wp @wp.kernel def inc(a: wp.array(dtype=float)): tid = wp.tid() a[tid] = a[tid] + 1.0 # get all CUDA devices devices = wp.get_cuda_devices() device_count = len(devices) # number of launches iters = 1000 # list of arrays, one per device arrs = [] # loop over all devices for device in devices: # use a ScopedDevice to set the target device with wp.ScopedDevice(device): # allocate array a = wp.zeros(250 * 1024 * 1024, dtype=float) arrs.append(a) # launch kernels for _ in range(iters): wp.launch(inc, dim=a.size, inputs=[a]) # synchronize all devices wp.synchronize() # print results for i in range(device_count): print(f"{arrs[i].device} -> {arrs[i].numpy()}") Current CUDA Device ------------------- Warp uses the device alias ``"cuda"`` to target the current CUDA device. This allows external code to manage the CUDA device on which to execute Warp scripts. It is analogous to the PyTorch ``"cuda"`` device, which should be familiar to Torch users and simplify interoperation. In this snippet, we use PyTorch to manage the current CUDA device and invoke a Warp kernel on that device:: def example_function(): # create a Torch tensor on the current CUDA device t = torch.arange(10, dtype=torch.float32, device="cuda") a = wp.from_torch(t) # launch a Warp kernel on the current CUDA device wp.launch(kernel, dim=a.size, inputs=[a], device="cuda") # use Torch to set the current CUDA device and run example_function() on that device torch.cuda.set_device(0) example_function() # use Torch to change the current CUDA device and re-run example_function() on that device torch.cuda.set_device(1) example_function() .. note:: Using the device alias ``"cuda"`` can be problematic if the code runs in an environment where another part of the code can unpredictably change the CUDA context. Using an explicit CUDA device like ``"cuda:i"`` is recommended to avoid such issues. Device Synchronization ---------------------- CUDA kernel launches and memory operations can execute asynchronously. This allows for overlapping compute and memory operations on different devices. Warp allows synchronizing the host with outstanding asynchronous operations on a specific device:: wp.synchronize_device("cuda:1") The ``wp.synchronize_device()`` function offers more fine-grained synchronization than ``wp.synchronize()``, as the latter waits for *all* devices to complete their work. Custom CUDA Contexts -------------------- Warp is designed to work with arbitrary CUDA contexts so it can easily integrate into different workflows. Applications built on the CUDA Runtime API target the *primary context* of each device. The Runtime API hides CUDA context management under the hood. In Warp, device ``"cuda:i"`` represents the primary context of device ``i``, which aligns with the CUDA Runtime API. Applications built on the CUDA Driver API work with CUDA contexts directly and can create custom CUDA contexts on any device. Custom CUDA contexts can be created with specific affinity or interop features that benefit the application. Warp can work with these CUDA contexts as well. The special device alias ``"cuda"`` can be used to target the current CUDA context, whether this is a primary or custom context. In addition, Warp allows registering new device aliases for custom CUDA contexts, so that they can be explicitly targeted by name. If the ``CUcontext`` pointer is available, it can be used to create a new device alias like this:: wp.map_cuda_device("foo", ctypes.c_void_p(context_ptr)) Alternatively, if the custom CUDA context was made current by the application, the pointer can be omitted:: wp.map_cuda_device("foo") In either case, mapping the custom CUDA context allows us to target the context directly using the assigned alias:: with wp.ScopedDevice("foo"): a = wp.zeros(n) wp.launch(kernel, dim=a.size, inputs=[a]) .. _peer_access: CUDA Peer Access ---------------- CUDA allows direct memory access between different GPUs if the system hardware configuration supports it. Typically, the GPUs should be of the same type and a special interconnect may be required (e.g., NVLINK or PCIe topology). During initialization, Warp reports whether peer access is supported on multi-GPU systems: .. code:: text Warp 0.15.1 initialized: CUDA Toolkit 11.5, Driver 12.2 Devices: "cpu" : "x86_64" "cuda:0" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled) "cuda:1" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled) "cuda:2" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled) "cuda:3" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled) CUDA peer access: Supported fully (all-directional) If the message reports that CUDA peer access is ``Supported fully``, it means that every CUDA device can access every other CUDA device in the system. If it says ``Supported partially``, it will be followed by the access matrix that shows which devices can access each other. If it says ``Not supported``, it means that access is not supported between any devices. In code, we can check support and enable peer access like this: .. code:: python if wp.is_peer_access_supported("cuda:0", "cuda:1"): wp.set_peer_access_enabled("cuda:0", "cuda:1", True): This will allow the memory of device ``cuda:0`` to be directly accessed on device ``cuda:1``. Peer access is directional, which means that enabling access to ``cuda:0`` from ``cuda:1`` does not automatically enable access to ``cuda:1`` from ``cuda:0``. The benefit of enabling peer access is that it allows direct memory transfers (DMA) between the devices. This is generally a faster way to copy data, since otherwise the transfer needs to be done using a CPU staging buffer. The drawback is that enabling peer access can reduce the performance of allocations and deallocations. Programs that don't rely on peer-to-peer memory transfers should leave this setting disabled. It's possible to temporarily enable or disable peer access using a scoped manager: .. code:: python with wp.ScopedPeerAccess("cuda:0", "cuda:1", True): ... .. note:: Peer access does not accelerate memory transfers between arrays allocated using the :ref:`stream-ordered memory pool allocators<mempool_allocators>` introduced in Warp 0.14.0. To accelerate memory pool transfers, :ref:`memory pool access<mempool_access>` should be enabled instead. .. autofunction:: warp.is_peer_access_supported .. autofunction:: warp.is_peer_access_enabled .. autofunction:: warp.set_peer_access_enabled
10,687
reStructuredText
40.913725
366
0.688126
NVIDIA/warp/docs/modules/allocators.rst
Allocators ========== .. _mempool_allocators: Stream-Ordered Memory Pool Allocators ------------------------------------- Introduction ~~~~~~~~~~~~ Warp 0.14.0 added support for `stream-ordered memory pool allocators for CUDA arrays <https://developer.nvidia.com/blog/using-cuda-stream-ordered-memory-allocator-part-1>`_. As of Warp 0.15.0, these allocators are enabled by default on all CUDA devices that support them. "Stream-ordered memory pool allocator" is quite a mouthful, so let's unpack it one bit at a time. Whenever you create an array, the memory needs to be allocated on the device: .. code:: python a = wp.empty(n, dtype=float, device="cuda:0") b = wp.zeros(n, dtype=float, device="cuda:0") c = wp.ones(n, dtype=float, device="cuda:0") d = wp.full(n, 42.0, dtype=float, device="cuda:0") Each of the calls above allocates a block of device memory large enough to hold the array and optionally initializes the contents with the specified values. ``wp.empty()`` is the only function that does not initialize the contents in any way, it just allocates the memory. Memory pool allocators grab a block of memory from a larger pool of reserved memory, which is generally faster than asking the operating system for a brand new chunk of storage. This is an important benefit of these pooled allocators - they are faster. Stream-ordered means that each allocation is scheduled on a :ref:`CUDA stream<streams>`, which represents a sequence of instructions that execute in order on the GPU. The main benefit is that it allows memory to be allocated in CUDA graphs, which was previously not possible: .. code:: python with wp.ScopedCapture() as capture: a = wp.zeros(n, dtype=float) wp.launch(kernel, dim=a.size, inputs=[a]) wp.capture_launch(capture.graph) From now on, we will refer to these allocators as mempool allocators, for short. Configuration ~~~~~~~~~~~~~ Mempool allocators are a feature of CUDA that is supported on most modern devices and operating systems. However, there can be systems where they are not supported, such as certain virtual machine setups. Warp is designed with resiliency in mind, so existing code written prior to the introduction of these new allocators should continue to function regardless of whether they are supported by the underlying system or not. Warp's startup message gives the status of these allocators, for example: .. code-block:: text Warp 0.15.1 initialized: CUDA Toolkit 11.5, Driver 12.2 Devices: "cpu" : "x86_64" "cuda:0" : "NVIDIA GeForce RTX 4090" (24 GiB, sm_89, mempool enabled) "cuda:1" : "NVIDIA GeForce RTX 3090" (24 GiB, sm_86, mempool enabled) Note the ``mempool enabled`` text next to each CUDA device. This means that memory pools are enabled on the device. Whenever you create an array on that device, it will be allocated using the mempool allocator. If you see ``mempool supported``, it means that memory pools are supported but were not enabled on startup. If you see ``mempool not supported``, it means that memory pools can't be used on this device. There is a configuration flag that controls whether memory pools should be automatically enabled during ``wp.init()``: .. code:: python import warp as wp wp.config.enable_mempools_at_init = False wp.init() The flag defaults to ``True``, but can be set to ``False`` if desired. Changing this configuration flag after ``wp.init()`` is called has no effect. After ``wp.init()``, you can check if the memory pool is enabled on each device like this: .. code:: python if wp.is_mempool_enabled("cuda:0"): ... You can also independently control enablement on each device: .. code:: python if wp.is_mempool_supported("cuda:0"): wp.set_mempool_enabled("cuda:0", True) It's possible to temporarily enable or disable memory pools using a scoped manager: .. code:: python with wp.ScopedMempool("cuda:0", True): a = wp.zeros(n, dtype=float, device="cuda:0") with wp.ScopedMempool("cuda:0", False): b = wp.zeros(n, dtype=float, device="cuda:0") In the snippet above, array ``a`` will be allocated using the mempool allocator and array ``b`` will be allocated using the default allocator. In most cases, it shouldn't be necessary to fiddle with these enablement functions, but they are there if you need them. By default, Warp will enable memory pools on startup if they are supported, which will bring the benefits of improved allocation speed automatically. Most Warp code should continue to function with or without mempool allocators, with the exception of memory allocations during graph capture, which will raise an exception if memory pools are not enabled. .. autofunction:: warp.is_mempool_supported .. autofunction:: warp.is_mempool_enabled .. autofunction:: warp.set_mempool_enabled Allocation Performance ~~~~~~~~~~~~~~~~~~~~~~ Allocating and releasing memory are rather expensive operations that can add overhead to a program. We can't avoid them, since we need to allocate storage for our data somewhere, but there are some simple strategies that can reduce the overall impact of allocations on performance. Consider the following example: .. code:: python for i in range(100): a = wp.zeros(n, dtype=float, device="cuda:0") wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0") On each iteration of the loop, we allocate an array and run a kernel on the data. This program has 100 allocations and 100 deallocations. When we assign a new value to ``a``, the previous value gets garbage collected by Python, which triggers the deallocation. Reusing Memory ^^^^^^^^^^^^^^ If the size of the array remains fixed, consider reusing the memory on subsequent iterations. We can allocate the array only once and just re-initialize its contents on each iteration: .. code:: python # pre-allocate the array a = wp.empty(n, dtype=float, device="cuda:0") for i in range(100): # reset the contents a.zero_() wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0") This works well if the array size does not change on each iteration. If the size changes but the upper bound is known, we can still pre-allocate a buffer large enough to store all the elements at any iteration. .. code:: python # pre-allocate a big enough buffer buffer = wp.empty(MAX_N, dtype=float, device="cuda:0") for i in range(100): # get a buffer slice of size n <= MAX_N n = get_size(i) a = buffer[:n] # reset the contents a.zero_() wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0") Reusing memory this way can improve performance, but may also add undesirable complexity to our code. The mempool allocators have a useful feature that can improve allocation performance without modifying our original code in any way. Release Threshold ^^^^^^^^^^^^^^^^^ The memory pool release threshold determines how much reserved memory the allocator should hold on to before releasing it back to the operating system. For programs that frequently allocate and release memory, setting a higher release threshold can improve the performance of allocations. By default, the release threshold is set to 0. Setting it to a higher number will reduce the cost of allocations if memory was previously acquired and returned to the pool. .. code:: python # set the release threshold to reduce re-allocation overhead wp.set_mempool_release_threshold("cuda:0", 1024**3) for i in range(100): a = wp.zeros(n, dtype=float, device="cuda:0") wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0") Threshold values between 0 and 1 are interpreted as fractions of available memory. For example, 0.5 means half of the device's physical memory and 1.0 means all of the memory. Greater values are interpreted as an absolute number of bytes. For example, 1024**3 means one GiB of memory. This is a simple optimization that can improve the performance of programs without modifying the existing code in any way. .. autofunction:: warp.set_mempool_release_threshold Graph Allocations ~~~~~~~~~~~~~~~~~ Mempool allocators can be used in CUDA graphs, which means that you can capture Warp code that creates arrays: .. code:: python with wp.ScopedCapture() as capture: a = wp.full(n, 42, dtype=float) wp.capture_launch(capture.graph) print(a) Capturing allocations is similar to capturing other operations like kernel launches or memory copies. During capture, the operations don't actually execute, but are recorded. To execute the captured operations, we must launch the graph using :func:`wp.capture_launch() <capture_launch>`. This is important to keep in mind if you want to use an array that was allocated during graph capture. The array doesn't actually exist until the captured graph is launched. In the snippet above, we would get an error if we tried to print the array before calling :func:`wp.capture_launch() <capture_launch>`. More generally, the ability to allocate memory during graph capture greatly increases the range of code that can be captured in a graph. This includes any code that creates temporary allocations. CUDA graphs can be used to re-run operations with minimal CPU overhead, which can yield dramatic performance improvements. .. _mempool_access: Memory Pool Access ~~~~~~~~~~~~~~~~~~ On multi-GPU systems that support :ref:`peer access<peer_access>`, we can enable directly accessing a memory pool from a different device: .. code:: python if wp.is_mempool_access_supported("cuda:0", "cuda:1"): wp.set_mempool_access_enabled("cuda:0", "cuda:1", True): This will allow the memory pool of device ``cuda:0`` to be directly accessed on device ``cuda:1``. Memory pool access is directional, which means that enabling access to ``cuda:0`` from ``cuda:1`` does not automatically enable access to ``cuda:1`` from ``cuda:0``. The benefit of enabling memory pool access is that it allows direct memory transfers (DMA) between the devices. This is generally a faster way to copy data, since otherwise the transfer needs to be done using a CPU staging buffer. The drawback is that enabling memory pool access can slightly reduce the performance of allocations and deallocations. However, for applications that rely on copying memory between devices, there should be a net benefit. It's possible to temporarily enable or disable memory pool access using a scoped manager: .. code:: python with wp.ScopedMempoolAccess("cuda:0", "cuda:1", True): a0 = wp.zeros(n, dtype=float, device="cuda:0") a1 = wp.empty(n, dtype=float, device="cuda:1") # use direct memory transfer between GPUs wp.copy(a1, a0) Note that memory pool access only applies to memory allocated using mempool allocators. For memory allocated using default CUDA allocators, we can enable CUDA peer access to get similar benefits. Because enabling memory pool access can have drawbacks, Warp does not automatically enable it, even if it's supported. Programs that don't require copying data between GPUs are therefore not affected in any way. .. autofunction:: warp.is_mempool_access_supported .. autofunction:: warp.is_mempool_access_enabled .. autofunction:: warp.set_mempool_access_enabled Limitations ~~~~~~~~~~~ Mempool-to-Mempool Copies Between GPUs During Graph Capture ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Copying data between different GPUs will fail during graph capture if the source and destination are allocated using mempool allocators and mempool access is not enabled between devices. Note that this only applies to capturing mempool-to-mempool copies in a graph; copies done outside of graph capture are not affected. Copies within the same mempool (i.e., same device) are also not affected. There are two workarounds. If mempool access is supported, you can simply enable mempool access between the devices prior to graph capture, as shown in :ref:`mempool_access`. If mempool access is not supported, you will need to pre-allocate the arrays involved in the copy using the default CUDA allocators. This will need to be done before capture begins: .. code:: python # pre-allocate the arrays with mempools disabled with wp.ScopedMempool("cuda:0", False): a0 = wp.zeros(n, dtype=float, device="cuda:0") with wp.ScopedMempool("cuda:1", False): a1 = wp.empty(n, dtype=float, device="cuda:1") with wp.ScopedCapture("cuda:1") as capture: wp.copy(a1, a0) wp.capture_launch(capture.graph) This is due to a limitation in CUDA, which we envision being fixed in the future.
12,785
reStructuredText
47.615969
602
0.730153
NVIDIA/warp/docs/modules/render.rst
warp.render =============================== .. currentmodule:: warp.render The ``warp.render`` module provides a set of renderers that can be used for visualizing scenes involving shapes of various types. Built on top of these stand-alone renderers, the ``warp.sim.render`` module provides renderers that can be used to visualize scenes directly from ``warp.sim.ModelBuilder`` objects and update them from ``warp.sim.State`` objects. .. .. toctree:: :maxdepth: 2 Stand-alone renderers --------------------- The ``OpenGLRenderer`` provides an interactive renderer to play back animations in real time, the ``UsdRenderer`` provides a renderer that exports the scene to a USD file that can be rendered in a renderer of your choice. .. autoclass:: UsdRenderer :members: .. autoclass:: OpenGLRenderer :members: Simulation renderers -------------------- Based on these renderers from ``warp.render``, the ``SimRendererUsd`` (which equals ``SimRenderer``) and ``SimRendererOpenGL`` classes from ``warp.sim.render`` are derived to populate the renderers directly from ``warp.sim.ModelBuilder`` scenes and update them from ``warp.sim.State`` objects. .. currentmodule:: warp.sim.render .. autoclass:: SimRendererUsd :members: .. autoclass:: SimRendererOpenGL :members:
1,299
reStructuredText
32.333333
293
0.704388
NVIDIA/warp/docs/modules/interoperability.rst
Interoperability ================ Warp can interop with other Python-based frameworks such as NumPy through standard interface protocols. NumPy ----- Warp arrays may be converted to a NumPy array through the ``warp.array.numpy()`` method. When the Warp array lives on the ``cpu`` device this will return a zero-copy view onto the underlying Warp allocation. If the array lives on a ``cuda`` device then it will first be copied back to a temporary buffer and copied to NumPy. Warp CPU arrays also implement the ``__array_interface__`` protocol and so can be used to construct NumPy arrays directly:: w = wp.array([1.0, 2.0, 3.0], dtype=float, device="cpu") a = np.array(w) print(a) > [1. 2. 3.] Data type conversion utilities are also available for convenience: .. code:: python warp_type = wp.float32 ... numpy_type = wp.dtype_to_numpy(warp_type) ... a = wp.zeros(n, dtype=warp_type) b = np.zeros(n, dtype=numpy_type) To create Warp arrays from NumPy arrays, use :func:`warp.from_numpy` or pass the NumPy array as the ``data`` argument of the :class:`warp.array` constructor directly. .. autofunction:: warp.from_numpy .. autofunction:: warp.dtype_from_numpy .. autofunction:: warp.dtype_to_numpy .. _pytorch-interop: PyTorch ------- Warp provides helper functions to convert arrays to/from PyTorch:: w = wp.array([1.0, 2.0, 3.0], dtype=float, device="cpu") # convert to Torch tensor t = wp.to_torch(w) # convert from Torch tensor w = wp.from_torch(t) These helper functions allow the conversion of Warp arrays to/from PyTorch tensors without copying the underlying data. At the same time, if available, gradient arrays and tensors are converted to/from PyTorch autograd tensors, allowing the use of Warp arrays in PyTorch autograd computations. .. autofunction:: warp.from_torch .. autofunction:: warp.to_torch .. autofunction:: warp.device_from_torch .. autofunction:: warp.device_to_torch .. autofunction:: warp.dtype_from_torch .. autofunction:: warp.dtype_to_torch To convert a PyTorch CUDA stream to a Warp CUDA stream and vice versa, Warp provides the following functions: .. autofunction:: warp.stream_from_torch .. autofunction:: warp.stream_to_torch Example: Optimization using ``warp.from_torch()`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ An example usage of minimizing a loss function over an array of 2D points written in Warp via PyTorch's Adam optimizer using :func:`warp.from_torch` is as follows:: import warp as wp import torch @wp.kernel() def loss(xs: wp.array(dtype=float, ndim=2), l: wp.array(dtype=float)): tid = wp.tid() wp.atomic_add(l, 0, xs[tid, 0] ** 2.0 + xs[tid, 1] ** 2.0) # indicate requires_grad so that Warp can accumulate gradients in the grad buffers xs = torch.randn(100, 2, requires_grad=True) l = torch.zeros(1, requires_grad=True) opt = torch.optim.Adam([xs], lr=0.1) wp_xs = wp.from_torch(xs) wp_l = wp.from_torch(l) tape = wp.Tape() with tape: # record the loss function kernel launch on the tape wp.launch(loss, dim=len(xs), inputs=[wp_xs], outputs=[wp_l], device=wp_xs.device) for i in range(500): tape.zero() tape.backward(loss=wp_l) # compute gradients # now xs.grad will be populated with the gradients computed by Warp opt.step() # update xs (and thereby wp_xs) # these lines are only needed for evaluating the loss # (the optimization just needs the gradient, not the loss value) wp_l.zero_() wp.launch(loss, dim=len(xs), inputs=[wp_xs], outputs=[wp_l], device=wp_xs.device) print(f"{i}\tloss: {l.item()}") Example: Optimization using ``warp.to_torch`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Less code is needed when we declare the optimization variables directly in Warp and use :func:`warp.to_torch` to convert them to PyTorch tensors. Here, we revisit the same example from above where now only a single conversion to a torch tensor is needed to supply Adam with the optimization variables:: import warp as wp import numpy as np import torch @wp.kernel() def loss(xs: wp.array(dtype=float, ndim=2), l: wp.array(dtype=float)): tid = wp.tid() wp.atomic_add(l, 0, xs[tid, 0] ** 2.0 + xs[tid, 1] ** 2.0) # initialize the optimization variables in Warp xs = wp.array(np.random.randn(100, 2), dtype=wp.float32, requires_grad=True) l = wp.zeros(1, dtype=wp.float32, requires_grad=True) # just a single wp.to_torch call is needed, Adam optimizes using the Warp array gradients opt = torch.optim.Adam([wp.to_torch(xs)], lr=0.1) tape = wp.Tape() with tape: wp.launch(loss, dim=len(xs), inputs=[xs], outputs=[l], device=xs.device) for i in range(500): tape.zero() tape.backward(loss=l) opt.step() l.zero_() wp.launch(loss, dim=len(xs), inputs=[xs], outputs=[l], device=xs.device) print(f"{i}\tloss: {l.numpy()[0]}") Example: Optimization using ``torch.autograd.function`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ One can insert Warp kernel launches in a PyTorch graph by defining a :class:`torch.autograd.Function` class, which requires forward and backward functions to be defined. After mapping incoming torch arrays to Warp arrays, a Warp kernel may be launched in the usual way. In the backward pass, the same kernel's adjoint may be launched by setting ``adjoint = True`` in :func:`wp.launch() <launch>`. Alternatively, the user may choose to rely on Warp's tape. In the following example, we demonstrate how Warp may be used to evaluate the Rosenbrock function in an optimization context:: import warp as wp import numpy as np import torch pvec2 = wp.types.vector(length=2, dtype=wp.float32) # Define the Rosenbrock function @wp.func def rosenbrock(x: float, y: float): return (1.0 - x) ** 2.0 + 100.0 * (y - x**2.0) ** 2.0 @wp.kernel def eval_rosenbrock( xs: wp.array(dtype=pvec2), # outputs z: wp.array(dtype=float), ): i = wp.tid() x = xs[i] z[i] = rosenbrock(x[0], x[1]) class Rosenbrock(torch.autograd.Function): @staticmethod def forward(ctx, xy, num_points): # ensure Torch operations complete before running Warp wp.synchronize_device() ctx.xy = wp.from_torch(xy, dtype=pvec2, requires_grad=True) ctx.num_points = num_points # allocate output ctx.z = wp.zeros(num_points, requires_grad=True) wp.launch( kernel=eval_rosenbrock, dim=ctx.num_points, inputs=[ctx.xy], outputs=[ctx.z] ) # ensure Warp operations complete before returning data to Torch wp.synchronize_device() return wp.to_torch(ctx.z) @staticmethod def backward(ctx, adj_z): # ensure Torch operations complete before running Warp wp.synchronize_device() # map incoming Torch grads to our output variables ctx.z.grad = wp.from_torch(adj_z) wp.launch( kernel=eval_rosenbrock, dim=ctx.num_points, inputs=[ctx.xy], outputs=[ctx.z], adj_inputs=[ctx.xy.grad], adj_outputs=[ctx.z.grad], adjoint=True ) # ensure Warp operations complete before returning data to Torch wp.synchronize_device() # return adjoint w.r.t. inputs return (wp.to_torch(ctx.xy.grad), None) num_points = 1500 learning_rate = 5e-2 torch_device = wp.device_to_torch(wp.get_device()) rng = np.random.default_rng(42) xy = torch.tensor(rng.normal(size=(num_points, 2)), dtype=torch.float32, requires_grad=True, device=torch_device) opt = torch.optim.Adam([xy], lr=learning_rate) for _ in range(10000): # step opt.zero_grad() z = Rosenbrock.apply(xy, num_points) z.backward(torch.ones_like(z)) opt.step() # minimum at (1, 1) xy_np = xy.numpy(force=True) print(np.mean(xy_np, axis=0)) Note that if Warp code is wrapped in a torch.autograd.function that gets called in ``torch.compile()``, it will automatically exclude that function from compiler optimizations. If your script uses ``torch.compile()``, we recommend using Pytorch version 2.3.0+, which has improvements that address this scenario. CuPy/Numba ---------- Warp GPU arrays support the ``__cuda_array_interface__`` protocol for sharing data with other Python GPU frameworks. Currently this is one-directional, so that Warp arrays can be used as input to any framework that also supports the ``__cuda_array_interface__`` protocol, but not the other way around. .. _jax-interop: JAX --- Interoperability with JAX arrays is supported through the following methods. Internally these use the DLPack protocol to exchange data in a zero-copy way with JAX:: warp_array = wp.from_jax(jax_array) jax_array = wp.to_jax(warp_array) It may be preferable to use the :ref:`DLPack` protocol directly for better performance and control over stream synchronization behaviour. .. autofunction:: warp.from_jax .. autofunction:: warp.to_jax .. autofunction:: warp.device_from_jax .. autofunction:: warp.device_to_jax .. autofunction:: warp.dtype_from_jax .. autofunction:: warp.dtype_to_jax Using Warp kernels as JAX primitives ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. note:: This is an experimental feature under development. Warp kernels can be used as JAX primitives, which can be used to call Warp kernels inside of jitted JAX functions:: import warp as wp import jax import jax.numpy as jp # import experimental feature from warp.jax_experimental import jax_kernel @wp.kernel def triple_kernel(input: wp.array(dtype=float), output: wp.array(dtype=float)): tid = wp.tid() output[tid] = 3.0 * input[tid] # create a Jax primitive from a Warp kernel jax_triple = jax_kernel(triple_kernel) # use the Warp kernel in a Jax jitted function @jax.jit def f(): x = jp.arange(0, 64, dtype=jp.float32) return jax_triple(x) print(f()) Since this is an experimental feature, there are some limitations: - All kernel arguments must be arrays. - Kernel launch dimensions are inferred from the shape of the first argument. - Input arguments are followed by output arguments in the Warp kernel definition. - There must be at least one input argument and at least one output argument. - Output shapes must match the launch dimensions (i.e., output shapes must match the shape of the first argument). - All arrays must be contiguous. - Only the CUDA backend is supported. Here is an example of an operation with three inputs and two outputs:: import warp as wp import jax import jax.numpy as jp # import experimental feature from warp.jax_experimental import jax_kernel # kernel with multiple inputs and outputs @wp.kernel def multiarg_kernel( # inputs a: wp.array(dtype=float), b: wp.array(dtype=float), c: wp.array(dtype=float), # outputs ab: wp.array(dtype=float), bc: wp.array(dtype=float), ): tid = wp.tid() ab[tid] = a[tid] + b[tid] bc[tid] = b[tid] + c[tid] # create a Jax primitive from a Warp kernel jax_multiarg = jax_kernel(multiarg_kernel) # use the Warp kernel in a Jax jitted function with three inputs and two outputs @jax.jit def f(): a = jp.full(64, 1, dtype=jp.float32) b = jp.full(64, 2, dtype=jp.float32) c = jp.full(64, 3, dtype=jp.float32) return jax_multiarg(a, b, c) x, y = f() print(x) print(y) .. _DLPack: DLPack ------ Warp supports the DLPack protocol included in the Python Array API standard v2022.12. See the `Python Specification for DLPack <https://dmlc.github.io/dlpack/latest/python_spec.html>`_ for reference. The canonical way to import an external array into Warp is using the ``warp.from_dlpack()`` function:: warp_array = wp.from_dlpack(external_array) The external array can be a PyTorch tensor, Jax array, or any other array type compatible with this version of the DLPack protocol. For CUDA arrays, this approach requires the producer to perform stream synchronization which ensures that operations on the array are ordered correctly. The ``warp.from_dlpack()`` function asks the producer to synchronize the current Warp stream on the device where the array resides. Thus it should be safe to use the array in Warp kernels on that device without any additional synchronization. The canonical way to export a Warp array to an external framework is to use the ``from_dlpack()`` function in that framework:: jax_array = jax.dlpack.from_dlpack(warp_array) torch_tensor = torch.utils.dlpack.from_dlpack(warp_array) For CUDA arrays, this will synchronize the current stream of the consumer framework with the current Warp stream on the array's device. Thus it should be safe to use the wrapped array in the consumer framework, even if the array was previously used in a Warp kernel on the device. Alternatively, arrays can be shared by explicitly creating PyCapsules using a ``to_dlpack()`` function provided by the producer framework. This approach may be used for older versions of frameworks that do not support the v2022.12 standard:: warp_array1 = wp.from_dlpack(jax.dlpack.to_dlpack(jax_array)) warp_array2 = wp.from_dlpack(torch.utils.dlpack.to_dlpack(torch_tensor)) jax_array = jax.dlpack.from_dlpack(wp.to_dlpack(warp_array)) torch_tensor = torch.utils.dlpack.from_dlpack(wp.to_dlpack(warp_array)) This approach is generally faster because it skips any stream synchronization, but another solution must be used to ensure correct ordering of operations. In situations where no synchronization is required, using this approach can yield better performance. This may be a good choice in situations like these: - The external framework is using the synchronous CUDA default stream. - Warp and the external framework are using the same CUDA stream. - Another synchronization mechanism is already in place. .. autofunction:: warp.from_dlpack .. autofunction:: warp.to_dlpack
14,587
reStructuredText
35.108911
156
0.667923
NVIDIA/warp/docs/modules/concurrency.rst
Concurrency =========== .. currentmodule:: warp Asynchronous Operations ----------------------- Kernel Launches ~~~~~~~~~~~~~~~ Kernels launched on a CUDA device are asynchronous with respect to the host (CPU Python thread). Launching a kernel schedules its execution on the CUDA device, but the :func:`wp.launch() <launch>` function can return before the kernel execution completes. This allows us to run some CPU computations while the CUDA kernel is executing, which is an easy way to introduce parallelism into our programs. .. code:: python wp.launch(kernel1, dim=n, inputs=[a], device="cuda:0") # do some CPU work while the CUDA kernel is running do_cpu_work() Kernels launched on different CUDA devices can execute concurrently. This can be used to tackle independent sub-tasks in parallel on different GPUs while using the CPU to do other useful work: .. code:: python # launch concurrent kernels on different devices wp.launch(kernel1, dim=n, inputs=[a0], device="cuda:0") wp.launch(kernel2, dim=n, inputs=[a1], device="cuda:1") # do CPU work while kernels are running on both GPUs do_cpu_work() Launching kernels on the CPU is currently a synchronous operation. In other words, :func:`wp.launch() <launch>` will return only after the kernel has finished executing on the CPU. To run a CUDA kernel and a CPU kernel concurrently, the CUDA kernel should be launched first: .. code:: python # schedule a kernel on a CUDA device wp.launch(kernel1, ..., device="cuda:0") # run a kernel on the CPU while the CUDA kernel is running wp.launch(kernel2, ..., device="cpu") Graph Launches ~~~~~~~~~~~~~~ The concurrency rules for CUDA graph launches are similar to CUDA kernel launches, except that graphs are not available on the CPU. .. code:: python # capture work on cuda:0 in a graph with wp.ScopedCapture(device="cuda:0") as capture0: do_gpu0_work() # capture work on cuda:1 in a graph with wp.ScopedCapture(device="cuda:1") as capture1: do_gpu1_work() # launch captured graphs on the respective devices concurrently wp.capture_launch(capture0.graph) wp.capture_launch(capture1.graph) # do some CPU work while the CUDA graphs are running do_cpu_work() Array Creation ~~~~~~~~~~~~~~ Creating CUDA arrays is also asynchronous with respect to the host. It involves allocating memory on the device and initializing it, which is done under the hood using a kernel launch or an asynchronous CUDA memset operation. .. code:: python a0 = wp.zeros(n, dtype=float, device="cuda:0") b0 = wp.ones(n, dtype=float, device="cuda:0") a1 = wp.empty(n, dtype=float, device="cuda:1") b1 = wp.full(n, 42.0, dtype=float, device="cuda:1") In this snippet, arrays ``a0`` and ``b0`` are created on device ``cuda:0`` and arrays ``a1`` and ``b1`` are created on device ``cuda:1``. The operations on the same device are sequential, but each device executes them independently of the other device, so they can run concurrently. Array Copying ~~~~~~~~~~~~~ Copying arrays between devices can also be asynchronous, but there are some details to be aware of. Copying from host memory to a CUDA device and copying from a CUDA device to host memory is asynchronous only if the host array is pinned. Pinned memory allows the CUDA driver to use direct memory transfers (DMA), which are generally faster and can be done without involving the CPU. There are a couple of drawbacks to using pinned memory: allocation and deallocation is usually slower and there are system-specific limits on how much pinned memory can be allocated on the system. For this reason, Warp CPU arrays are not pinned by default. You can request a pinned allocation by passing the ``pinned=True`` flag when creating a CPU array. This is a good option for arrays that are used to copy data between host and device, especially if asynchronous transfers are desired. .. code:: python h = wp.zeros(n, dtype=float, device="cpu") p = wp.zeros(n, dtype=float, device="cpu", pinned=True) d = wp.zeros(n, dtype=float, device="cuda:0") # host-to-device copy wp.copy(d, h) # synchronous wp.copy(d, p) # asynchronous # device-to-host copy wp.copy(h, d) # synchronous wp.copy(p, d) # asynchronous # wait for asynchronous operations to complete wp.synchronize_device("cuda:0") Copying between CUDA arrays on the same device is always asynchronous with respect to the host, since it does not involve the CPU: .. code:: python a = wp.zeros(n, dtype=float, device="cuda:0") b = wp.empty(n, dtype=float, device="cuda:0") # asynchronous device-to-device copy wp.copy(a, b) # wait for transfer to complete wp.synchronize_device("cuda:0") Copying between CUDA arrays on different devices is also asynchronous with respect to the host. Peer-to-peer transfers require extra care, because CUDA devices are also asynchronous with respect to each other. When copying an array from one GPU to another, the destination GPU is used to perform the copy, so we need to ensure that prior work on the source GPU completes before the transfer. .. code:: python a0 = wp.zeros(n, dtype=float, device="cuda:0") a1 = wp.empty(n, dtype=float, device="cuda:1") # wait for outstanding work on the source device to complete to ensure the source array is ready wp.synchronize_device("cuda:0") # asynchronous peer-to-peer copy wp.copy(a1, a0) # wait for the copy to complete on the destination device wp.synchronize_device("cuda:1") Note that peer-to-peer transfers can be accelerated using :ref:`memory pool access <mempool_access>` or :ref:`peer access <peer_access>`, which enables DMA transfers between CUDA devices on supported systems. .. _streams: Streams ------- A CUDA stream is a sequence of operations that execute in order on the GPU. Operations from different streams may run concurrently and may be interleaved by the device scheduler. Warp automatically creates a stream for each CUDA device during initialization. This becomes the current stream for the device. All kernel launches and memory operations issued on that device are placed on the current stream. Creating Streams ~~~~~~~~~~~~~~~~ A stream is tied to a particular CUDA device. New streams can be created using the :class:`wp.Stream <Stream>` constructor: .. code:: python s1 = wp.Stream("cuda:0") # create a stream on a specific CUDA device s2 = wp.Stream() # create a stream on the default device If the device parameter is omitted, the default device will be used, which can be managed using :class:`wp.ScopedDevice <ScopedDevice>`. For interoperation with external code, it is possible to pass a CUDA stream handle to wrap an external stream: .. code:: python s3 = wp.Stream("cuda:0", cuda_stream=stream_handle) The ``cuda_stream`` argument must be a native stream handle (``cudaStream_t`` or ``CUstream``) passed as a Python integer. This mechanism is used internally for sharing streams with external frameworks like PyTorch or DLPack. The caller is responsible for ensuring that the external stream does not get destroyed while it is referenced by a ``wp.Stream`` object. Using Streams ~~~~~~~~~~~~~ Use :class:`wp.ScopedStream <ScopedStream>` to temporarily change the current stream on a device and schedule a sequence of operations on that stream: .. code:: python stream = wp.Stream("cuda:0") with wp.ScopedStream(stream): a = wp.zeros(n, dtype=float) b = wp.empty(n, dtype=float) wp.launch(kernel, dim=n, inputs=[a]) wp.copy(b, a) Since streams are tied to a particular device, :class:`wp.ScopedStream <ScopedStream>` subsumes the functionality of :class:`wp.ScopedDevice <ScopedDevice>`. That's why we don't need to explicitly specify the ``device`` argument to each of the calls. An important benefit of streams is that they can be used to overlap compute and data transfer operations on the same device, which can improve the overall throughput of a program by doing those operations in parallel. .. code:: python with wp.ScopedDevice("cuda:0"): a = wp.zeros(n, dtype=float) b = wp.empty(n, dtype=float) c = wp.ones(n, dtype=float, device="cpu", pinned=True) compute_stream = wp.Stream() transfer_stream = wp.Stream() # asynchronous kernel launch on a stream with wp.ScopedStream(compute_stream) wp.launch(kernel, dim=a.size, inputs=[a]) # asynchronous host-to-device copy on another stream with wp.ScopedStream(transfer_stream) wp.copy(b, c) The :func:`wp.get_stream() <get_stream>` function can be used to get the current stream on a device: .. code:: python s1 = wp.get_stream("cuda:0") # get the current stream on a specific device s2 = wp.get_stream() # get the current stream on the default device The :func:`wp.set_stream() <set_stream>` function can be used to set the current stream on a device: .. code:: python wp.set_stream(stream, device="cuda:0") # set the stream on a specific device wp.set_stream(stream) # set the stream on the default device In general, we recommend using :class:`wp.ScopedStream <ScopedStream>` rather than :func:`wp.set_stream() <set_stream>`. Synchronization ~~~~~~~~~~~~~~~ The :func:`wp.synchronize_stream() <synchronize_stream>` function can be used to block the host thread until the given stream completes: .. code:: python wp.synchronize_stream(stream) In a program that uses multiple streams, this gives a more fine-grained level of control over synchronization behavior than :func:`wp.synchronize_device() <synchronize_device>`, which synchronizes all streams on the device. For example, if a program has multiple compute and transfer streams, the host might only want to wait for one transfer stream to complete, without waiting for the other streams. By synchronizing only one stream, we allow the others to continue running concurrently with the host thread. .. _cuda_events: Events ~~~~~~ Functions like :func:`wp.synchronize_device() <synchronize_device>` or :func:`wp.synchronize_stream() <synchronize_stream>` block the CPU thread until work completes on a CUDA device, but they're not intended to synchronize multiple CUDA streams with each other. CUDA events provide a mechanism for device-side synchronization between streams. This kind of synchronization does not block the host thread, but it allows one stream to wait for work on another stream to complete. Like streams, events are tied to a particular device: .. code:: python e1 = wp.Event("cuda:0") # create an event on a specific CUDA device e2 = wp.Event() # create an event on the default device To wait for a stream to complete some work, we first record the event on that stream. Then we make another stream wait on that event: .. code:: python stream1 = wp.Stream("cuda:0") stream2 = wp.Stream("cuda:0") event = wp.Event("cuda:0") stream1.record_event(event) stream2.wait_event(event) Note that when recording events, the event must be from the same device as the recording stream. When waiting for events, the waiting stream can be from another device. This allows using events to synchronize streams on different GPUs. If the ``record_event()`` method is called without an event argument, a temporary event will be created, recorded, and returned: .. code:: python event = stream1.record_event() stream2.wait_event(event) The ``wait_stream()`` method combines the acts of recording and waiting on an event in one call: .. code:: python stream2.wait_stream(stream1) Warp also provides global functions :func:`wp.record_event() <record_event>`, :func:`wp.wait_event() <wait_event>`, and :func:`wp.wait_stream() <wait_stream>` which operate on the current stream of the default device: .. code:: python wp.record_event(event) # record an event on the current stream wp.wait_event(event) # make the current stream wait for an event wp.wait_stream(stream) # make the current stream wait for another stream These variants are convenient to use inside of :class:`wp.ScopedStream <ScopedStream>` and :class:`wp.ScopedDevice <ScopedDevice>` managers. Here is a more complete example with a producer stream that copies data into an array and a consumer stream that uses the array in a kernel: .. code:: python with wp.ScopedDevice("cuda:0"): a = wp.empty(n, dtype=float) b = wp.ones(n, dtype=float, device="cpu", pinned=True) producer_stream = wp.Stream() consumer_stream = wp.Stream() with wp.ScopedStream(producer_stream) # asynchronous host-to-device copy wp.copy(a, b) # record an event to create a synchronization point for the consumer stream event = wp.record_event() # do some unrelated work in the producer stream do_other_producer_work() with wp.ScopedStream(consumer_stream) # do some unrelated work in the consumer stream do_other_consumer_work() # wait for the producer copy to complete wp.wait_event(event) # consume the array in a kernel wp.launch(kernel, dim=a.size, inputs=[a]) The function :func:`wp.synchronize_event() <synchronize_event>` can be used to block the host thread until a recorded event completes. This is useful when the host wants to wait for a specific synchronization point on a stream, while allowing subsequent stream operations to continue executing asynchronously. .. code:: python with wp.ScopedDevice("cpu"): # CPU buffers for readback a_host = wp.empty(N, dtype=float, pinned=True) b_host = wp.empty(N, dtype=float, pinned=True) with wp.ScopedDevice("cuda:0"): stream = wp.get_stream() # initialize first GPU array a = wp.full(N, 17, dtype=float) # asynchronous readback wp.copy(a_host, a) # record event a_event = stream.record_event() # initialize second GPU array b = wp.full(N, 42, dtype=float) # asynchronous readback wp.copy(b_host, b) # record event b_event = stream.record_event() # wait for first array readback to complete wp.synchronize_event(a_event) # process first array on the CPU assert np.array_equal(a_host.numpy(), np.full(N, fill_value=17.0)) # wait for second array readback to complete wp.synchronize_event(b_event) # process second array on the CPU assert np.array_equal(b_host.numpy(), np.full(N, fill_value=42.0)) CUDA Default Stream ~~~~~~~~~~~~~~~~~~~ Warp avoids using the synchronous CUDA default stream, which is a special stream that synchronizes with all other streams on the same device. This stream is currently only used during readback operations that are provided for convenience, such as ``array.numpy()`` and ``array.list()``. .. code:: python stream1 = wp.Stream("cuda:0") stream2 = wp.Stream("cuda:0") with wp.ScopedStream(stream1): a = wp.zeros(n, dtype=float) with wp.ScopedStream(stream2): b = wp.ones(n, dtype=float) print(a) print(b) In the snippet above, there are two arrays that are initialized on different CUDA streams. Printing those arrays triggers a readback, which is done using the ``array.numpy()`` method. This readback happens on the synchronous CUDA default stream, which means that no explicit synchronization is required. The reason for this is convenience - printing an array is useful for debugging purposes, so it's nice not to worry about synchronization. The drawback of this approach is that the CUDA default stream (and any methods that use it) cannot be used during graph capture. The regular :func:`wp.copy() <copy>` function should be used to capture readback operations in a graph. Explicit Streams Arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~ Several Warp functions accept optional ``stream`` arguments. This allows directly specifying the stream without using a :class:`wp.ScopedStream <ScopedStream>` manager. There are benefits and drawbacks to both approaches, which will be discussed below. Functions that accept stream arguments directly include :func:`wp.launch() <launch>`, :func:`wp.capture_launch() <capture_launch>`, and :func:`wp.copy() <copy>`. To launch a kernel on a specific stream: .. code:: python wp.launch(kernel, dim=n, inputs=[...], stream=my_stream) When launching a kernel with an explicit ``stream`` argument, the ``device`` argument should be omitted, since the device is inferred from the stream. If both ``stream`` and ``device`` are specified, the ``stream`` argument takes precedence. To launch a graph on a specific stream: .. code:: python wp.capture_launch(graph, stream=my_stream) For both kernel and graph launches, specifying the stream directly can be faster than using :class:`wp.ScopedStream <ScopedStream>`. While :class:`wp.ScopedStream <ScopedStream>` is useful for scheduling a sequence of operations on a specific stream, there is some overhead in setting and restoring the current stream on the device. This overhead is negligible for larger workloads, but performance-sensitive code may benefit from specifying the stream directly instead of using :class:`wp.ScopedStream <ScopedStream>`, especially for a single kernel or graph launch. In addition to these performance considerations, specifying the stream directly can be useful when copying arrays between two CUDA devices. By default, Warp uses the following rules to determine which stream will be used for the copy: - If the destination array is on a CUDA device, use the current stream on the destination device. - Otherwise, if the source array is on a CUDA device, use the current stream on the source device. In the case of peer-to-peer copies, specifying the ``stream`` argument allows overriding these rules, and the copy can be performed on a stream from any device. .. code:: python stream0 = wp.get_stream("cuda:0") stream1 = wp.get_stream("cuda:1") a0 = wp.zeros(n, dtype=float, device="cuda:0") a1 = wp.empty(n, dtype=float, device="cuda:1") # wait for the destination array to be ready stream0.wait_stream(stream1) # use the source device stream to do the copy wp.copy(a1, a0, stream=stream0) Notice that we use event synchronization to make the source stream wait for the destination stream prior to the copy. This is due to the :ref:`stream-ordered memory pool allocators<mempool_allocators>` introduced in Warp 0.14.0. The allocation of the empty array ``a1`` is scheduled on stream ``stream1``. To avoid use-before-alloc errors, we need to wait until the allocation completes before using that array on a different stream. Stream Usage Guidance ~~~~~~~~~~~~~~~~~~~~~ Stream synchronization can be a tricky business, even for experienced CUDA developers. Consider the following code: .. code:: python a = wp.zeros(n, dtype=float, device="cuda:0") s = wp.Stream("cuda:0") wp.launch(kernel, dim=a.size, inputs=[a], stream=s) This snippet has a stream synchronization problem that is difficult to detect at first glance. It's quite possible that the code will work just fine, but it introduces undefined behaviour, which may lead to incorrect results that manifest only once in a while. The issue is that the kernel is launched on stream ``s``, which is different than the stream used for creating array ``a``. The array is allocated and initialized on the current stream of device ``cuda:0``, which means that it might not be ready when stream ``s`` begins executing the kernel that consumes the array. The solution is to synchronize the streams, which can be done like this: .. code:: python a = wp.zeros(n, dtype=float, device="cuda:0") s = wp.Stream("cuda:0") # wait for the current stream on cuda:0 to finish initializing the array s.wait_stream(wp.get_stream("cuda:0")) wp.launch(kernel, dim=a.size, inputs=[a], stream=s) The :class:`wp.ScopedStream <ScopedStream>` manager is designed to alleviate this common problem. It synchronizes the new stream with the previous stream on the device. Its behavior is equivalent to inserting the ``wait_stream()`` call as shown above. With :class:`wp.ScopedStream <ScopedStream>`, we don't need to explicitly sync the new stream with the previous stream: .. code:: python a = wp.zeros(n, dtype=float, device="cuda:0") s = wp.Stream("cuda:0") with wp.ScopedStream(s): wp.launch(kernel, dim=a.size, inputs=[a]) This makes :class:`wp.ScopedStream <ScopedStream>` the recommended way of getting started with streams in Warp. Using explicit stream arguments might be slightly more performant, but it requires more attention to stream synchronization mechanics. If you are a stream novice, consider the following trajectory for integrating streams into your Warp programs: - Level 1: Don't. You don't need to use streams to use Warp. Avoiding streams is a perfectly valid and respectable way to live. Many interesting and sophisticated algorithms can be developed without fancy stream juggling. Often it's better to focus on solving a problem in a simple and elegant way, unencumbered by the vagaries of low-level stream management. - Level 2: Use :class:`wp.ScopedStream <ScopedStream>`. It helps to avoid some common hard-to-catch issues. There's a little bit of overhead, but it should be negligible if the GPU workloads are large enough. Consider adding streams into your program as a form of targeted optimization, especially if some areas like memory transfers ("feeding the beast") are a known bottleneck. Streams are great for overlapping memory transfers with compute workloads. - Level 3: Use explicit stream arguments for kernel launches, array copying, etc. This will be the most performant approach that can get you close to the speed of light. You will need to take care of all stream synchronization yourself, but the results can be rewarding in the benchmarks. .. _synchronization_guidance: Synchronization Guidance ------------------------ The general rule with synchronization is to use as little of it as possible, but not less. Excessive synchronization can severely limit the performance of programs. Synchronization means that a stream or thread is waiting for something else to complete. While it's waiting, it's not doing any useful work, which means that any outstanding work cannot start until the synchronization point is reached. This limits parallel execution, which is often important for squeezing the most juice out of the collection of hardware components. On the other hand, insufficient synchronization can lead to errors or incorrect results if operations execute out-of-order. A fast program is no good if it can't guarantee correct results. Host-side Synchronization ~~~~~~~~~~~~~~~~~~~~~~~~~ Host-side synchronization blocks the host thread (Python) until GPU work completes. This is necessary when you are waiting for some GPU work to complete so that you can access the results on the CPU. :func:`wp.synchronize() <synchronize>` is the most heavy-handed synchronization function, since it synchronizes all the devices in the system. It is almost never the right function to call if performance is important. However, it can sometimes be useful when debugging synchronization-related issues. :func:`wp.synchronize_device(device) <synchronize_device>` synchronizes a single device, which is generally better and faster. This synchronizes all the streams on the specified device, including streams created by Warp and those created by any other framework. :func:`wp.synchronize_stream(stream) <synchronize_stream>` synchronizes a single stream, which is better still. If the program uses multiple streams, you can wait for a specific one to finish without waiting for the others. This is handy if you have a readback stream that is copying data from the GPU to the CPU. You can wait for the transfer to complete and start processing it on the CPU while other streams are still chugging along on the GPU, in parallel with the host code. :func:`wp.synchronize_event(event) <synchronize_event>` is the most specific host synchronization function. It blocks the host until an event previously recorded on a CUDA stream completes. This can be used to wait for a specific stream synchronization point to be reached, while allowing subsequent operations on that stream to continue asynchronously. Device-side Synchronization ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Device-side synchronization uses CUDA events to make one stream wait for a synchronization point recorded on another stream (:func:`wp.record_event() <record_event>`, :func:`wp.wait_event() <wait_event>`, :func:`wp.wait_stream() <wait_stream>`). These functions don't block the host thread, so the CPU can stay busy doing useful work, like preparing the next batch of data to feed the beast. Events can be used to synchronize streams on the same device or even different CUDA devices, so you can choreograph very sophisticated multi-stream and multi-device workloads that execute entirely on the available GPUs. This allows keeping host-side synchronization to a minimum, perhaps only when reading back the final results. Synchronization and Graph Capture ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A CUDA graph captures a sequence of operations on a CUDA stream that can be replayed multiple times with low overhead. During capture, certain CUDA functions are not allowed, which includes host-side synchronization functions. Using the synchronous CUDA default stream is also not allowed. The only form of synchronization allowed in CUDA graphs is event-based synchronization. A CUDA graph capture must start and end on the same stream, but multiple streams can be used in the middle. This allows CUDA graphs to encompass multiple streams and even multiple GPUs. Events play a crucial role with multi-stream graph capture because they are used to fork and join new streams to the main capture stream, in addition to their regular synchronization duties. Here's an example of capturing a multi-GPU graph using a stream on each device: .. code:: python stream0 = wp.Stream("cuda:0") stream1 = wp.Stream("cuda:1") # use stream0 as the main capture stream with wp.ScopedCapture(stream=stream0) as capture: # fork stream1, which adds it to the set of streams being captured stream1.wait_stream(stream0) # launch a kernel on stream0 wp.launch(kernel, ..., stream=stream0) # launch a kernel on stream1 wp.launch(kernel, ..., stream=stream1) # join stream1 stream0.wait_stream(stream1) # launch the multi-GPU graph, which can execute the captured kernels concurrently wp.capture_launch(capture.graph)
27,125
reStructuredText
44.898477
482
0.727779
NVIDIA/warp/docs/modules/fem.rst
warp.fem ===================== .. currentmodule:: warp.fem The ``warp.fem`` module is designed to facilitate solving physical systems described as differential equations. For example, it can solve PDEs for diffusion, convection, fluid flow, and elasticity problems using finite-element-based (FEM) Galerkin methods, and allows users to quickly experiment with various FEM formulations and discretization schemes. Integrands ---------- The core functionality of the FEM toolkit is the ability to integrate constant, linear, and bilinear forms over various domains and using arbitrary interpolation basis. The main mechanism is the :py:func:`.integrand` decorator, for instance: :: @integrand def linear_form( s: Sample, v: Field, ): return v(s) @integrand def diffusion_form(s: Sample, u: Field, v: Field, nu: float): return nu * wp.dot( grad(u, s), grad(v, s), ) Integrands are normal Warp kernels, meaning any usual Warp function can be used. However, they accept a few special parameters: - :class:`.Sample` contains information about the current integration sample point, such as the element index and coordinates in element. - :class:`.Field` designates an abstract field, which will be replaced at call time by the actual field type: for instance a :class:`.DiscreteField`, :class:`.field.TestField` or :class:`.field.TrialField` defined over an arbitrary :class:`.FunctionSpace`. A field `u` can be evaluated at a given sample `s` using the :func:`.inner` operator, i.e, ``inner(u, s)``, or as a shortcut using the usual call operator, ``u(s)``. Several other operators are available, such as :func:`.grad`; see the :ref:`Operators` section. - :class:`.Domain` designates an abstract integration domain. Several operators are also provided for domains, for example in the example below evaluating the normal at the current sample position: :: @integrand def boundary_form( s: Sample, domain: Domain, u: Field, ): nor = normal(domain, s) return wp.dot(u(s), nor) Integrands cannot be used directly with :func:`warp.launch`, but must be called through :func:`.integrate` or :func:`.interpolate` instead. The root integrand (`integrand` argument passed to :func:`integrate` or :func:`interpolate` call) will automatically get passed :class:`.Sample` and :class:`.Domain` parameters. :class:`.Field` parameters must be passed as a dictionary in the `fields` argument of the launcher function, and all other standard Warp types arguments must be passed as a dictionary in the `values` argument of the launcher function, for instance: :: integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": viscosity}) Basic workflow -------------- The typical steps for solving a linear PDE are as follow: - Define a :class:`.Geometry` (grid, mesh, etc). At the moment, 2D and 3D regular grids, NanoVDB volumes, and triangle, quadrilateral, tetrahedron and hexahedron unstructured meshes are supported. - Define one or more :class:`.FunctionSpace`, by equipping the geometry elements with shape functions. See :func:`.make_polynomial_space`. At the moment, continuous/discontinuous Lagrange (:math:`P_{k[d]}, Q_{k[d]}`) and Serendipity (:math:`S_k`) shape functions of order :math:`k \leq 3` are supported. - Define an integration :class:`.GeometryDomain`, for instance the geometry's cells (:class:`.Cells`) or boundary sides (:class:`.BoundarySides`). - Integrate linear forms to build the system's right-hand-side. Define a test function over the function space using :func:`.make_test`, a :class:`.Quadrature` formula (or let the module choose one based on the function space degree), and call :func:`.integrate` with the linear form integrand. The result is a :class:`warp.array` containing the integration result for each of the function space degrees of freedom. - Integrate bilinear forms to build the system's left-hand-side. Define a trial function over the function space using :func:`.make_trial`, then call :func:`.integrate` with the bilinear form integrand. The result is a :class:`warp.sparse.BsrMatrix` containing the integration result for each pair of test and trial function space degrees of freedom. Note that the trial and test functions do not have to be defined over the same function space, so that Mixed FEM is supported. - Solve the resulting linear system using the solver of your choice The following excerpt from the introductory example ``warp/examples/fem/example_diffusion.py`` outlines this procedure: :: # Grid geometry geo = Grid2D(n=50, cell_size=2) # Domain and function spaces domain = Cells(geometry=geo) scalar_space = make_polynomial_space(geo, degree=3) # Right-hand-side (forcing term) test = make_test(space=scalar_space, domain=domain) rhs = integrate(linear_form, fields={"v": test}) # Weakly-imposed boundary conditions on Y sides boundary = BoundarySides(geo) bd_test = make_test(space=scalar_space, domain=boundary) bd_trial = make_trial(space=scalar_space, domain=boundary) bd_matrix = integrate(y_mass_form, fields={"u": bd_trial, "v": bd_test}) # Diffusion form trial = make_trial(space=scalar_space, domain=domain) matrix = integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": viscosity}) # Assemble linear system (add diffusion and boundary condition matrices) bsr_axpy(x=bd_matrix, y=matrix, alpha=boundary_strength, beta=1) # Solve linear system using Conjugate Gradient x = wp.zeros_like(rhs) bsr_cg(matrix, b=rhs, x=x) .. note:: The :func:`.integrate` function does not check that the passed integrands are actually linear or bilinear forms; it is up to the user to ensure that they are. To solve non-linear PDEs, one can use an iterative procedure and pass the current value of the studied function :class:`.DiscreteField` argument to the integrand, on which arbitrary operations are permitted. However, the result of the form must remain linear in the test and trial fields. Introductory examples --------------------- ``warp.fem`` ships with a list of examples in the ``warp/examples/fem`` directory illustrating common model problems. - ``example_diffusion.py``: 2D diffusion with homogeneous Neumann and Dirichlet boundary conditions * ``example_diffusion_3d.py``: 3D variant of the diffusion problem - ``example_convection_diffusion.py``: 2D convection-diffusion using semi-Lagrangian advection * ``example_convection_diffusion_dg.py``: 2D convection-diffusion using Discontinuous Galerkin with upwind transport and Symmetric Interior Penalty - ``example_burgers.py``: 2D inviscid Burgers using Discontinuous Galerkin with upwind transport and slope limiter - ``example_stokes.py``: 2D incompressible Stokes flow using mixed :math:`P_k/P_{k-1}` or :math:`Q_k/P_{(k-1)d}` elements - ``example_navier_stokes.py``: 2D Navier-Stokes flow using mixed :math:`P_k/P_{k-1}` elements - ``example_mixed_elasticity.py``: 2D linear elasticity using mixed continuous/discontinuous :math:`S_k/P_{(k-1)d}` elements Advanced usages --------------- High-order (curved) geometries ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ It is possible to convert any :class:`.Geometry` (grids and explicit meshes) into a curved, high-order variant by deforming them with an arbitrary-order displacement field using the :meth:`~.DiscreteField.make_deformed_geometry` method. The process looks as follow: :: # Define a base geometry base_geo = fem.Grid3D(res=resolution) # Define a displacement field on the base geometry deformation_space = fem.make_polynomial_space(base_geo, degree=deformation_degree, dtype=wp.vec3) deformation_field = deformation_space.make_field() # Populate the field value by interpolating an expression fem.interpolate(deformation_field_expr, dest=deformation_field) # Construct the deformed geometry from the displacement field deform_geo = deformation_field.make_deformed_geometry() # Define new function spaces on the deformed geometry scalar_space = fem.make_polynomial_space(deformed_geo, degree=scalar_space_degree) See also ``example_deformed_geometry.py`` for a complete example. Particle-based quadrature ^^^^^^^^^^^^^^^^^^^^^^^^^ The :class:`.PicQuadrature` provides a way to define Particle-In-Cell quadratures from a set or arbitrary particles, which can be helpful to develop MPM-like methods. The particles are automatically bucketed to the geometry cells when the quadrature is initialized. This is illustrated by the ``example_stokes_transfer.py`` and ``example_apic_fluid.py`` examples. Partitioning ^^^^^^^^^^^^ The FEM toolkit makes it possible to perform integration on a subset of the domain elements, possibly re-indexing degrees of freedom so that the linear system contains the local ones only. This is useful for distributed computation (see ``warp/examples/fem/example_diffusion_mgpu.py``), or simply to limit the simulation domain to a subset of active cells (see ``warp/examples/fem/example_stokes_transfer.py``). A partition of the simulation geometry can be defined using subclasses of :class:`.GeometryPartition` such as :class:`.LinearGeometryPartition` or :class:`.ExplicitGeometryPartition`. Function spaces can then be partitioned according to the geometry partition using :func:`.make_space_partition`. The resulting :class:`.SpacePartition` object allows translating between space-wide and partition-wide node indices, and differentiating interior, frontier and exterior nodes. Memory management ^^^^^^^^^^^^^^^^^ Several ``warp.fem`` functions require allocating temporary buffers to perform their computations. If such functions are called many times in a tight loop, those many allocations and de-allocations may degrade performance. To overcome this issue, a :class:`.cache.TemporaryStore` object may be created to persist and reuse temporary allocations across calls, either globally using :func:`set_default_temporary_store` or at a per-function granularity using the corresponding argument. .. _Operators: Operators --------- .. autofunction:: position(domain: Domain, s: Sample) .. autofunction:: normal(domain: Domain, s: Sample) .. autofunction:: lookup(domain: Domain, x) .. autofunction:: measure(domain: Domain, s: Sample) .. autofunction:: measure_ratio(domain: Domain, s: Sample) .. autofunction:: deformation_gradient(domain: Domain, s: Sample) .. autofunction:: degree(f: Field) .. autofunction:: inner(f: Field, s: Sample) .. autofunction:: outer(f: Field, s: Sample) .. autofunction:: grad(f: Field, s: Sample) .. autofunction:: grad_outer(f: Field, s: Sample) .. autofunction:: div(f: Field, s: Sample) .. autofunction:: div_outer(f: Field, s: Sample) .. autofunction:: at_node(f: Field, s: Sample) .. autofunction:: D(f: Field, s: Sample) .. autofunction:: curl(f: Field, s: Sample) .. autofunction:: jump(f: Field, s: Sample) .. autofunction:: average(f: Field, s: Sample) .. autofunction:: grad_jump(f: Field, s: Sample) .. autofunction:: grad_average(f: Field, s: Sample) .. autofunction:: warp.fem.operator.operator Integration ----------- .. autofunction:: integrate .. autofunction:: interpolate .. autofunction:: integrand .. class:: Sample Per-sample point context for evaluating fields and related operators in integrands. .. autoclass:: Field .. autoclass:: Domain Geometry -------- .. autoclass:: Grid2D :show-inheritance: .. autoclass:: Trimesh2D :show-inheritance: .. autoclass:: Quadmesh2D :show-inheritance: .. autoclass:: Grid3D :show-inheritance: .. autoclass:: Tetmesh :show-inheritance: .. autoclass:: Hexmesh :show-inheritance: .. autoclass:: Nanogrid :show-inheritance: .. autoclass:: LinearGeometryPartition .. autoclass:: ExplicitGeometryPartition .. autoclass:: Cells :show-inheritance: .. autoclass:: Sides :show-inheritance: .. autoclass:: BoundarySides :show-inheritance: .. autoclass:: FrontierSides :show-inheritance: .. autoclass:: Polynomial :members: .. autoclass:: RegularQuadrature :show-inheritance: .. autoclass:: NodalQuadrature :show-inheritance: .. autoclass:: ExplicitQuadrature :show-inheritance: .. autoclass:: PicQuadrature :show-inheritance: Function Spaces --------------- .. autofunction:: make_polynomial_space .. autofunction:: make_polynomial_basis_space .. autofunction:: make_collocated_function_space .. autofunction:: make_space_partition .. autofunction:: make_space_restriction .. autoclass:: ElementBasis :members: .. autoclass:: SymmetricTensorMapper :show-inheritance: .. autoclass:: SkewSymmetricTensorMapper :show-inheritance: .. autoclass:: PointBasisSpace :show-inheritance: Fields ------ .. autofunction:: make_test .. autofunction:: make_trial .. autofunction:: make_restriction Boundary Conditions ------------------- .. autofunction:: normalize_dirichlet_projector .. autofunction:: project_linear_system Memory management ----------------- .. autofunction:: set_default_temporary_store .. autofunction:: borrow_temporary .. autofunction:: borrow_temporary_like Interfaces ---------- Interface classes are not meant to be constructed directly, but can be derived from extend the built-in functionality. .. autoclass:: Geometry :members: cell_count, side_count, boundary_side_count .. autoclass:: GeometryPartition :members: cell_count, side_count, boundary_side_count, frontier_side_count .. autoclass:: GeometryDomain :members: ElementKind, element_kind, dimension, element_count .. autoclass:: Quadrature :members: domain, total_point_count .. autoclass:: FunctionSpace :members: dtype, topology, geometry, dimension, degree, trace, make_field .. autoclass:: SpaceTopology :members: dimension, geometry, node_count, element_node_indices, trace .. autoclass:: BasisSpace :members: topology, geometry, node_positions .. autoclass:: warp.fem.space.shape.ShapeFunction .. autoclass:: SpacePartition :members: node_count, owned_node_count, interior_node_count, space_node_indices .. autoclass:: SpaceRestriction :members: node_count .. autoclass:: DofMapper .. autoclass:: FieldLike .. autoclass:: DiscreteField :show-inheritance: :members: dof_values, trace, make_deformed_geometry .. autoclass:: warp.fem.field.FieldRestriction .. autoclass:: warp.fem.field.SpaceField :show-inheritance: .. autoclass:: warp.fem.field.TestField :show-inheritance: .. autoclass:: warp.fem.field.TrialField :show-inheritance: .. autoclass:: TemporaryStore :members: clear .. autoclass:: warp.fem.cache.Temporary :members: array, detach, release
14,857
reStructuredText
36.520202
304
0.72417
adegirmenci/HBL-ICEbot/qcustomplot.h
/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2015 Emanuel Eichhammer ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 22.12.15 ** ** Version: 1.3.2 ** ****************************************************************************/ #ifndef QCUSTOMPLOT_H #define QCUSTOMPLOT_H #include <QObject> #include <QPointer> #include <QWidget> #include <QPainter> #include <QPaintEvent> #include <QtGui/QMouseEvent> #include <QPixmap> #include <QVector> #include <QString> #include <QDateTime> #include <QMultiMap> #include <QFlags> #include <QDebug> #include <QVector2D> #include <QStack> #include <QCache> #include <QMargins> #include <qmath.h> #include <limits> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) # include <qnumeric.h> # include <QPrinter> # include <QPrintEngine> #else # include <QtNumeric> # include <QtPrintSupport/QtPrintSupport> #endif class QCPPainter; class QCustomPlot; class QCPLayerable; class QCPLayoutElement; class QCPLayout; class QCPAxis; class QCPAxisRect; class QCPAxisPainterPrivate; class QCPAbstractPlottable; class QCPGraph; class QCPAbstractItem; class QCPItemPosition; class QCPLayer; class QCPPlotTitle; class QCPLegend; class QCPAbstractLegendItem; class QCPColorMap; class QCPColorScale; class QCPBars; /*! \file */ // decl definitions for shared library compilation/usage: #if defined(QCUSTOMPLOT_COMPILE_LIBRARY) # define QCP_LIB_DECL Q_DECL_EXPORT #elif defined(QCUSTOMPLOT_USE_LIBRARY) # define QCP_LIB_DECL Q_DECL_IMPORT #else # define QCP_LIB_DECL #endif /*! The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library */ namespace QCP { /*! Defines the sides of a rectangular entity to which margins can be applied. \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< <tt>0x01</tt> left margin ,msRight = 0x02 ///< <tt>0x02</tt> right margin ,msTop = 0x04 ///< <tt>0x04</tt> top margin ,msBottom = 0x08 ///< <tt>0x08</tt> bottom margin ,msAll = 0xFF ///< <tt>0xFF</tt> all margins ,msNone = 0x00 ///< <tt>0x00</tt> no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) /*! Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. \c AntialiasedElements is a flag of or-combined elements of this enum type. \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< <tt>0x0001</tt> Axis base line and tick marks ,aeGrid = 0x0002 ///< <tt>0x0002</tt> Grid lines ,aeSubGrid = 0x0004 ///< <tt>0x0004</tt> Sub grid lines ,aeLegend = 0x0008 ///< <tt>0x0008</tt> Legend box ,aeLegendItems = 0x0010 ///< <tt>0x0010</tt> Legend items ,aePlottables = 0x0020 ///< <tt>0x0020</tt> Main lines of plottables (excluding error bars, see element \ref aeErrorBars) ,aeItems = 0x0040 ///< <tt>0x0040</tt> Main lines of items ,aeScatters = 0x0080 ///< <tt>0x0080</tt> Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) ,aeErrorBars = 0x0100 ///< <tt>0x0100</tt> Error bars ,aeFills = 0x0200 ///< <tt>0x0200</tt> Borders of fills (e.g. under or between graphs) ,aeZeroLine = 0x0400 ///< <tt>0x0400</tt> Zero-lines, see \ref QCPGrid::setZeroLinePen ,aeAll = 0xFFFF ///< <tt>0xFFFF</tt> All elements ,aeNone = 0x0000 ///< <tt>0x0000</tt> No elements }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. \see QCustomPlot::setPlottingHints */ enum PlottingHint { phNone = 0x000 ///< <tt>0x000</tt> No hints are set ,phFastPolylines = 0x001 ///< <tt>0x001</tt> Graph/Curve lines are drawn with a faster method. This reduces the quality ///< especially of the line segment joins. (Only relevant for solid line pens.) ,phForceRepaint = 0x002 ///< <tt>0x002</tt> causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). ,phCacheLabels = 0x004 ///< <tt>0x004</tt> axis (tick) labels will be cached as pixmaps, increasing replot performance. }; Q_DECLARE_FLAGS(PlottingHints, PlottingHint) /*! Defines the mouse interactions possible with QCustomPlot. \c Interactions is a flag of or-combined elements of this enum type. \see QCustomPlot::setInteractions */ enum Interaction { iRangeDrag = 0x001 ///< <tt>0x001</tt> Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) ,iRangeZoom = 0x002 ///< <tt>0x002</tt> Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) ,iMultiSelect = 0x004 ///< <tt>0x004</tt> The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking ,iSelectPlottables = 0x008 ///< <tt>0x008</tt> Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) ,iSelectAxes = 0x010 ///< <tt>0x010</tt> Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) ,iSelectLegend = 0x020 ///< <tt>0x020</tt> Legends are selectable (or their child items, see QCPLegend::setSelectableParts) ,iSelectItems = 0x040 ///< <tt>0x040</tt> Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) ,iSelectOther = 0x080 ///< <tt>0x080</tt> All other objects are selectable (e.g. your own derived layerables, the plot title,...) }; Q_DECLARE_FLAGS(Interactions, Interaction) /*! \internal Returns whether the specified \a value is considered an invalid data value for plottables (i.e. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ inline bool isInvalidData(double value) { return qIsNaN(value) || qIsInf(value); } /*! \internal \overload Checks two arguments instead of one. */ inline bool isInvalidData(double value1, double value2) { return isInvalidData(value1) || isInvalidData(value2); } /*! \internal Sets the specified \a side of \a margins to \a value \see getMarginValue */ inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { switch (side) { case QCP::msLeft: margins.setLeft(value); break; case QCP::msRight: margins.setRight(value); break; case QCP::msTop: margins.setTop(value); break; case QCP::msBottom: margins.setBottom(value); break; case QCP::msAll: margins = QMargins(value, value, value, value); break; default: break; } } /*! \internal Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. \see setMarginValue */ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { switch (side) { case QCP::msLeft: return margins.left(); case QCP::msRight: return margins.right(); case QCP::msTop: return margins.top(); case QCP::msBottom: return margins.bottom(); default: break; } return 0; } } // end of namespace QCP Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) class QCP_LIB_DECL QCPScatterStyle { Q_GADGET public: /*! Defines the shape used for scatter points. On plottables/items that draw scatters, the sizes of these visualizations (with exception of \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are drawn with the pen and brush specified with \ref setPen and \ref setBrush. */ Q_ENUMS(ScatterShape) enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) ,ssCross ///< \enumimage{ssCross.png} a cross ,ssPlus ///< \enumimage{ssPlus.png} a plus ,ssCircle ///< \enumimage{ssCircle.png} a circle ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) ,ssSquare ///< \enumimage{ssSquare.png} a square ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) }; QCPScatterStyle(); QCPScatterStyle(ScatterShape shape, double size=6); QCPScatterStyle(ScatterShape shape, const QColor &color, double size); QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); QCPScatterStyle(const QPixmap &pixmap); QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); // getters: double size() const { return mSize; } ScatterShape shape() const { return mShape; } QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } QPixmap pixmap() const { return mPixmap; } QPainterPath customPath() const { return mCustomPath; } // setters: void setSize(double size); void setShape(ScatterShape shape); void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setPixmap(const QPixmap &pixmap); void setCustomPath(const QPainterPath &customPath); // non-property methods: bool isNone() const { return mShape == ssNone; } bool isPenDefined() const { return mPenDefined; } void applyTo(QCPPainter *painter, const QPen &defaultPen) const; void drawShape(QCPPainter *painter, QPointF pos) const; void drawShape(QCPPainter *painter, double x, double y) const; protected: // property members: double mSize; ScatterShape mShape; QPen mPen; QBrush mBrush; QPixmap mPixmap; QPainterPath mCustomPath; // non-property members: bool mPenDefined; }; Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPPainter : public QPainter { Q_GADGET public: /*! Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, depending on whether they are wanted on the respective output device. */ enum PainterMode { pmDefault = 0x00 ///< <tt>0x00</tt> Default mode for painting on screen devices ,pmVectorized = 0x01 ///< <tt>0x01</tt> Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. ,pmNoCaching = 0x02 ///< <tt>0x02</tt> Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels ,pmNonCosmetic = 0x04 ///< <tt>0x04</tt> Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) }; Q_FLAGS(PainterMode PainterModes) Q_DECLARE_FLAGS(PainterModes, PainterMode) QCPPainter(); QCPPainter(QPaintDevice *device); ~QCPPainter(); // getters: bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } PainterModes modes() const { return mModes; } // setters: void setAntialiasing(bool enabled); void setMode(PainterMode mode, bool enabled=true); void setModes(PainterModes modes); // methods hiding non-virtual base class functions (QPainter bug workarounds): bool begin(QPaintDevice *device); void setPen(const QPen &pen); void setPen(const QColor &color); void setPen(Qt::PenStyle penStyle); void drawLine(const QLineF &line); void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} void save(); void restore(); // non-virtual methods: void makeNonCosmetic(); protected: // property members: PainterModes mModes; bool mIsAntialiasing; // non-property members: QStack<bool> mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) class QCP_LIB_DECL QCPLayer : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QString name READ name) Q_PROPERTY(int index READ index) Q_PROPERTY(QList<QCPLayerable*> children READ children) Q_PROPERTY(bool visible READ visible WRITE setVisible) /// \endcond public: QCPLayer(QCustomPlot* parentPlot, const QString &layerName); ~QCPLayer(); // getters: QCustomPlot *parentPlot() const { return mParentPlot; } QString name() const { return mName; } int index() const { return mIndex; } QList<QCPLayerable*> children() const { return mChildren; } bool visible() const { return mVisible; } // setters: void setVisible(bool visible); protected: // property members: QCustomPlot *mParentPlot; QString mName; int mIndex; QList<QCPLayerable*> mChildren; bool mVisible; // non-virtual methods: void addChild(QCPLayerable *layerable, bool prepend); void removeChild(QCPLayerable *layerable); private: Q_DISABLE_COPY(QCPLayer) friend class QCustomPlot; friend class QCPLayerable; }; class QCP_LIB_DECL QCPLayerable : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) /// \endcond public: QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0); ~QCPLayerable(); // getters: bool visible() const { return mVisible; } QCustomPlot *parentPlot() const { return mParentPlot; } QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } QCPLayer *layer() const { return mLayer; } bool antialiased() const { return mAntialiased; } // setters: void setVisible(bool on); Q_SLOT bool setLayer(QCPLayer *layer); bool setLayer(const QString &layerName); void setAntialiased(bool enabled); // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-property methods: bool realVisibility() const; signals: void layerChanged(QCPLayer *newLayer); protected: // property members: bool mVisible; QCustomPlot *mParentPlot; QPointer<QCPLayerable> mParentLayerable; QCPLayer *mLayer; bool mAntialiased; // introduced virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-property methods: void initializeParentPlot(QCustomPlot *parentPlot); void setParentLayerable(QCPLayerable* parentLayerable); bool moveToLayer(QCPLayer *layer, bool prepend); void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; private: Q_DISABLE_COPY(QCPLayerable) friend class QCustomPlot; friend class QCPAxisRect; }; class QCP_LIB_DECL QCPRange { public: double lower, upper; QCPRange(); QCPRange(double lower, double upper); bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } bool operator!=(const QCPRange& other) const { return !(*this == other); } QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } friend inline const QCPRange operator+(const QCPRange&, double); friend inline const QCPRange operator+(double, const QCPRange&); friend inline const QCPRange operator-(const QCPRange& range, double value); friend inline const QCPRange operator*(const QCPRange& range, double value); friend inline const QCPRange operator*(double value, const QCPRange& range); friend inline const QCPRange operator/(const QCPRange& range, double value); double size() const; double center() const; void normalize(); void expand(const QCPRange &otherRange); QCPRange expanded(const QCPRange &otherRange) const; QCPRange sanitizedForLogScale() const; QCPRange sanitizedForLinScale() const; bool contains(double value) const; static bool validRange(double lower, double upper); static bool validRange(const QCPRange &range); static const double minRange; //1e-280; static const double maxRange; //1e280; }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /* documentation of inline functions */ /*! \fn QCPRange &QCPRange::operator+=(const double& value) Adds \a value to both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator-=(const double& value) Subtracts \a value from both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator*=(const double& value) Multiplies both boundaries of the range by \a value. */ /*! \fn QCPRange &QCPRange::operator/=(const double& value) Divides both boundaries of the range by \a value. */ /* end documentation of inline functions */ /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(const QCPRange& range, double value) { QCPRange result(range); result += value; return result; } /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(double value, const QCPRange& range) { QCPRange result(range); result += value; return result; } /*! Subtracts \a value from both boundaries of the range. */ inline const QCPRange operator-(const QCPRange& range, double value) { QCPRange result(range); result -= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(const QCPRange& range, double value) { QCPRange result(range); result *= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(double value, const QCPRange& range) { QCPRange result(range); result *= value; return result; } /*! Divides both boundaries of the range by \a value. */ inline const QCPRange operator/(const QCPRange& range, double value) { QCPRange result(range); result /= value; return result; } class QCP_LIB_DECL QCPMarginGroup : public QObject { Q_OBJECT public: QCPMarginGroup(QCustomPlot *parentPlot); ~QCPMarginGroup(); // non-virtual methods: QList<QCPLayoutElement*> elements(QCP::MarginSide side) const { return mChildren.value(side); } bool isEmpty() const; void clear(); protected: // non-property members: QCustomPlot *mParentPlot; QHash<QCP::MarginSide, QList<QCPLayoutElement*> > mChildren; // non-virtual methods: int commonMargin(QCP::MarginSide side) const; void addChild(QCP::MarginSide side, QCPLayoutElement *element); void removeChild(QCP::MarginSide side, QCPLayoutElement *element); private: Q_DISABLE_COPY(QCPMarginGroup) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLayout* layout READ layout) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) Q_PROPERTY(QMargins margins READ margins WRITE setMargins) Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) /// \endcond public: /*! Defines the phases of the update process, that happens just before a replot. At each phase, \ref update is called with the according UpdatePhase value. */ enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout ,upMargins ///< Phase in which the margins are calculated and set ,upLayout ///< Final phase in which the layout system places the rects of the elements }; Q_ENUMS(UpdatePhase) explicit QCPLayoutElement(QCustomPlot *parentPlot=0); virtual ~QCPLayoutElement(); // getters: QCPLayout *layout() const { return mParentLayout; } QRect rect() const { return mRect; } QRect outerRect() const { return mOuterRect; } QMargins margins() const { return mMargins; } QMargins minimumMargins() const { return mMinimumMargins; } QCP::MarginSides autoMargins() const { return mAutoMargins; } QSize minimumSize() const { return mMinimumSize; } QSize maximumSize() const { return mMaximumSize; } QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } QHash<QCP::MarginSide, QCPMarginGroup*> marginGroups() const { return mMarginGroups; } // setters: void setOuterRect(const QRect &rect); void setMargins(const QMargins &margins); void setMinimumMargins(const QMargins &margins); void setAutoMargins(QCP::MarginSides sides); void setMinimumSize(const QSize &size); void setMinimumSize(int width, int height); void setMaximumSize(const QSize &size); void setMaximumSize(int width, int height); void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); // introduced virtual methods: virtual void update(UpdatePhase phase); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; virtual QList<QCPLayoutElement*> elements(bool recursive) const; // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPLayout *mParentLayout; QSize mMinimumSize, mMaximumSize; QRect mRect, mOuterRect; QMargins mMargins, mMinimumMargins; QCP::MarginSides mAutoMargins; QHash<QCP::MarginSide, QCPMarginGroup*> mMarginGroups; // introduced virtual methods: virtual int calculateAutoMargin(QCP::MarginSide side); // events: virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } virtual void parentPlotInitialized(QCustomPlot *parentPlot); private: Q_DISABLE_COPY(QCPLayoutElement) friend class QCustomPlot; friend class QCPLayout; friend class QCPMarginGroup; }; class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { Q_OBJECT public: explicit QCPLayout(); // reimplemented virtual methods: virtual void update(UpdatePhase phase); virtual QList<QCPLayoutElement*> elements(bool recursive) const; // introduced virtual methods: virtual int elementCount() const = 0; virtual QCPLayoutElement* elementAt(int index) const = 0; virtual QCPLayoutElement* takeAt(int index) = 0; virtual bool take(QCPLayoutElement* element) = 0; virtual void simplify(); // non-virtual methods: bool removeAt(int index); bool remove(QCPLayoutElement* element); void clear(); protected: // introduced virtual methods: virtual void updateLayout(); // non-virtual methods: void sizeConstraintsChanged() const; void adoptElement(QCPLayoutElement *el); void releaseElement(QCPLayoutElement *el); QVector<int> getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const; private: Q_DISABLE_COPY(QCPLayout) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(int rowCount READ rowCount) Q_PROPERTY(int columnCount READ columnCount) Q_PROPERTY(QList<double> columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) Q_PROPERTY(QList<double> rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) /// \endcond public: explicit QCPLayoutGrid(); virtual ~QCPLayoutGrid(); // getters: int rowCount() const; int columnCount() const; QList<double> columnStretchFactors() const { return mColumnStretchFactors; } QList<double> rowStretchFactors() const { return mRowStretchFactors; } int columnSpacing() const { return mColumnSpacing; } int rowSpacing() const { return mRowSpacing; } // setters: void setColumnStretchFactor(int column, double factor); void setColumnStretchFactors(const QList<double> &factors); void setRowStretchFactor(int row, double factor); void setRowStretchFactors(const QList<double> &factors); void setColumnSpacing(int pixels); void setRowSpacing(int pixels); // reimplemented virtual methods: virtual void updateLayout(); virtual int elementCount() const; virtual QCPLayoutElement* elementAt(int index) const; virtual QCPLayoutElement* takeAt(int index); virtual bool take(QCPLayoutElement* element); virtual QList<QCPLayoutElement*> elements(bool recursive) const; virtual void simplify(); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // non-virtual methods: QCPLayoutElement *element(int row, int column) const; bool addElement(int row, int column, QCPLayoutElement *element); bool hasElement(int row, int column); void expandTo(int newRowCount, int newColumnCount); void insertRow(int newIndex); void insertColumn(int newIndex); protected: // property members: QList<QList<QCPLayoutElement*> > mElements; QList<double> mColumnStretchFactors; QList<double> mRowStretchFactors; int mColumnSpacing, mRowSpacing; // non-virtual methods: void getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const; void getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const; private: Q_DISABLE_COPY(QCPLayoutGrid) }; class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { Q_OBJECT public: /*! Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. */ enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment }; explicit QCPLayoutInset(); virtual ~QCPLayoutInset(); // getters: InsetPlacement insetPlacement(int index) const; Qt::Alignment insetAlignment(int index) const; QRectF insetRect(int index) const; // setters: void setInsetPlacement(int index, InsetPlacement placement); void setInsetAlignment(int index, Qt::Alignment alignment); void setInsetRect(int index, const QRectF &rect); // reimplemented virtual methods: virtual void updateLayout(); virtual int elementCount() const; virtual QCPLayoutElement* elementAt(int index) const; virtual QCPLayoutElement* takeAt(int index); virtual bool take(QCPLayoutElement* element); virtual void simplify() {} virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: void addElement(QCPLayoutElement *element, Qt::Alignment alignment); void addElement(QCPLayoutElement *element, const QRectF &rect); protected: // property members: QList<QCPLayoutElement*> mElements; QList<InsetPlacement> mInsetPlacement; QList<Qt::Alignment> mInsetAlignment; QList<QRectF> mInsetRect; private: Q_DISABLE_COPY(QCPLayoutInset) }; class QCP_LIB_DECL QCPLineEnding { Q_GADGET public: /*! Defines the type of ending decoration for line-like items, e.g. an arrow. \image html QCPLineEnding.png The width and length of these decorations can be controlled with the functions \ref setWidth and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only support a width, the length property is ignored. \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding */ Q_ENUMS(EndingStyle) enum EndingStyle { esNone ///< No ending decoration ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) ,esSpikeArrow ///< A filled arrow head with an indented back ,esLineArrow ///< A non-filled arrow head with open back ,esDisc ///< A filled circle ,esSquare ///< A filled square ,esDiamond ///< A filled diamond (45° rotated square) ,esBar ///< A bar perpendicular to the line ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) }; QCPLineEnding(); QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); // getters: EndingStyle style() const { return mStyle; } double width() const { return mWidth; } double length() const { return mLength; } bool inverted() const { return mInverted; } // setters: void setStyle(EndingStyle style); void setWidth(double width); void setLength(double length); void setInverted(bool inverted); // non-property methods: double boundingDistance() const; double realLength() const; void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; protected: // property members: EndingStyle mStyle; double mWidth, mLength; bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPGrid :public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) /// \endcond public: QCPGrid(QCPAxis *parentAxis); // getters: bool subGridVisible() const { return mSubGridVisible; } bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } QPen pen() const { return mPen; } QPen subGridPen() const { return mSubGridPen; } QPen zeroLinePen() const { return mZeroLinePen; } // setters: void setSubGridVisible(bool visible); void setAntialiasedSubGrid(bool enabled); void setAntialiasedZeroLine(bool enabled); void setPen(const QPen &pen); void setSubGridPen(const QPen &pen); void setZeroLinePen(const QPen &pen); protected: // property members: bool mSubGridVisible; bool mAntialiasedSubGrid, mAntialiasedZeroLine; QPen mPen, mSubGridPen, mZeroLinePen; // non-property members: QCPAxis *mParentAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); // non-virtual methods: void drawGridLines(QCPPainter *painter) const; void drawSubGridLines(QCPPainter *painter) const; friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(AxisType axisType READ axisType) Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) Q_PROPERTY(bool ticks READ ticks WRITE setTicks) Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide) Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) Q_PROPERTY(QVector<double> tickVector READ tickVector WRITE setTickVector) Q_PROPERTY(QVector<QString> tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) Q_PROPERTY(int padding READ padding WRITE setPadding) Q_PROPERTY(int offset READ offset WRITE setOffset) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) Q_PROPERTY(QCPGrid* grid READ grid) /// \endcond public: /*! Defines at which side of the axis rect the axis will appear. This also affects how the tick marks are drawn, on which side the labels are placed etc. */ enum AxisType { atLeft = 0x01 ///< <tt>0x01</tt> Axis is vertical and on the left side of the axis rect ,atRight = 0x02 ///< <tt>0x02</tt> Axis is vertical and on the right side of the axis rect ,atTop = 0x04 ///< <tt>0x04</tt> Axis is horizontal and on the top side of the axis rect ,atBottom = 0x08 ///< <tt>0x08</tt> Axis is horizontal and on the bottom side of the axis rect }; Q_FLAGS(AxisType AxisTypes) Q_DECLARE_FLAGS(AxisTypes, AxisType) /*! When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the coordinate of the tick is interpreted, i.e. translated into a string. \see setTickLabelType */ enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) }; Q_ENUMS(LabelType) /*! Defines on which side of the axis the tick labels (numbers) shall appear. \see setTickLabelSide */ enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect ,lsOutside ///< Tick labels will be displayed outside the axis rect }; Q_ENUMS(LabelSide) /*! Defines the scale of an axis. \see setScaleType */ enum ScaleType { stLinear ///< Linear scaling ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). }; Q_ENUMS(ScaleType) /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts */ enum SelectablePart { spNone = 0 ///< None of the selectable parts ,spAxis = 0x001 ///< The axis backbone and tick marks ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; Q_FLAGS(SelectablePart SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPAxis(QCPAxisRect *parent, AxisType type); virtual ~QCPAxis(); // getters: AxisType axisType() const { return mAxisType; } QCPAxisRect *axisRect() const { return mAxisRect; } ScaleType scaleType() const { return mScaleType; } double scaleLogBase() const { return mScaleLogBase; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } bool autoTicks() const { return mAutoTicks; } int autoTickCount() const { return mAutoTickCount; } bool autoTickLabels() const { return mAutoTickLabels; } bool autoTickStep() const { return mAutoTickStep; } bool autoSubTicks() const { return mAutoSubTicks; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const; LabelType tickLabelType() const { return mTickLabelType; } QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const; LabelSide tickLabelSide() const; QString dateTimeFormat() const { return mDateTimeFormat; } Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } double tickStep() const { return mTickStep; } QVector<double> tickVector() const { return mTickVector; } QVector<QString> tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const; int tickLengthOut() const; int subTickCount() const { return mSubTickCount; } int subTickLengthIn() const; int subTickLengthOut() const; QPen basePen() const { return mBasePen; } QPen tickPen() const { return mTickPen; } QPen subTickPen() const { return mSubTickPen; } QFont labelFont() const { return mLabelFont; } QColor labelColor() const { return mLabelColor; } QString label() const { return mLabel; } int labelPadding() const; int padding() const { return mPadding; } int offset() const; SelectableParts selectedParts() const { return mSelectedParts; } SelectableParts selectableParts() const { return mSelectableParts; } QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } QFont selectedLabelFont() const { return mSelectedLabelFont; } QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } QColor selectedLabelColor() const { return mSelectedLabelColor; } QPen selectedBasePen() const { return mSelectedBasePen; } QPen selectedTickPen() const { return mSelectedTickPen; } QPen selectedSubTickPen() const { return mSelectedSubTickPen; } QCPLineEnding lowerEnding() const; QCPLineEnding upperEnding() const; QCPGrid *grid() const { return mGrid; } // setters: Q_SLOT void setScaleType(QCPAxis::ScaleType type); void setScaleLogBase(double base); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); void setAutoTicks(bool on); void setAutoTickCount(int approximateCount); void setAutoTickLabels(bool on); void setAutoTickStep(bool on); void setAutoSubTicks(bool on); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); void setTickLabelType(LabelType type); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setTickLabelSide(LabelSide side); void setDateTimeFormat(const QString &format); void setDateTimeSpec(const Qt::TimeSpec &timeSpec); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); void setTickStep(double step); void setTickVector(const QVector<double> &vec); void setTickVectorLabels(const QVector<QString> &vec); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); void setSubTickCount(int count); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); void setBasePen(const QPen &pen); void setTickPen(const QPen &pen); void setSubTickPen(const QPen &pen); void setLabelFont(const QFont &font); void setLabelColor(const QColor &color); void setLabel(const QString &str); void setLabelPadding(int padding); void setPadding(int padding); void setOffset(int offset); void setSelectedTickLabelFont(const QFont &font); void setSelectedLabelFont(const QFont &font); void setSelectedTickLabelColor(const QColor &color); void setSelectedLabelColor(const QColor &color); void setSelectedBasePen(const QPen &pen); void setSelectedTickPen(const QPen &pen); void setSelectedSubTickPen(const QPen &pen); Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); void setLowerEnding(const QCPLineEnding &ending); void setUpperEnding(const QCPLineEnding &ending); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-property methods: Qt::Orientation orientation() const { return mOrientation; } void moveRange(double diff); void scaleRange(double factor, double center); void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); void rescale(bool onlyVisiblePlottables=false); double pixelToCoord(double value) const; double coordToPixel(double value) const; SelectablePart getPartAt(const QPointF &pos) const; QList<QCPAbstractPlottable*> plottables() const; QList<QCPGraph*> graphs() const; QList<QCPAbstractItem*> items() const; static AxisType marginSideToAxisType(QCP::MarginSide side); static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } static AxisType opposite(AxisType type); signals: void ticksRequest(); void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void scaleTypeChanged(QCPAxis::ScaleType scaleType); void selectionChanged(const QCPAxis::SelectableParts &parts); void selectableChanged(const QCPAxis::SelectableParts &parts); protected: // property members: // axis base: AxisType mAxisType; QCPAxisRect *mAxisRect; //int mOffset; // in QCPAxisPainter int mPadding; Qt::Orientation mOrientation; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter // axis label: //int mLabelPadding; // in QCPAxisPainter QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; // in QCPAxisPainter bool mTickLabels, mAutoTickLabels; //double mTickLabelRotation; // in QCPAxisPainter LabelType mTickLabelType; QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; QString mDateTimeFormat; Qt::TimeSpec mDateTimeSpec; int mNumberPrecision; QLatin1Char mNumberFormatChar; bool mNumberBeautifulPowers; //bool mNumberMultiplyCross; // QCPAxisPainter // ticks and subticks: bool mTicks; double mTickStep; int mSubTickCount, mAutoTickCount; bool mAutoTicks, mAutoTickStep, mAutoSubTicks; //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: QCPRange mRange; bool mRangeReversed; ScaleType mScaleType; double mScaleLogBase, mScaleLogBaseLogInv; // non-property members: QCPGrid *mGrid; QCPAxisPainterPrivate *mAxisPainter; int mLowestVisibleTick, mHighestVisibleTick; QVector<double> mTickVector; QVector<QString> mTickVectorLabels; QVector<double> mSubTickVector; bool mCachedMarginValid; int mCachedMargin; // introduced virtual methods: virtual void setupTickVectors(); virtual void generateAutoTicks(); virtual int calculateAutoSubTickCount(double tickStep) const; virtual int calculateMargin(); // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual QCP::Interaction selectionCategory() const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: void visibleTickBounds(int &lowIndex, int &highIndex) const; double baseLog(double value) const; double basePow(double value) const; QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; QFont getTickLabelFont() const; QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; private: Q_DISABLE_COPY(QCPAxis) friend class QCustomPlot; friend class QCPGrid; friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); virtual ~QCPAxisPainterPrivate(); virtual void draw(QCPPainter *painter); virtual int size() const; void clearCache(); QRect axisSelectionBox() const { return mAxisSelectionBox; } QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } QRect labelSelectionBox() const { return mLabelSelectionBox; } // public property members: QCPAxis::AxisType type; QPen basePen; QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters int labelPadding; // directly accessed by QCPAxis setters/getters QFont labelFont; QColor labelColor; QString label; int tickLabelPadding; // directly accessed by QCPAxis setters/getters double tickLabelRotation; // directly accessed by QCPAxis setters/getters QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters bool substituteExponent; bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters QPen tickPen, subTickPen; QFont tickLabelFont; QColor tickLabelColor; QRect axisRect, viewportRect; double offset; // directly accessed by QCPAxis setters/getters bool abbreviateDecimalPowers; bool reversedEndings; QVector<double> subTickPositions; QVector<double> tickPositions; QVector<QString> tickLabels; protected: struct CachedLabel { QPointF offset; QPixmap pixmap; }; struct TickLabelData { QString basePart, expPart; QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; QFont baseFont, expFont; }; QCustomPlot *mParentPlot; QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters QCache<QString, CachedLabel> mLabelCache; QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; virtual QByteArray generateLabelParameterHash() const; virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } bool antialiasedScatters() const { return mAntialiasedScatters; } bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setName(const QString &name); void setAntialiasedFill(bool enabled); void setAntialiasedScatters(bool enabled); void setAntialiasedErrorBars(bool enabled); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setKeyAxis(QCPAxis *axis); void setValueAxis(QCPAxis *axis); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // introduced virtual methods: virtual void clearData() = 0; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; virtual bool addToLegend(); virtual bool removeFromLegend() const; // non-property methods: void rescaleAxes(bool onlyEnlarge=false) const; void rescaleKeyAxis(bool onlyEnlarge=false) const; void rescaleValueAxis(bool onlyEnlarge=false) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: /*! Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. */ enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero }; // property members: QString mName; bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QPointer<QCPAxis> mKeyAxis, mValueAxis; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QRect clipRect() const; virtual void draw(QCPPainter *painter) = 0; virtual QCP::Interaction selectionCategory() const; void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // introduced virtual methods: virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; // non-virtual methods: void coordsToPixels(double key, double value, double &x, double &y) const; const QPointF coordsToPixels(double key, double value) const; void pixelsToCoords(double x, double y, double &key, double &value) const; void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; QPen mainPen() const; QBrush mainBrush() const; void applyFillAntialiasingHint(QCPPainter *painter) const; void applyScattersAntialiasingHint(QCPPainter *painter) const; void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; private: Q_DISABLE_COPY(QCPAbstractPlottable) friend class QCustomPlot; friend class QCPAxis; friend class QCPPlottableLegendItem; }; class QCP_LIB_DECL QCPItemAnchor { public: QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); virtual ~QCPItemAnchor(); // getters: QString name() const { return mName; } virtual QPointF pixelPoint() const; protected: // property members: QString mName; // non-property members: QCustomPlot *mParentPlot; QCPAbstractItem *mParentItem; int mAnchorId; QSet<QCPItemPosition*> mChildrenX, mChildrenY; // introduced virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return 0; } // non-virtual methods: void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted private: Q_DISABLE_COPY(QCPItemAnchor) friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { public: /*! Defines the ways an item position can be specified. Thus it defines what the numbers passed to \ref setCoords actually mean. \see setType */ enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the viewport/widget, etc. ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). }; QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); virtual ~QCPItemPosition(); // getters: PositionType type() const { return typeX(); } PositionType typeX() const { return mPositionTypeX; } PositionType typeY() const { return mPositionTypeY; } QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } double key() const { return mKey; } double value() const { return mValue; } QPointF coords() const { return QPointF(mKey, mValue); } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } QCPAxisRect *axisRect() const; virtual QPointF pixelPoint() const; // setters: void setType(PositionType type); void setTypeX(PositionType type); void setTypeY(PositionType type); bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); void setCoords(double key, double value); void setCoords(const QPointF &coords); void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); void setAxisRect(QCPAxisRect *axisRect); void setPixelPoint(const QPointF &pixelPoint); protected: // property members: PositionType mPositionTypeX, mPositionTypeY; QPointer<QCPAxis> mKeyAxis, mValueAxis; QPointer<QCPAxisRect> mAxisRect; double mKey, mValue; QCPItemAnchor *mParentAnchorX, *mParentAnchorY; // reimplemented virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return this; } private: Q_DISABLE_COPY(QCPItemPosition) }; class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: QCPAbstractItem(QCustomPlot *parentPlot); virtual ~QCPAbstractItem(); // getters: bool clipToAxisRect() const { return mClipToAxisRect; } QCPAxisRect *clipAxisRect() const; bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setClipToAxisRect(bool clip); void setClipAxisRect(QCPAxisRect *rect); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; // non-virtual methods: QList<QCPItemPosition*> positions() const { return mPositions; } QList<QCPItemAnchor*> anchors() const { return mAnchors; } QCPItemPosition *position(const QString &name) const; QCPItemAnchor *anchor(const QString &name) const; bool hasAnchor(const QString &name) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: bool mClipToAxisRect; QPointer<QCPAxisRect> mClipAxisRect; QList<QCPItemPosition*> mPositions; QList<QCPItemAnchor*> mAnchors; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // introduced virtual methods: virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; QCPItemPosition *createPosition(const QString &name); QCPItemAnchor *createAnchor(const QString &name, int anchorId); private: Q_DISABLE_COPY(QCPAbstractItem) friend class QCustomPlot; friend class QCPItemAnchor; }; class QCP_LIB_DECL QCustomPlot : public QWidget { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) /// \endcond public: /*! Defines how a layer should be inserted relative to an other layer. \see addLayer, moveLayer */ enum LayerInsertMode { limBelow ///< Layer is inserted below other layer ,limAbove ///< Layer is inserted above other layer }; Q_ENUMS(LayerInsertMode) /*! Defines with what timing the QCustomPlot surface is refreshed after a replot. \see replot */ enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. }; explicit QCustomPlot(QWidget *parent = 0); virtual ~QCustomPlot(); // getters: QRect viewport() const { return mViewport; } QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } QCPLayoutGrid *plotLayout() const { return mPlotLayout; } QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } const QCP::Interactions interactions() const { return mInteractions; } int selectionTolerance() const { return mSelectionTolerance; } bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } QCP::PlottingHints plottingHints() const { return mPlottingHints; } Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } // setters: void setViewport(const QRect &rect); void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); void setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements); void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); void setAutoAddPlottableToLegend(bool on); void setInteractions(const QCP::Interactions &interactions); void setInteraction(const QCP::Interaction &interaction, bool enabled=true); void setSelectionTolerance(int pixels); void setNoAntialiasingOnDrag(bool enabled); void setPlottingHints(const QCP::PlottingHints &hints); void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); void setMultiSelectModifier(Qt::KeyboardModifier modifier); // non-property methods: // plottable interface: QCPAbstractPlottable *plottable(int index); QCPAbstractPlottable *plottable(); bool addPlottable(QCPAbstractPlottable *plottable); bool removePlottable(QCPAbstractPlottable *plottable); bool removePlottable(int index); int clearPlottables(); int plottableCount() const; QList<QCPAbstractPlottable*> selectedPlottables() const; QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; bool hasPlottable(QCPAbstractPlottable *plottable) const; // specialized interface for QCPGraph: QCPGraph *graph(int index) const; QCPGraph *graph() const; QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); bool removeGraph(QCPGraph *graph); bool removeGraph(int index); int clearGraphs(); int graphCount() const; QList<QCPGraph*> selectedGraphs() const; // item interface: QCPAbstractItem *item(int index) const; QCPAbstractItem *item() const; bool addItem(QCPAbstractItem* item); bool removeItem(QCPAbstractItem *item); bool removeItem(int index); int clearItems(); int itemCount() const; QList<QCPAbstractItem*> selectedItems() const; QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; bool hasItem(QCPAbstractItem *item) const; // layer interface: QCPLayer *layer(const QString &name) const; QCPLayer *layer(int index) const; QCPLayer *currentLayer() const; bool setCurrentLayer(const QString &name); bool setCurrentLayer(QCPLayer *layer); int layerCount() const; bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); bool removeLayer(QCPLayer *layer); bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); // axis rect/layout interface: int axisRectCount() const; QCPAxisRect* axisRect(int index=0) const; QList<QCPAxisRect*> axisRects() const; QCPLayoutElement* layoutElementAt(const QPointF &pos) const; Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); QList<QCPAxis*> selectedAxes() const; QList<QCPLegend*> selectedLegends() const; Q_SLOT void deselectAll(); bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator=QString(), const QString &pdfTitle=QString()); bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); QPixmap toPixmap(int width=0, int height=0, double scale=1.0); void toPainter(QCPPainter *painter, int width=0, int height=0); Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; QCPLegend *legend; signals: void mouseDoubleClick(QMouseEvent *event); void mousePress(QMouseEvent *event); void mouseMove(QMouseEvent *event); void mouseRelease(QMouseEvent *event); void mouseWheel(QWheelEvent *event); void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); void itemClick(QCPAbstractItem *item, QMouseEvent *event); void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void titleClick(QMouseEvent *event, QCPPlotTitle *title); void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); void selectionChangedByUser(); void beforeReplot(); void afterReplot(); protected: // property members: QRect mViewport; QCPLayoutGrid *mPlotLayout; bool mAutoAddPlottableToLegend; QList<QCPAbstractPlottable*> mPlottables; QList<QCPGraph*> mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph QList<QCPAbstractItem*> mItems; QList<QCPLayer*> mLayers; QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; QCP::Interactions mInteractions; int mSelectionTolerance; bool mNoAntialiasingOnDrag; QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayer *mCurrentLayer; QCP::PlottingHints mPlottingHints; Qt::KeyboardModifier mMultiSelectModifier; // non-property members: QPixmap mPaintBuffer; QPoint mMousePressPos; QPointer<QCPLayoutElement> mMouseEventElement; bool mReplotting; // reimplemented virtual methods: virtual QSize minimumSizeHint() const; virtual QSize sizeHint() const; virtual void paintEvent(QPaintEvent *event); virtual void resizeEvent(QResizeEvent *event); virtual void mouseDoubleClickEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); // introduced virtual methods: virtual void draw(QCPPainter *painter); virtual void axisRemoved(QCPAxis *axis); virtual void legendRemoved(QCPLegend *legend); // non-virtual methods: void updateLayerIndices() const; QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; void drawBackground(QCPPainter *painter); friend class QCPLegend; friend class QCPAxis; friend class QCPLayer; friend class QCPAxisRect; }; class QCP_LIB_DECL QCPColorGradient { Q_GADGET public: /*! Defines the color spaces in which color interpolation between gradient stops can be performed. \see setColorInterpolation */ enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) }; Q_ENUMS(ColorInterpolation) /*! Defines the available presets that can be loaded with \ref loadPreset. See the documentation there for an image of the presets. */ enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) ,gpCandy ///< Blue over pink to white ,gpGeography ///< Colors suitable to represent different elevations on geographical maps ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) }; Q_ENUMS(GradientPreset) QCPColorGradient(GradientPreset preset=gpCold); bool operator==(const QCPColorGradient &other) const; bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } // getters: int levelCount() const { return mLevelCount; } QMap<double, QColor> colorStops() const { return mColorStops; } ColorInterpolation colorInterpolation() const { return mColorInterpolation; } bool periodic() const { return mPeriodic; } // setters: void setLevelCount(int n); void setColorStops(const QMap<double, QColor> &colorStops); void setColorStopAt(double position, const QColor &color); void setColorInterpolation(ColorInterpolation interpolation); void setPeriodic(bool enabled); // non-property methods: void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); QRgb color(double position, const QCPRange &range, bool logarithmic=false); void loadPreset(GradientPreset preset); void clearColorStops(); QCPColorGradient inverted() const; protected: void updateColorBuffer(); // property members: int mLevelCount; QMap<double, QColor> mColorStops; ColorInterpolation mColorInterpolation; bool mPeriodic; // non-property members: QVector<QRgb> mColorBuffer; bool mColorBufferInvalidated; }; class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); virtual ~QCPAxisRect(); // getters: QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } Qt::Orientations rangeDrag() const { return mRangeDrag; } Qt::Orientations rangeZoom() const { return mRangeZoom; } QCPAxis *rangeDragAxis(Qt::Orientation orientation); QCPAxis *rangeZoomAxis(Qt::Orientation orientation); double rangeZoomFactor(Qt::Orientation orientation); // setters: void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setRangeDrag(Qt::Orientations orientations); void setRangeZoom(Qt::Orientations orientations); void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomFactor(double horizontalFactor, double verticalFactor); void setRangeZoomFactor(double factor); // non-property methods: int axisCount(QCPAxis::AxisType type) const; QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; QList<QCPAxis*> axes(QCPAxis::AxisTypes types) const; QList<QCPAxis*> axes() const; QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=0); QList<QCPAxis*> addAxes(QCPAxis::AxisTypes types); bool removeAxis(QCPAxis *axis); QCPLayoutInset *insetLayout() const { return mInsetLayout; } void setupFullAxesBox(bool connectRanges=false); QList<QCPAbstractPlottable*> plottables() const; QList<QCPGraph*> graphs() const; QList<QCPAbstractItem*> items() const; // read-only interface imitating a QRect: int left() const { return mRect.left(); } int right() const { return mRect.right(); } int top() const { return mRect.top(); } int bottom() const { return mRect.bottom(); } int width() const { return mRect.width(); } int height() const { return mRect.height(); } QSize size() const { return mRect.size(); } QPoint topLeft() const { return mRect.topLeft(); } QPoint topRight() const { return mRect.topRight(); } QPoint bottomLeft() const { return mRect.bottomLeft(); } QPoint bottomRight() const { return mRect.bottomRight(); } QPoint center() const { return mRect.center(); } // reimplemented virtual methods: virtual void update(UpdatePhase phase); virtual QList<QCPLayoutElement*> elements(bool recursive) const; protected: // property members: QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayoutInset *mInsetLayout; Qt::Orientations mRangeDrag, mRangeZoom; QPointer<QCPAxis> mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; double mRangeZoomFactorHorz, mRangeZoomFactorVert; // non-property members: QCPRange mDragStartHorzRange, mDragStartVertRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QPoint mDragStart; bool mDragging; QHash<QCPAxis::AxisType, QList<QCPAxis*> > mAxes; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual int calculateAutoMargin(QCP::MarginSide side); // events: virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); // non-property methods: void drawBackground(QCPPainter *painter); void updateAxesOffset(QCPAxis::AxisType type); private: Q_DISABLE_COPY(QCPAxisRect) friend class QCustomPlot; }; class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) /// \endcond public: explicit QCPAbstractLegendItem(QCPLegend *parent); // getters: QCPLegend *parentLegend() const { return mParentLegend; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QCPLegend *mParentLegend; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual QRect clipRect() const; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); private: Q_DISABLE_COPY(QCPAbstractLegendItem) friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { Q_OBJECT public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); // getters: QCPAbstractPlottable *plottable() { return mPlottable; } protected: // property members: QCPAbstractPlottable *mPlottable; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QSize minimumSizeHint() const; // non-virtual methods: QPen getIconBorderPen() const; QColor getTextColor() const; QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) /// \endcond public: /*! Defines the selectable parts of a legend \see setSelectedParts, setSelectableParts */ enum SelectablePart { spNone = 0x000 ///< <tt>0x000</tt> None ,spLegendBox = 0x001 ///< <tt>0x001</tt> The legend box (frame) ,spItems = 0x002 ///< <tt>0x002</tt> Legend items individually (see \ref selectedItems) }; Q_FLAGS(SelectablePart SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPLegend(); virtual ~QCPLegend(); // getters: QPen borderPen() const { return mBorderPen; } QBrush brush() const { return mBrush; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QSize iconSize() const { return mIconSize; } int iconTextPadding() const { return mIconTextPadding; } QPen iconBorderPen() const { return mIconBorderPen; } SelectableParts selectableParts() const { return mSelectableParts; } SelectableParts selectedParts() const; QPen selectedBorderPen() const { return mSelectedBorderPen; } QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } QBrush selectedBrush() const { return mSelectedBrush; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } // setters: void setBorderPen(const QPen &pen); void setBrush(const QBrush &brush); void setFont(const QFont &font); void setTextColor(const QColor &color); void setIconSize(const QSize &size); void setIconSize(int width, int height); void setIconTextPadding(int padding); void setIconBorderPen(const QPen &pen); Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); void setSelectedBorderPen(const QPen &pen); void setSelectedIconBorderPen(const QPen &pen); void setSelectedBrush(const QBrush &brush); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: QCPAbstractLegendItem *item(int index) const; QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; int itemCount() const; bool hasItem(QCPAbstractLegendItem *item) const; bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; bool addItem(QCPAbstractLegendItem *item); bool removeItem(int index); bool removeItem(QCPAbstractLegendItem *item); void clearItems(); QList<QCPAbstractLegendItem*> selectedItems() const; signals: void selectionChanged(QCPLegend::SelectableParts parts); void selectableChanged(QCPLegend::SelectableParts parts); protected: // property members: QPen mBorderPen, mIconBorderPen; QBrush mBrush; QFont mFont; QColor mTextColor; QSize mIconSize; int mIconTextPadding; SelectableParts mSelectedParts, mSelectableParts; QPen mSelectedBorderPen, mSelectedIconBorderPen; QBrush mSelectedBrush; QFont mSelectedFont; QColor mSelectedTextColor; // reimplemented virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: QPen getBorderPen() const; QBrush getBrush() const; private: Q_DISABLE_COPY(QCPLegend) friend class QCustomPlot; friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: explicit QCPPlotTitle(QCustomPlot *parentPlot); explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); // getters: QString text() const { return mText; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setText(const QString &text); void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QString mText; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; QRect mTextBoundingRect; bool mSelectable, mSelected; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: QFont mainFont() const; QColor mainTextColor() const; private: Q_DISABLE_COPY(QCPPlotTitle) }; class QCPColorScaleAxisRectPrivate : public QCPAxisRect { Q_OBJECT public: explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: QCPColorScale *mParentColorScale; QImage mGradientImage; bool mGradientImageInvalidated; // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale using QCPAxisRect::calculateAutoMargin; using QCPAxisRect::mousePressEvent; using QCPAxisRect::mouseMoveEvent; using QCPAxisRect::mouseReleaseEvent; using QCPAxisRect::wheelEvent; using QCPAxisRect::update; virtual void draw(QCPPainter *painter); void updateGradientImage(); Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPColorScale(QCustomPlot *parentPlot); virtual ~QCPColorScale(); // getters: QCPAxis *axis() const { return mColorAxis.data(); } QCPAxis::AxisType type() const { return mType; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } QCPColorGradient gradient() const { return mGradient; } QString label() const; int barWidth () const { return mBarWidth; } bool rangeDrag() const; bool rangeZoom() const; // setters: void setType(QCPAxis::AxisType type); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setLabel(const QString &str); void setBarWidth(int width); void setRangeDrag(bool enabled); void setRangeZoom(bool enabled); // non-property methods: QList<QCPColorMap*> colorMaps() const; void rescaleDataRange(bool onlyVisibleMaps); // reimplemented virtual methods: virtual void update(UpdatePhase phase); signals: void dataRangeChanged(QCPRange newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(QCPColorGradient newGradient); protected: // property members: QCPAxis::AxisType mType; QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorGradient mGradient; int mBarWidth; // non-property members: QPointer<QCPColorScaleAxisRectPrivate> mAxisRect; QPointer<QCPAxis> mColorAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); private: Q_DISABLE_COPY(QCPColorScale) friend class QCPColorScaleAxisRectPrivate; }; /*! \file */ class QCP_LIB_DECL QCPData { public: QCPData(); QCPData(double key, double value); double key, value; double keyErrorPlus, keyErrorMinus; double valueErrorPlus, valueErrorMinus; }; Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); /*! \typedef QCPDataMap Container for storing \ref QCPData items in a sorted fashion. The key of the map is the key member of the QCPData instance. This is the container in which QCPGraph holds its data. \see QCPData, QCPGraph::setData */ typedef QMap<double, QCPData> QCPDataMap; typedef QMapIterator<double, QCPData> QCPDataMapIterator; typedef QMutableMapIterator<double, QCPData> QCPDataMutableMapIterator; class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) /// \endcond public: /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented ///< with symbols according to the scatter style, see \ref setScatterStyle) ,lsLine ///< data points are connected by a straight line ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point ,lsStepCenter ///< line is drawn as steps where the step is in between two data points ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line }; Q_ENUMS(LineStyle) /*! Defines what kind of error bars are drawn for each data point */ enum ErrorType { etNone ///< No error bars are shown ,etKey ///< Error bars for the key dimension of the data point are shown ,etValue ///< Error bars for the value dimension of the data point are shown ,etBoth ///< Error bars for both key and value dimensions of the data point are shown }; Q_ENUMS(ErrorType) explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPGraph(); // getters: QCPDataMap *data() const { return mData; } LineStyle lineStyle() const { return mLineStyle; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } ErrorType errorType() const { return mErrorType; } QPen errorPen() const { return mErrorPen; } double errorBarSize() const { return mErrorBarSize; } bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } bool adaptiveSampling() const { return mAdaptiveSampling; } // setters: void setData(QCPDataMap *data, bool copy=false); void setData(const QVector<double> &key, const QVector<double> &value); void setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError); void setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus); void setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError); void setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus); void setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError); void setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus); void setLineStyle(LineStyle ls); void setScatterStyle(const QCPScatterStyle &style); void setErrorType(ErrorType errorType); void setErrorPen(const QPen &pen); void setErrorBarSize(double size); void setErrorBarSkipSymbol(bool enabled); void setChannelFillGraph(QCPGraph *targetGraph); void setAdaptiveSampling(bool enabled); // non-property methods: void addData(const QCPDataMap &dataMap); void addData(const QCPData &data); void addData(double key, double value); void addData(const QVector<double> &keys, const QVector<double> &values); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; using QCPAbstractPlottable::rescaleAxes; using QCPAbstractPlottable::rescaleKeyAxis; using QCPAbstractPlottable::rescaleValueAxis; void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface protected: // property members: QCPDataMap *mData; QPen mErrorPen; LineStyle mLineStyle; QCPScatterStyle mScatterStyle; ErrorType mErrorType; double mErrorBarSize; bool mErrorBarSkipSymbol; QPointer<QCPGraph> mChannelFillGraph; bool mAdaptiveSampling; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface // introduced virtual methods: virtual void drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const; virtual void drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const; virtual void drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const; virtual void drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const; // non-virtual methods: void getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const; void getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const; void getScatterPlotData(QVector<QCPData> *scatterData) const; void getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const; void getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const; void getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const; void getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const; void getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const; void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; void addFillBasePoints(QVector<QPointF> *lineData) const; void removeFillBasePoints(QVector<QPointF> *lineData) const; QPointF lowerFillBasePoint(double lowerKey) const; QPointF upperFillBasePoint(double upperKey) const; const QPolygonF getChannelFillPolygon(const QVector<QPointF> *lineData) const; int findIndexBelowX(const QVector<QPointF> *data, double x) const; int findIndexAboveX(const QVector<QPointF> *data, double x) const; int findIndexBelowY(const QVector<QPointF> *data, double y) const; int findIndexAboveY(const QVector<QPointF> *data, double y) const; double pointDistance(const QPointF &pixelPoint) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPCurveData { public: QCPCurveData(); QCPCurveData(double t, double key, double value); double t, key, value; }; Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); /*! \typedef QCPCurveDataMap Container for storing \ref QCPCurveData items in a sorted fashion. The key of the map is the t member of the QCPCurveData instance. This is the container in which QCPCurve holds its data. \see QCPCurveData, QCPCurve::setData */ typedef QMap<double, QCPCurveData> QCPCurveDataMap; typedef QMapIterator<double, QCPCurveData> QCPCurveDataMapIterator; typedef QMutableMapIterator<double, QCPCurveData> QCPCurveDataMutableMapIterator; class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) /// \endcond public: /*! Defines how the curve's line is represented visually in the plot. The line is drawn with the current pen of the curve (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) ,lsLine ///< Data points are connected with a straight line }; explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPCurve(); // getters: QCPCurveDataMap *data() const { return mData; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } LineStyle lineStyle() const { return mLineStyle; } // setters: void setData(QCPCurveDataMap *data, bool copy=false); void setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value); void setData(const QVector<double> &key, const QVector<double> &value); void setScatterStyle(const QCPScatterStyle &style); void setLineStyle(LineStyle style); // non-property methods: void addData(const QCPCurveDataMap &dataMap); void addData(const QCPCurveData &data); void addData(double t, double key, double value); void addData(double key, double value); void addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values); void removeDataBefore(double t); void removeDataAfter(double t); void removeData(double fromt, double tot); void removeData(double t); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPCurveDataMap *mData; QCPScatterStyle mScatterStyle; LineStyle mLineStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // introduced virtual methods: virtual void drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const; // non-virtual methods: void getCurveData(QVector<QPointF> *lineData) const; int getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const; QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; QVector<QPointF> getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; bool mayTraverse(int prevRegion, int currentRegion) const; bool getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const; void getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const; double pointDistance(const QPointF &pixelPoint) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPBarsGroup : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) Q_PROPERTY(double spacing READ spacing WRITE setSpacing) /// \endcond public: /*! Defines the ways the spacing between bars in the group can be specified. Thus it defines what the number passed to \ref setSpacing actually means. \see setSpacingType, setSpacing */ enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels ,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size ,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range }; QCPBarsGroup(QCustomPlot *parentPlot); ~QCPBarsGroup(); // getters: SpacingType spacingType() const { return mSpacingType; } double spacing() const { return mSpacing; } // setters: void setSpacingType(SpacingType spacingType); void setSpacing(double spacing); // non-virtual methods: QList<QCPBars*> bars() const { return mBars; } QCPBars* bars(int index) const; int size() const { return mBars.size(); } bool isEmpty() const { return mBars.isEmpty(); } void clear(); bool contains(QCPBars *bars) const { return mBars.contains(bars); } void append(QCPBars *bars); void insert(int i, QCPBars *bars); void remove(QCPBars *bars); protected: // non-property members: QCustomPlot *mParentPlot; SpacingType mSpacingType; double mSpacing; QList<QCPBars*> mBars; // non-virtual methods: void registerBars(QCPBars *bars); void unregisterBars(QCPBars *bars); // virtual methods: double keyPixelOffset(const QCPBars *bars, double keyCoord); double getPixelSpacing(const QCPBars *bars, double keyCoord); private: Q_DISABLE_COPY(QCPBarsGroup) friend class QCPBars; }; class QCP_LIB_DECL QCPBarData { public: QCPBarData(); QCPBarData(double key, double value); double key, value; }; Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); /*! \typedef QCPBarDataMap Container for storing \ref QCPBarData items in a sorted fashion. The key of the map is the key member of the QCPBarData instance. This is the container in which QCPBars holds its data. \see QCPBarData, QCPBars::setData */ typedef QMap<double, QCPBarData> QCPBarDataMap; typedef QMapIterator<double, QCPBarData> QCPBarDataMapIterator; typedef QMutableMapIterator<double, QCPBarData> QCPBarDataMutableMapIterator; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup) Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue) Q_PROPERTY(QCPBars* barBelow READ barBelow) Q_PROPERTY(QCPBars* barAbove READ barAbove) /// \endcond public: /*! Defines the ways the width of the bar can be specified. Thus it defines what the number passed to \ref setWidth actually means. \see setWidthType, setWidth */ enum WidthType { wtAbsolute ///< Bar width is in absolute pixels ,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size ,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range }; Q_ENUMS(WidthType) explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPBars(); // getters: double width() const { return mWidth; } WidthType widthType() const { return mWidthType; } QCPBarsGroup *barsGroup() const { return mBarsGroup; } double baseValue() const { return mBaseValue; } QCPBars *barBelow() const { return mBarBelow.data(); } QCPBars *barAbove() const { return mBarAbove.data(); } QCPBarDataMap *data() const { return mData; } // setters: void setWidth(double width); void setWidthType(WidthType widthType); void setBarsGroup(QCPBarsGroup *barsGroup); void setBaseValue(double baseValue); void setData(QCPBarDataMap *data, bool copy=false); void setData(const QVector<double> &key, const QVector<double> &value); // non-property methods: void moveBelow(QCPBars *bars); void moveAbove(QCPBars *bars); void addData(const QCPBarDataMap &dataMap); void addData(const QCPBarData &data); void addData(double key, double value); void addData(const QVector<double> &keys, const QVector<double> &values); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPBarDataMap *mData; double mWidth; WidthType mWidthType; QCPBarsGroup *mBarsGroup; double mBaseValue; QPointer<QCPBars> mBarBelow, mBarAbove; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // non-virtual methods: void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; QPolygonF getBarPolygon(double key, double value) const; void getPixelWidth(double key, double &lower, double &upper) const; double getStackedBaseValue(double key, bool positive) const; static void connectBars(QCPBars* lower, QCPBars* upper); friend class QCustomPlot; friend class QCPLegend; friend class QCPBarsGroup; }; /*! \file */ class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double key READ key WRITE setKey) Q_PROPERTY(double minimum READ minimum WRITE setMinimum) Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) Q_PROPERTY(double median READ median WRITE setMedian) Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) Q_PROPERTY(double maximum READ maximum WRITE setMaximum) Q_PROPERTY(QVector<double> outliers READ outliers WRITE setOutliers) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) /// \endcond public: explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: double key() const { return mKey; } double minimum() const { return mMinimum; } double lowerQuartile() const { return mLowerQuartile; } double median() const { return mMedian; } double upperQuartile() const { return mUpperQuartile; } double maximum() const { return mMaximum; } QVector<double> outliers() const { return mOutliers; } double width() const { return mWidth; } double whiskerWidth() const { return mWhiskerWidth; } QPen whiskerPen() const { return mWhiskerPen; } QPen whiskerBarPen() const { return mWhiskerBarPen; } QPen medianPen() const { return mMedianPen; } QCPScatterStyle outlierStyle() const { return mOutlierStyle; } // setters: void setKey(double key); void setMinimum(double value); void setLowerQuartile(double value); void setMedian(double value); void setUpperQuartile(double value); void setMaximum(double value); void setOutliers(const QVector<double> &values); void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); void setWidth(double width); void setWhiskerWidth(double width); void setWhiskerPen(const QPen &pen); void setWhiskerBarPen(const QPen &pen); void setMedianPen(const QPen &pen); void setOutlierStyle(const QCPScatterStyle &style); // non-property methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QVector<double> mOutliers; double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; double mWidth; double mWhiskerWidth; QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; QCPScatterStyle mOutlierStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // introduced virtual methods: virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; virtual void drawMedian(QCPPainter *painter) const; virtual void drawWhiskers(QCPPainter *painter) const; virtual void drawOutliers(QCPPainter *painter) const; friend class QCustomPlot; friend class QCPLegend; }; class QCP_LIB_DECL QCPColorMapData { public: QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); ~QCPColorMapData(); QCPColorMapData(const QCPColorMapData &other); QCPColorMapData &operator=(const QCPColorMapData &other); // getters: int keySize() const { return mKeySize; } int valueSize() const { return mValueSize; } QCPRange keyRange() const { return mKeyRange; } QCPRange valueRange() const { return mValueRange; } QCPRange dataBounds() const { return mDataBounds; } double data(double key, double value); double cell(int keyIndex, int valueIndex); // setters: void setSize(int keySize, int valueSize); void setKeySize(int keySize); void setValueSize(int valueSize); void setRange(const QCPRange &keyRange, const QCPRange &valueRange); void setKeyRange(const QCPRange &keyRange); void setValueRange(const QCPRange &valueRange); void setData(double key, double value, double z); void setCell(int keyIndex, int valueIndex, double z); // non-property methods: void recalculateDataBounds(); void clear(); void fill(double z); bool isEmpty() const { return mIsEmpty; } void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; protected: // property members: int mKeySize, mValueSize; QCPRange mKeyRange, mValueRange; bool mIsEmpty; // non-property members: double *mData; QCPRange mDataBounds; bool mDataModified; friend class QCPColorMap; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) /// \endcond public: explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPColorMap(); // getters: QCPColorMapData *data() const { return mMapData; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } bool interpolate() const { return mInterpolate; } bool tightBoundary() const { return mTightBoundary; } QCPColorGradient gradient() const { return mGradient; } QCPColorScale *colorScale() const { return mColorScale.data(); } // setters: void setData(QCPColorMapData *data, bool copy=false); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setInterpolate(bool enabled); void setTightBoundary(bool enabled); void setColorScale(QCPColorScale *colorScale); // non-property methods: void rescaleDataRange(bool recalculateDataBounds=false); Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void dataRangeChanged(QCPRange newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(QCPColorGradient newGradient); protected: // property members: QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorMapData *mMapData; QCPColorGradient mGradient; bool mInterpolate; bool mTightBoundary; QPointer<QCPColorScale> mColorScale; // non-property members: QImage mMapImage, mUndersampledMapImage; QPixmap mLegendIcon; bool mMapImageInvalidated; // introduced virtual methods: virtual void updateMapImage(); // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPFinancialData { public: QCPFinancialData(); QCPFinancialData(double key, double open, double high, double low, double close); double key, open, high, low, close; }; Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_TYPE); /*! \typedef QCPFinancialDataMap Container for storing \ref QCPFinancialData items in a sorted fashion. The key of the map is the key member of the QCPFinancialData instance. This is the container in which QCPFinancial holds its data. \see QCPFinancial, QCPFinancial::setData */ typedef QMap<double, QCPFinancialData> QCPFinancialDataMap; typedef QMapIterator<double, QCPFinancialData> QCPFinancialDataMapIterator; typedef QMutableMapIterator<double, QCPFinancialData> QCPFinancialDataMutableMapIterator; class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) /// \endcond public: /*! Defines the possible representations of OHLC data in the plot. \see setChartStyle */ enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation ,csCandlestick ///< Candlestick representation }; Q_ENUMS(ChartStyle) explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPFinancial(); // getters: QCPFinancialDataMap *data() const { return mData; } ChartStyle chartStyle() const { return mChartStyle; } double width() const { return mWidth; } bool twoColored() const { return mTwoColored; } QBrush brushPositive() const { return mBrushPositive; } QBrush brushNegative() const { return mBrushNegative; } QPen penPositive() const { return mPenPositive; } QPen penNegative() const { return mPenNegative; } // setters: void setData(QCPFinancialDataMap *data, bool copy=false); void setData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close); void setChartStyle(ChartStyle style); void setWidth(double width); void setTwoColored(bool twoColored); void setBrushPositive(const QBrush &brush); void setBrushNegative(const QBrush &brush); void setPenPositive(const QPen &pen); void setPenNegative(const QPen &pen); // non-property methods: void addData(const QCPFinancialDataMap &dataMap); void addData(const QCPFinancialData &data); void addData(double key, double open, double high, double low, double close); void addData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // static methods: static QCPFinancialDataMap timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset = 0); protected: // property members: QCPFinancialDataMap *mData; ChartStyle mChartStyle; double mWidth; bool mTwoColored; QBrush mBrushPositive, mBrushNegative; QPen mPenPositive, mPenNegative; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // non-virtual methods: void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; void getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const; friend class QCustomPlot; friend class QCPLegend; }; class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: QCPItemStraightLine(QCustomPlot *parentPlot); virtual ~QCPItemStraightLine(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const point1; QCPItemPosition * const point2; protected: // property members: QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: QCPItemLine(QCustomPlot *parentPlot); virtual ~QCPItemLine(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const start; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: QCPItemCurve(QCustomPlot *parentPlot); virtual ~QCPItemCurve(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const start; QCPItemPosition * const startDir; QCPItemPosition * const endDir; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QPen mainPen() const; }; class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: QCPItemRect(QCustomPlot *parentPlot); virtual ~QCPItemRect(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) Q_PROPERTY(double rotation READ rotation WRITE setRotation) Q_PROPERTY(QMargins padding READ padding WRITE setPadding) /// \endcond public: QCPItemText(QCustomPlot *parentPlot); virtual ~QCPItemText(); // getters: QColor color() const { return mColor; } QColor selectedColor() const { return mSelectedColor; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QFont font() const { return mFont; } QFont selectedFont() const { return mSelectedFont; } QString text() const { return mText; } Qt::Alignment positionAlignment() const { return mPositionAlignment; } Qt::Alignment textAlignment() const { return mTextAlignment; } double rotation() const { return mRotation; } QMargins padding() const { return mPadding; } // setters; void setColor(const QColor &color); void setSelectedColor(const QColor &color); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setFont(const QFont &font); void setSelectedFont(const QFont &font); void setText(const QString &text); void setPositionAlignment(Qt::Alignment alignment); void setTextAlignment(Qt::Alignment alignment); void setRotation(double degrees); void setPadding(const QMargins &padding); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const position; QCPItemAnchor * const topLeft; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottomRight; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QColor mColor, mSelectedColor; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QFont mFont, mSelectedFont; QString mText; Qt::Alignment mPositionAlignment; Qt::Alignment mTextAlignment; double mRotation; QMargins mPadding; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; QFont mainFont() const; QColor mainColor() const; QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: QCPItemEllipse(QCustomPlot *parentPlot); virtual ~QCPItemEllipse(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const topLeftRim; QCPItemAnchor * const top; QCPItemAnchor * const topRightRim; QCPItemAnchor * const right; QCPItemAnchor * const bottomRightRim; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeftRim; QCPItemAnchor * const left; QCPItemAnchor * const center; protected: enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) Q_PROPERTY(bool scaled READ scaled WRITE setScaled) Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: QCPItemPixmap(QCustomPlot *parentPlot); virtual ~QCPItemPixmap(); // getters: QPixmap pixmap() const { return mPixmap; } bool scaled() const { return mScaled; } Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } Qt::TransformationMode transformationMode() const { return mTransformationMode; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPixmap(const QPixmap &pixmap); void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPixmap mPixmap; QPixmap mScaledPixmap; bool mScaled; bool mScaledPixmapInvalidated; Qt::AspectRatioMode mAspectRatioMode; Qt::TransformationMode mTransformationMode; QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(double size READ size WRITE setSize) Q_PROPERTY(TracerStyle style READ style WRITE setStyle) Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) /// \endcond public: /*! The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. \see setStyle */ enum TracerStyle { tsNone ///< The tracer is not visible ,tsPlus ///< A plus shaped crosshair with limited size ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect ,tsCircle ///< A circle ,tsSquare ///< A square }; Q_ENUMS(TracerStyle) QCPItemTracer(QCustomPlot *parentPlot); virtual ~QCPItemTracer(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } double size() const { return mSize; } TracerStyle style() const { return mStyle; } QCPGraph *graph() const { return mGraph; } double graphKey() const { return mGraphKey; } bool interpolating() const { return mInterpolating; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setSize(double size); void setStyle(TracerStyle style); void setGraph(QCPGraph *graph); void setGraphKey(double key); void setInterpolating(bool enabled); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: void updatePosition(); QCPItemPosition * const position; protected: // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; double mSize; TracerStyle mStyle; QCPGraph *mGraph; double mGraphKey; bool mInterpolating; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(double length READ length WRITE setLength) Q_PROPERTY(BracketStyle style READ style WRITE setStyle) /// \endcond public: enum BracketStyle { bsSquare ///< A brace with angled edges ,bsRound ///< A brace with round edges ,bsCurly ///< A curly brace ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression }; QCPItemBracket(QCustomPlot *parentPlot); virtual ~QCPItemBracket(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } double length() const { return mLength; } BracketStyle style() const { return mStyle; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setLength(double length); void setStyle(BracketStyle style); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const left; QCPItemPosition * const right; QCPItemAnchor * const center; protected: // property members: enum AnchorIndex {aiCenter}; QPen mPen, mSelectedPen; double mLength; BracketStyle mStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; }; #endif // QCUSTOMPLOT_H
149,287
C
38.609445
236
0.737365
adegirmenci/HBL-ICEbot/icebot_definitions.h
#ifndef ICEBOT_DEFINITIONS #define ICEBOT_DEFINITIONS //*****************************************************************************// // // Author: Alperen Degirmenci // // Date: 11/29/2015 // Last Update: 09/07/2016 // // COPYRIGHT: COPYRIGHT HARVARD BIOROBOTICS LABORATORY - 2015, 2016 // //*****************************************************************************// // // DESCRIPTION: icebot_definitions.h // // Header file containing definitions of constants and structures required. // //*****************************************************************************// #include "../AscensionWidget/3DGAPI/ATC3DG.h" // Alternative to using Boost for value of Pi //const long double PI = 3.141592653589793238L; //const double PI = 3.141592653589793; //const float PI = 3.1415927; enum LOG_TYPES { LOG_INFO = 0, // regular messages LOG_WARNING, // warnings LOG_ERROR, // errors LOG_FATAL // fatal errors }; enum LOG_SOURCE { SRC_EM = 0, SRC_EPOS, SRC_FRMGRAB, SRC_EPIPHAN, SRC_LABJACK, SRC_OMNI, SRC_DATALOGGER, SRC_CONTROLLER, SRC_GUI, SRC_UNKNOWN }; // ********************** // ******** EM ******** // ********************** enum EM_ERROR_CODES { EM_SUCCESS = 0, // EM_FAIL, EM_BELOW_MIN_SAMPLE_RATE, EM_ABOVE_MAX_SAMPLE_RATE, EM_CANT_MUTATE_WHILE_RUNNING, EM_FREQ_SET_FAILURE, EM_SET_DATA_FORMAT_TYPE_FAILURE }; enum EM_EVENT_IDS { EM_INITIALIZE_BEGIN = 0, EM_INITIALIZE_FAILED, EM_INITIALIZED, EM_SENSORS_DETECTED, EM_TRANSMITTER_SET, EM_FREQ_DETECTED, EM_FREQ_SET, EM_FREQ_SET_FAILED, EM_ACQUISITION_STARTED, EM_START_ACQUISITION_FAILED, EM_ACQUIRE_FAILED, EM_ACQUISITION_STOPPED, EM_STOP_ACQUISITION_FAILED, EM_DISCONNECT_FAILED, EM_DISCONNECTED, EM_EPOCH_SET, EM_EPOCH_SET_FAILED, EM_SET_DATA_FORMAT_TYPE, EM_SET_DATA_FORMAT_TYPE_FAILED }; enum EM_SENSOR_IDS { EM_SENSOR_BB = 0, EM_SENSOR_BT, EM_SENSOR_INST, EM_SENSOR_CHEST }; static const char* const EM_SENSOR_NAMES[] = {"BB", "BT", "INST", "CHEST"}; static const int EM_DEFAULT_SAMPLE_RATE = 150; static const int EM_MIN_SAMPLE_RATE = 20; static const int EM_MAX_SAMPLE_RATE = 250; #define EM_DELTA_T_SIZE 151 //typedef DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD EM_RECORD_TYPE; // typedef DOUBLE_POSITION_MATRIX_TIME_Q_RECORD EM_RECORD_TYPE; // Preferred EM reading type is : DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD // ********************** // ******** EPOS ******** // ********************** enum EPOS_ERROR_CODES { EPOS_SUCCESS = 0, EPOS_FAIL, EPOS_FAILED_TO_CONNECT }; enum EPOS_EVENT_IDS { EPOS_INITIALIZE_BEGIN = 0, EPOS_INITIALIZE_FAILED, EPOS_INITIALIZED, EPOS_SERVO_LOOP_STARTED, EPOS_SERVO_LOOP_STOPPED, EPOS_SERVO_TO_POS_FAILED, EPOS_EPOCH_SET, EPOS_EPOCH_SET_FAILED, EPOS_DISABLE_MOTOR_FAILED, EPOS_DISABLE_MOTOR_SUCCESS, EPOS_DEVICE_CANT_CONNECT, EPOS_UPDATE_QC_FAILED, EPOS_HALT_FAILED, EPOS_DISCONNECTED, EPOS_DISCONNECT_FAILED }; enum EPOS_DATA_IDS { EPOS_COMMANDED = 0, EPOS_READ }; enum EPOS_MOTOR_STATUS { EPOS_MOTOR_DISABLED = 0, EPOS_MOTOR_ENABLED, EPOS_MOTOR_FAULT, EPOS_MOTOR_CANT_CONNECT, EPOS_INVALID_MOTOR_ID }; // enum EPOS_MOTOR_IDS // { // TRANS_MOTOR_ID = 1, // PITCH_MOTOR_ID, // YAW_MOTOR_ID, // ROLL_MOTOR_ID // }; static const int EPOS_NUM_MOTORS = 4; static const int TRANS_MOTOR_ID = 1; static const int PITCH_MOTOR_ID = 2; static const int YAW_MOTOR_ID = 3; static const int ROLL_MOTOR_ID = 4; static const int EPOS_MOTOR_IDS[EPOS_NUM_MOTORS] = {TRANS_MOTOR_ID, PITCH_MOTOR_ID, YAW_MOTOR_ID, ROLL_MOTOR_ID}; static const int TRANS_AXIS_ID = 0; static const int PITCH_AXIS_ID = 1; static const int YAW_AXIS_ID = 2; static const int ROLL_AXIS_ID = 3; static const int EPOS_AXIS_IDS[EPOS_NUM_MOTORS] = {TRANS_AXIS_ID, PITCH_AXIS_ID, YAW_AXIS_ID, ROLL_AXIS_ID}; // original values from Alienware //static const int EPOS_VELOCITY[EPOS_NUM_MOTORS] = {5000, 5000, 5000, 5000}; //static const int EPOS_ACCEL[EPOS_NUM_MOTORS] = {20000, 50000, 50000, 50000}; //static const int EPOS_DECEL[EPOS_NUM_MOTORS] = {20000, 30000, 30000, 30000}; // better values static const int EPOS_VELOCITY[EPOS_NUM_MOTORS] = {5000, 10000, 10000, 10000}; static const int EPOS_ACCEL[EPOS_NUM_MOTORS] = {50000, 80000, 80000, 80000}; static const int EPOS_DECEL[EPOS_NUM_MOTORS] = {50000, 70000, 70000, 70000}; // values for mapping //static const int EPOS_VELOCITY[EPOS_NUM_MOTORS] = {5000, 5000, 5000, 5000}; //static const int EPOS_ACCEL[EPOS_NUM_MOTORS] = {50000, 30000, 30000, 30000}; //static const int EPOS_DECEL[EPOS_NUM_MOTORS] = {50000, 20000, 20000, 20000}; static const long EPOS_TRANS_MIN = -320000; static const long EPOS_TRANS_MAX = 320000; static const long EPOS_PITCH_MIN = -45000; static const long EPOS_PITCH_MAX = 45000; static const long EPOS_YAW_MIN = -45000; static const long EPOS_YAW_MAX = 45000; static const long EPOS_ROLL_MIN = -1381000; static const long EPOS_ROLL_MAX = 1381000; static const int EPOS_MOTOR_LIMITS[EPOS_NUM_MOTORS][2] = { {EPOS_TRANS_MIN, EPOS_TRANS_MAX}, {EPOS_PITCH_MIN, EPOS_PITCH_MAX}, {EPOS_YAW_MIN, EPOS_YAW_MAX}, {EPOS_ROLL_MIN, EPOS_ROLL_MAX} }; static const long EPOS_TRANS_RAD2QC = -8503937; static const long EPOS_PITCH_RAD2QC = 45837; static const long EPOS_YAW_RAD2QC = -45837; static const long EPOS_ROLL_RAD2QC = -45837; // *********************** // ****** LabJack ****** // *********************** // enum LABJACK_ERROR_CODES ---- use LJ_ERROR codes instead from LabJackUD.h enum LABJACK_EVENT_IDS { LABJACK_CONNECT_BEGIN = 0, LABJACK_CONNECT_FAILED, LABJACK_CONNECTED, LABJACK_INITIALIZE_BEGIN, LABJACK_INITIALIZE_FAILED, LABJACK_INITIALIZED, LABJACK_LOOP_STARTED, LABJACK_LOOP_STOPPED, LABJACK_EPOCH_SET, LABJACK_EPOCH_SET_FAILED, LABJACK_DISCONNECTED, LABJACK_DISCONNECT_FAILED }; // *********************** // ****** FrmGrab ****** // *********************** enum FRMGRAB_ERROR_CODES { FRMGRAB_SUCCESS = 0, // FRMGRAB_FAIL, FRMGRAB_CANT_MUTATE_WHILE_RUNNING }; enum FRMGRAB_EVENT_IDS { FRMGRAB_CONNECT_BEGIN = 0, FRMGRAB_CONNECT_FAILED, FRMGRAB_CONNECTED, FRMGRAB_INITIALIZE_BEGIN, FRMGRAB_INITIALIZE_FAILED, FRMGRAB_INITIALIZED, FRMGRAB_LOOP_STARTED, FRMGRAB_LOOP_STOPPED, FRMGRAB_LIVE_FEED_STARTED, FRMGRAB_LIVE_FEED_STOPPED, FRMGRAB_EPOCH_SET, FRMGRAB_EPOCH_SET_FAILED, FRMGRAB_DISCONNECTED, FRMGRAB_DISCONNECT_FAILED }; static const int FRMGRAB_IM_WIDTH = 1920; // 640; static const int FRMGRAB_IM_HEIGHT = 1080; // 480; static const int FRMGRAB_FPS = 60; // ************************** // ****** CONTROLLER ****** // ************************** #define PERIOD_FILTER_SIZE 150 static const double PITCH_WP = 7.3896; static const double PITCH_WY = 1.2693; static const double PITCH_BIAS = 0.2529; static const double PITCH_SUM = 8.9118; static const double YAW_WY = 5.9987; static const double YAW_WP = 0.3187; static const double YAW_BIAS = -0.1743; static const double YAW_SUM = 6.1431; enum CONTROLLER_ERROR_CODES { CONTROLLER_SUCCESS = 0, // CONTROLLER_FAIL, CONTROLLER_CANT_MUTATE_WHILE_RUNNING }; enum CONTROLLER_EVENT_IDS { CONTROLLER_INITIALIZE_BEGIN = 0, CONTROLLER_INITIALIZE_FAILED, CONTROLLER_INITIALIZED, CONTROLLER_LOOP_STARTED, CONTROLLER_LOOP_STOPPED, CONTROLLER_RESP_MODEL_INIT_BEGIN, CONTROLLER_RESP_MODEL_INITIALIZED, CONTROLLER_RESP_MODEL_INIT_FAILED, CONTROLLER_RESP_MODEL_STOPPED, CONTROLLER_RESETBB_SUCCESS, CONTROLLER_EPOCH_SET, CONTROLLER_EPOCH_SET_FAILED, CONTROLLER_RESET, CONTROLLER_RESET_FAILED, CONTROLLER_SWEEP_STARTED, CONTROLLER_SWEEP_ABORTED }; enum CONTROLLER_DATA_IDS { CONTROLLER_DXYZPSI = 0, // 4 values CONTROLLER_USER_XYZDXYZPSI, // 7 values CONTROLLER_CURR_PSY_GAMMA, // 2 values CONTROLLER_T_BB_CT_curTipPos, // 16 values CONTROLLER_CURR_TASK, // 4 values CONTROLLER_PERIOD, // 1 value CONTROLLER_BIRD4_MODEL_PARAMS, // 19 = 10 polar + 9 rect CONTROLLER_RESETBB, // 16 values CONTROLLER_MODES, // 6 values CONTROLLER_USANGLE, // 1 value CONTROLLER_SWEEP_START, // 4 values CONTROLLER_NEXT_SWEEP, CONTROLLER_SWEEP_CONVERGED }; enum CONTROLLER_SPACES { JOINT_SPACE = 0, CONFIG_SPACE, TASK_SPACE }; enum CONTROLLER_SPACE_VARIABLES { JOINT_SPACE_TRANS = 0, JOINT_SPACE_PITCH, JOINT_SPACE_YAW, JOINT_SPACE_ROLL, CONFIG_SPACE_ALPHA, CONFIG_SPACE_THETA, CONFIG_SPACE_GAMMA, CONFIG_SPACE_D, TASK_SPACE_X, TASK_SPACE_Y, TASK_SPACE_Z, TASK_SPACE_DEL_PSI }; // Mode flags enum COORD_FRAME_MODE { COORD_FRAME_WORLD = 0, COORD_FRAME_MOBILE }; enum TETHER_MODE { MODE_TETHETERED = 0, MODE_RELATIVE }; enum INST_TRACK_STATE { INST_TRACK_OFF = 0, INST_TRACK_ON }; enum INST_TRACK_MODE { INST_TRACK_POSITION = 0, INST_TRACK_IMAGER }; enum EKF_STATE { EKF_OFF = 0, EKF_ON }; enum IN_VIVO_MODE { IN_VIVO_OFF = 0, IN_VIVO_ON }; enum MODEL_PLOT_INDEX { RESP_MODEL_PLOT_BIRD4 = 0, RESP_MODEL_PLOT_CT }; enum SWEEP_MODES { SWEEP_INACTIVE = 0, SWEEP_WAIT_TO_CONVERGE, SWEEP_CONVERGED, SWEEP_CONVERGED_ACQUIRING, SWEEP_NEXT, SWEEP_DONE }; static const int CONTROLLER_LOOP_TIMER_MSEC = 1; // ************************* // ****** FILTERING ****** // ************************* #define FILTER_ORDER 50 // LPF filter order #define SAMPLE_DELTA_TIME 0.005992 //0.006667 // delta time b/w EM readings #define HEART_RATE 100 // animal heartrate #define N_HARMONICS 4 // number of Fourier decomp harmonics #define N_STATES N_HARMONICS*2 + 2 // number of states #define N_RECT N_STATES - 1 // NUM_STATES of Rectangular components #define N_POLAR N_STATES // NUM_STATES of Polar components #define N_SAMPLES 2750 // CYCLE_DATA_SIZE #define EDGE_EFFECT 35 // extent of edge effects #define N_FILTERED N_SAMPLES - 2*EDGE_EFFECT // Filtered data length #define BREATH_RATE 5.0 // respiration period (seconds) #define PEAK_THRESHOLD 0.80 // For peak detection // *********************** // ***** DATA LOGGER ***** // *********************** static const int DATALOG_NUM_FILES = 8; static const unsigned short DATALOG_EM_ID = 0; static const unsigned short DATALOG_ECG_ID = 1; static const unsigned short DATALOG_EPOS_ID = 2; static const unsigned short DATALOG_FrmGrab_ID = 3; static const unsigned short DATALOG_Log_ID = 4; static const unsigned short DATALOG_Error_ID = 5; static const unsigned short DATALOG_Note_ID = 6; static const unsigned short DATALOG_Control_ID = 7; static const unsigned short DATALOG_FILE_IDS[DATALOG_NUM_FILES] = {DATALOG_EM_ID, DATALOG_ECG_ID, DATALOG_EPOS_ID, DATALOG_FrmGrab_ID, DATALOG_Log_ID, DATALOG_Error_ID, DATALOG_Note_ID, DATALOG_Control_ID}; enum DATALOG_EVENT_IDS { DATALOG_INITIALIZE_BEGIN = 0, DATALOG_INITIALIZE_FAILED, DATALOG_INITIALIZED, DATALOG_FILE_OPENED, DATALOG_FILE_CLOSED, DATALOG_FOLDER_ERROR, DATALOG_FILE_ERROR, DATALOG_FILE_DATA_LOGGED, DATALOG_EM_FILE_OPENED, DATALOG_EM_FILE_CLOSED, DATALOG_EM_FILE_DATA_LOGGED, DATALOG_ECG_FILE_OPENED, DATALOG_ECG_FILE_CLOSED, DATALOG_ECG_FILE_DATA_LOGGED, DATALOG_EPOS_FILE_OPENED, DATALOG_EPOS_FILE_CLOSED, DATALOG_EPOS_FILE_DATA_LOGGED, DATALOG_FRMGRAB_FILE_OPENED, DATALOG_FRMGRAB_FILE_CLOSED, DATALOG_FRMGRAB_FILE_DATA_LOGGED, DATALOG_LOG_FILE_OPENED, DATALOG_LOG_FILE_CLOSED, DATALOG_LOG_FILE_DATA_LOGGED, DATALOG_ERROR_FILE_OPENED, DATALOG_ERROR_FILE_CLOSED, DATALOG_ERROR_FILE_DATA_LOGGED, DATALOG_NOTE_FILE_OPENED, DATALOG_NOTE_FILE_CLOSED, DATALOG_NOTE_FILE_DATA_LOGGED, DATALOG_CONTROL_FILE_OPENED, DATALOG_CONTROL_FILE_CLOSED, DATALOG_CONTROL_FILE_DATA_LOGGED, DATALOG_EPOCH_SET, DATALOG_EPOCH_SET_FAILED, DATALOG_LOGGING_STARTED, DATALOG_LOGGING_STOPPED, DATALOG_CLOSED }; // ************************ // ***** FRAME SERVER ***** // ************************ enum FRMSRVR_EVENT_IDS { FRMSRVR_STARTED = 0, FRMSRVR_START_FAILED, FRMSRVR_CLOSED, FRMSRVR_CLOSE_FAILED, FRMSRVR_NEW_CONNECTION, FRMSRVR_SOCKET_NOT_READABLE, FRMSRVR_FRAME_RECEIVED, FRMSRVR_EPOCH_SET, FRMSRVR_EPOCH_SET_FAILED }; // ************************ // ***** FRAME CLIENT ***** // ************************ enum FRMCLNT_EVENT_IDS { FRMCLNT_CONNECTED = 0, FRMCLNT_CONNECTION_FAILED, FRMCLNT_DISCONNECTED, FRMCLNT_DISCONNECTION_FAILED, FRMCLNT_SOCKET_NOT_WRITABLE, FRMCLNT_FRAME_SENT, FRMCLNT_EPOCH_SET, FRMCLNT_EPOCH_SET_FAILED, FRMCLNT_FIRST_FRAME_NOT_RECEIVED }; // ************************* // ***** VOLUME SERVER ***** // ************************* enum VOLSRVR_EVENT_IDS { VOLSRVR_STARTED = 0, VOLSRVR_START_FAILED, VOLSRVR_CLOSED, VOLSRVR_CLOSE_FAILED, VOLSRVR_NEW_CONNECTION, VOLSRVR_SOCKET_NOT_READABLE, VOLSRVR_VOLUME_RECEIVED, VOLSRVR_EPOCH_SET, VOLSRVR_EPOCH_SET_FAILED }; // ************************* // ***** VOLUME CLIENT ***** // ************************* enum VOLCLNT_EVENT_IDS { VOLCLNT_CONNECTED = 0, VOLCLNT_CONNECTION_FAILED, VOLCLNT_DISCONNECTED, VOLCLNT_DISCONNECTION_FAILED, VOLCLNT_SOCKET_NOT_WRITABLE, VOLCLNT_VOLUME_SENT, VOLCLNT_EPOCH_SET, VOLCLNT_EPOCH_SET_FAILED, VOLCLNT_NOT_READY }; #endif // ICEBOT_DEFINITIONS // NEVER PASS EIGEN TYPES BY VALUE TO FUNCTIONS, ALWAYS PASS BY REFERENCE - BUT IT'S OK IF FUNCTIONS RETURN EIGEN TYPES BY VALUE // IF USING VECTOR/LIST/DEQUE/ETC TO STORE EIGEN FIXED TYPES (LIKE TRANSFORM), USE THE EIGEN::ALIGNED_ALLOCATOR IN DECLARING THE CONTAINER TYPE
14,708
C
25.266071
143
0.610076
adegirmenci/HBL-ICEbot/icebot_gui.cpp
#include "icebot_gui.h" #include "ui_icebot_gui.h" ICEbot_GUI::ICEbot_GUI(QWidget *parent) : QMainWindow(parent), ui(new Ui::ICEbot_GUI) { ui->setupUi(this); qDebug() << "Setting up GUI connections."; // EM Data to DataLogger connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)), ui->dataLogWidget->m_worker, SLOT(logEMdata(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD))); // LabJack Data to DataLogger connect(ui->labjackWidget->m_worker, SIGNAL(logData(qint64,std::vector<double>)), ui->dataLogWidget->m_worker, SLOT(logLabJackData(qint64,std::vector<double>))); // FrameGrabber Data to DataLogger connect(ui->frmGrabWidget->m_worker, SIGNAL(pleaseSaveImage(std::shared_ptr<Frame>)), ui->dataLogWidget->m_worker, SLOT(logFrmGrabImage(std::shared_ptr<Frame>))); // EPOS Data to DataLogger connect(ui->eposWidget->m_worker, SIGNAL(logData(QTime,int,int,long)), ui->dataLogWidget->m_worker, SLOT(logEPOSdata(QTime,int,int,long))); connect(ui->eposWidget->m_worker, SIGNAL(logData(QTime,int,std::vector<long>)), ui->dataLogWidget->m_worker, SLOT(logEPOSdata(QTime,int,std::vector<long>))); // Controller to DataLogger connect(ui->controlWidget->m_worker, SIGNAL(logData(QTime,int,int,std::vector<double>)), ui->dataLogWidget->m_worker, SLOT(logControllerData(QTime,int,int,std::vector<double>))); // Events to DataLogger connect(ui->emWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)), ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int))); connect(ui->eposWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)), ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int))); connect(ui->frmGrabWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)), ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int))); connect(ui->labjackWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)), ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int))); connect(ui->controlWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)), ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int))); // Errors to DataLogger connect(ui->emWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)), ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString))); connect(ui->eposWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)), ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString))); connect(ui->frmGrabWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)), ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString))); connect(ui->labjackWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)), ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString))); connect(ui->controlWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)), ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString))); // EM to SceneVizWidget // connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)), // ui->sceneVizWidget->m_modifier, SLOT(receiveEMreading(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD))); connect(ui->emWidget->m_worker, SIGNAL(sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)), ui->sceneVizWidget->m_modifier, SLOT(receiveEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>))); // EM to Controller //connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD)), // ui->controlWidget->m_worker, SLOT(receiveEMdata(QTime,int,DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD))); connect(ui->emWidget->m_worker, SIGNAL(sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)), ui->controlWidget->m_worker, SLOT(receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>))); // inter-process communication connect(ui->frmGrabWidget->m_worker, SIGNAL(imageAcquired(std::shared_ptr<Frame>)), ui->frameClientWidget->m_worker, SLOT(receiveFrame(std::shared_ptr<Frame>))); // connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)), // ui->frameClientWidget->m_worker, SLOT(receiveEMreading(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD))); // connect(ui->emWidget->m_worker, SIGNAL(sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)), // ui->frameClientWidget->m_worker, SLOT(receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>))); connect(ui->controlWidget->m_worker, SIGNAL(send_CT_toFrameClient(std::vector<double>,double)), ui->frameClientWidget->m_worker, SLOT(receive_T_CT(std::vector<double>,double))); connect(ui->controlWidget->m_worker, SIGNAL(toggleFrameClientContinuousStreaming(bool)), ui->frameClientWidget->m_worker, SLOT(toggleContinuousSteaming(bool))); connect(ui->labjackWidget->m_hrWidget, SIGNAL(reportPhase(qint64,double)), ui->frameClientWidget->m_worker, SLOT(receivePhase(qint64,double))); // Controller to EPOS connect(ui->controlWidget->m_worker, SIGNAL(setEPOSservoTargetPos(std::vector<long>,bool)), ui->eposWidget->m_worker, SLOT(setServoTargetPos(std::vector<long>,bool))); // Controller to frame grabber // FIXME: don't forget to uncomment this connect(ui->controlWidget, SIGNAL(startControlCycle()), ui->frmGrabWidget, SLOT(controlStarted())); connect(ui->controlWidget, SIGNAL(stopControlCycle()), ui->frmGrabWidget, SLOT(controlStopped())); // get current date time m_epoch = QDateTime::currentDateTime(); qDebug() << "Setting epoch."; // set date time of widgets ui->emWidget->m_worker->setEpoch(m_epoch); ui->frmGrabWidget->m_worker->setEpoch(m_epoch); ui->eposWidget->m_worker->setEpoch(m_epoch); ui->labjackWidget->m_worker->setEpoch(m_epoch); ui->frameClientWidget->m_worker->setEpoch(m_epoch); qDebug() << "GUI ready."; } ICEbot_GUI::~ICEbot_GUI() { delete ui; } void ICEbot_GUI::closeEvent(QCloseEvent *event) { event->accept(); qApp->quit(); }
6,405
C++
52.383333
128
0.693365
adegirmenci/HBL-ICEbot/icebot_gui.h
#ifndef ICEBOT_GUI_H #define ICEBOT_GUI_H #include <QMainWindow> #include <QDebug> #include <QCloseEvent> #include <QDateTime> namespace Ui { class ICEbot_GUI; } class ICEbot_GUI : public QMainWindow { Q_OBJECT public: explicit ICEbot_GUI(QWidget *parent = 0); ~ICEbot_GUI(); private slots: private: Ui::ICEbot_GUI *ui; void closeEvent(QCloseEvent *event); QDateTime m_epoch; }; #endif // ICEBOT_GUI_H
437
C
11.882353
45
0.681922
adegirmenci/HBL-ICEbot/qcustomplot.cpp
/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2015 Emanuel Eichhammer ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 22.12.15 ** ** Version: 1.3.2 ** ****************************************************************************/ #include "qcustomplot.h" //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPainter //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPainter \brief QPainter subclass used internally This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because it will call the base class implementations of the functions actually hidden by QCPPainter). */ /*! Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : QPainter(), mModes(pmDefault), mIsAntialiasing(false) { // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : QPainter(device), mModes(pmDefault), mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (isActive()) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif } QCPPainter::~QCPPainter() { } /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { QPainter::setPen(pen); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { QPainter::setPen(color); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { QPainter::setPen(penStyle); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { if (mIsAntialiasing || mModes.testFlag(pmVectorized)) QPainter::drawLine(line); else QPainter::drawLine(line.toLine()); } /*! Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for AA/Non-AA painting). */ void QCPPainter::setAntialiasing(bool enabled) { setRenderHint(QPainter::Antialiasing, enabled); if (mIsAntialiasing != enabled) { mIsAntialiasing = enabled; if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs { if (mIsAntialiasing) translate(0.5, 0.5); else translate(-0.5, -0.5); } } } /*! Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { mModes = modes; } /*! Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (result) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif return result; } /*! \overload Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { if (!enabled && mModes.testFlag(mode)) mModes &= ~mode; else if (enabled && !mModes.testFlag(mode)) mModes |= mode; } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see restore */ void QCPPainter::save() { mAntialiasingStack.push(mIsAntialiasing); QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see save */ void QCPPainter::restore() { if (!mAntialiasingStack.isEmpty()) mIsAntialiasing = mAntialiasingStack.pop(); else qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; QPainter::restore(); } /*! Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen overrides when the \ref pmNonCosmetic mode is set. */ void QCPPainter::makeNonCosmetic() { if (qFuzzyIsNull(pen().widthF())) { QPen p = pen(); p.setWidth(1); QPainter::setPen(p); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPScatterStyle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPScatterStyle \brief Represents the visual appearance of scatter points This class holds information about shape, color and size of scatter points. In plottables like QCPGraph it is used to store how scatter points shall be drawn. For example, \ref QCPGraph::setScatterStyle takes a QCPScatterStyle instance. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can be controlled with \ref setSize. \section QCPScatterStyle-defining Specifying a scatter style You can set all these configurations either by calling the respective functions on an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1 Or you can use one of the various constructors that take different parameter combinations, making it easy to specify a scatter style in a single call, like so: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2 \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref isPenDefined will return false. It leads to scatter points that inherit the pen from the plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes it very convenient to set up typical scatter settings: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref ScatterShape, where actually a QCPScatterStyle is expected. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref setCustomPath function or call the constructor that takes a painter path. The scatter shape will automatically be set to \ref ssCustom. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. Note that \ref setSize does not influence the appearance of the pixmap. */ /* start documentation of inline functions */ /*! \fn bool QCPScatterStyle::isNone() const Returns whether the scatter shape is \ref ssNone. \see setShape */ /*! \fn bool QCPScatterStyle::isPenDefined() const Returns whether a pen has been defined for this scatter style. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is left undefined, the scatter color will be inherited from the plottable that uses this scatter style. \see setPen */ /* end documentation of inline functions */ /*! Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle() : mSize(6), mShape(ssNone), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : mSize(size), mShape(shape), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, and size to \a size. No brush is defined, i.e. the scatter point will not be filled. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(Qt::NoBrush), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, the brush color to \a fill (with a solid pattern), and size to \a size. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(QBrush(fill)), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the brush to \a brush, and size to \a size. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n doesn't necessarily lead C++ to use this constructor in some cases, but might mistake <tt>Qt::NoPen</tt> for a QColor and use the \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) constructor instead (which will lead to an unexpected look of the scatter points). To prevent this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt> instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is wanted. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(shape), mPen(pen), mBrush(brush), mPenDefined(pen.style() != Qt::NoPen) { } /*! Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : mSize(5), mShape(ssPixmap), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPixmap(pixmap), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The scatter shape is set to \ref ssCustom. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly different meaning than for built-in scatter points: The custom path will be drawn scaled by a factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its natural size by default. To double the size of the path for example, set \a size to 12. */ QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(ssCustom), mPen(pen), mBrush(brush), mCustomPath(customPath), mPenDefined(pen.style() != Qt::NoPen) { } /*! Sets the size (pixel diameter) of the drawn scatter points to \a size. \see setShape */ void QCPScatterStyle::setSize(double size) { mSize = size; } /*! Sets the shape to \a shape. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref ssPixmap and \ref ssCustom, respectively. \see setSize */ void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) { mShape = shape; } /*! Sets the pen that will be used to draw scatter points to \a pen. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. \see setBrush */ void QCPScatterStyle::setPen(const QPen &pen) { mPenDefined = true; mPen = pen; } /*! Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. \see setPen */ void QCPScatterStyle::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the pixmap that will be drawn as scatter point to \a pixmap. Note that \ref setSize does not influence the appearance of the pixmap. The scatter shape is automatically set to \ref ssPixmap. */ void QCPScatterStyle::setPixmap(const QPixmap &pixmap) { setShape(ssPixmap); mPixmap = pixmap; } /*! Sets the custom shape that will be drawn as scatter point to \a customPath. The scatter shape is automatically set to \ref ssCustom. */ void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) { setShape(ssCustom); mCustomPath = customPath; } /*! Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. This function is used by plottables (or any class that wants to draw scatters) just before a number of scatters with this style shall be drawn with the \a painter. \see drawShape */ void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const { painter->setPen(mPenDefined ? mPen : defaultPen); painter->setBrush(mBrush); } /*! Draws the scatter shape with \a painter at position \a pos. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be called before scatter points are drawn with \ref drawShape. \see applyTo */ void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const { drawShape(painter, pos.x(), pos.y()); } /*! \overload Draws the scatter shape with \a painter at position \a x and \a y. */ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const { double w = mSize/2.0; switch (mShape) { case ssNone: break; case ssDot: { painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); break; } case ssCross: { painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); break; } case ssPlus: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); break; } case ssCircle: { painter->drawEllipse(QPointF(x , y), w, w); break; } case ssDisc: { QBrush b = painter->brush(); painter->setBrush(painter->pen().color()); painter->drawEllipse(QPointF(x , y), w, w); painter->setBrush(b); break; } case ssSquare: { painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssDiamond: { painter->drawLine(QLineF(x-w, y, x, y-w)); painter->drawLine(QLineF( x, y-w, x+w, y)); painter->drawLine(QLineF(x+w, y, x, y+w)); painter->drawLine(QLineF( x, y+w, x-w, y)); break; } case ssStar: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); break; } case ssTriangle: { painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w)); painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w)); painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w)); break; } case ssTriangleInverted: { painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w)); painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w)); painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w)); break; } case ssCrossSquare: { painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssPlusSquare: { painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssCrossCircle: { painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPlusCircle: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPeace: { painter->drawLine(QLineF(x, y-w, x, y+w)); painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPixmap: { painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap); break; } case ssCustom: { QTransform oldTransform = painter->transform(); painter->translate(x, y); painter->scale(mSize/6.0, mSize/6.0); painter->drawPath(mCustomPath); painter->setTransform(oldTransform); break; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayer \brief A layer that may contain objects, to control the rendering order The Layering system of QCustomPlot is the mechanism to control the rendering order of the elements inside the plot. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers bottom to top and successively draws the layerables of the layers. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base class from which almost all visible objects derive, like axes, grids, graphs, items, etc. Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in that order). The top two layers "axes" and "legend" contain the default axes and legend, so they will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of course, the layer affiliation of the individual objects can be changed as required (\ref QCPLayerable::setLayer). Controlling the ordering of objects is easy: Create a new layer in the position you want it to be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will be placed on the new layer automatically, due to the current layer setting. Alternatively you could have also ignored the current layer setting and just moved the objects with QCPLayerable::setLayer to the desired layer after creating them. It is also possible to move whole layers. For example, If you want the grid to be shown in front of all plottables/items on the "main" layer, just move it above "main" with QCustomPlot::moveLayer. The rendering order within one layer is simply by order of creation or insertion. The item created last (or added last to the layer), is drawn on top of all other objects on that layer. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below the deleted layer, see QCustomPlot::removeLayer. */ /* start documentation of inline functions */ /*! \fn QList<QCPLayerable*> QCPLayer::children() const Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. Layers with higher indices will be drawn above layers with lower indices. */ /* end documentation of inline functions */ /*! Creates a new QCPLayer instance. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : QObject(parentPlot), mParentPlot(parentPlot), mName(layerName), mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function mVisible(true) { // Note: no need to make sure layerName is unique, because layer // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { // If child layerables are still on this layer, detach them, so they don't try to reach back to this // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) while (!mChildren.isEmpty()) mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() if (mParentPlot->currentLayer() == this) qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; } /*! Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this layer will be invisible. This function doesn't change the visibility property of the layerables (\ref QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the visibility of the parent layer into account. */ void QCPLayer::setVisible(bool visible) { mVisible = visible; } /*! \internal Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will be prepended to the list, i.e. be drawn beneath the other layerables already in the list. This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { if (!mChildren.contains(layerable)) { if (prepend) mChildren.prepend(layerable); else mChildren.append(layerable); } else qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable); } /*! \internal Removes the \a layerable from the list of this layer. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see addChild */ void QCPLayer::removeChild(QCPLayerable *layerable) { if (!mChildren.removeOne(layerable)) qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayerable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayerable \brief Base class for all drawable objects This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. Note that a parent layerable is not necessarily also the QObject parent for memory management. Further, a layerable doesn't always have a parent layerable, so this function may return 0. A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be set manually by the user. */ /* end documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing setting may be specified individually, this function should set the antialiasing state of the most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the default antialiasing hint. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased, QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw calls the respective specialized applyAntialiasingHint function. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the respective layerable subclass.) Consequently it only has the normal QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to care about setting any antialiasing states, because the default antialiasing hint is already set on the painter when the \ref draw function is called, and that's the state it wants to draw the line with. */ /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. \see setLayer */ /* end documentation of signals */ /*! Creates a new QCPLayerable instance. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later time with \ref initializeParentPlot. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents are mainly used to control visibility in a hierarchy of layerables. This means a layerable is only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a plot does. It is not uncommon to set the QObject-parent to something else in the constructors of QCPLayerable subclasses, to guarantee a working destruction hierarchy. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : QObject(plot), mVisible(true), mParentPlot(plot), mParentLayerable(parentLayerable), mLayer(0), mAntialiased(true) { if (mParentPlot) { if (targetLayer.isEmpty()) setLayer(mParentPlot->currentLayer()); else if (!setLayer(targetLayer)) qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; } } QCPLayerable::~QCPLayerable() { if (mLayer) { mLayer->removeChild(this); mLayer = 0; } } /*! Sets the visibility of this layerable object. If an object is not visible, it will not be drawn on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not possible. */ void QCPLayerable::setVisible(bool on) { mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a layer. If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or interact/receive events). Returns true if the layer of this layerable was successfully changed to \a layer. */ bool QCPLayerable::setLayer(QCPLayer *layer) { return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { if (!mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (QCPLayer *layer = mParentPlot->layer(layerName)) { return setLayer(layer); } else { qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; return false; } } /*! Sets whether this object will be drawn antialiased or not. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { mAntialiased = enabled; } /*! Returns whether this layerable is visible, taking the visibility of the layerable parent and the visibility of the layer this layerable is on into account. This is the method that is consulted to decide whether a layerable shall be drawn or not. If this layerable has a direct layerable parent (usually set via hierarchies implemented in subclasses, like in the case of QCPLayoutElement), this function returns true only if this layerable has its visibility set to true and the parent layerable's \ref realVisibility returns true. If this layerable doesn't have a direct layerable parent, returns the state of this layerable's visibility. */ bool QCPLayerable::realVisibility() const { return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! This function is used to decide whether a click hits a layerable object or not. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the shortest pixel distance of this point to the object. If the object is either invisible or the distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the object is not selectable, -1.0 is returned, too. If the object is represented not by single lines but by an area like a \ref QCPItemText or the bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In these cases this function thus returns a constant value greater zero but still below the parent plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). The actual setting of the selection state is not done by this function. This is handled by the parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified via the selectEvent/deselectEvent methods. \a details is an optional output parameter. Every layerable subclass may place any information in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot decides on the basis of this selectTest call, that the object was successfully selected. The subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. You may pass 0 as \a details to indicate that you are not interested in those selection details. \see selectEvent, deselectEvent, QCustomPlot::setInteractions */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(pos) Q_UNUSED(onlySelectable) Q_UNUSED(details) return -1.0; } /*! \internal Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. Note that, unlike when passing a non-null parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { if (mParentPlot) { qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; return; } if (!parentPlot) qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; mParentPlot = parentPlot; parentPlotInitialized(mParentPlot); } /*! \internal Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { mParentLayerable = parentLayerable; } /*! \internal Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { if (layer && !mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (layer && layer->parentPlot() != mParentPlot) { qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; return false; } QCPLayer *oldLayer = mLayer; if (mLayer) mLayer->removeChild(this); mLayer = layer; if (mLayer) mLayer->addChild(this, prepend); if (mLayer != oldLayer) emit layerChanged(mLayer); return true; } /*! \internal Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is controlled via \a overrideElement. */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(false); else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(true); else painter->setAntialiasing(localAntialiased); } /*! \internal This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the parent plot is set at a later time. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. The default implementation does nothing. \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } /*! \internal Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { return QCP::iSelectOther; } /*! \internal Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { if (mParentPlot) return mParentPlot->viewport(); else return QRect(); } /*! \internal This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may use it to transport any kind of information from the selectTest to the possibly subsequent selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(additive) Q_UNUSED(details) Q_UNUSED(selectionStateChanged) } /*! \internal This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { Q_UNUSED(selectionStateChanged) } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPRange //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. contains a \a lower and \a upper double value and provides convenience input, output and modification functions. \see QCPAxis::setRange */ /*! Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller intervals would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a minimum magnitude of roughly 1e-308. \see validRange, maxRange */ const double QCPRange::minRange = 1e-280; /*! Maximum values (negative and positive) the range will accept in range-changing functions. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a maximum magnitude of roughly 1e308. Since the number of planck-volumes in the entire visible universe is only ~1e183, this should be enough. \see validRange, minRange */ const double QCPRange::maxRange = 1e250; /*! Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : lower(0), upper(0) { } /*! \overload Constructs a range with the specified \a lower and \a upper values. */ QCPRange::QCPRange(double lower, double upper) : lower(lower), upper(upper) { normalize(); } /*! Returns the size of the range, i.e. \a upper-\a lower */ double QCPRange::size() const { return upper-lower; } /*! Returns the center of the range, i.e. (\a upper+\a lower)*0.5 */ double QCPRange::center() const { return (upper+lower)*0.5; } /*! Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are swapped. */ void QCPRange::normalize() { if (lower > upper) qSwap(lower, upper); } /*! Expands this range such that \a otherRange is contained in the new range. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). If \a otherRange is already inside the current range, this function does nothing. \see expanded */ void QCPRange::expand(const QCPRange &otherRange) { if (lower > otherRange.lower) lower = otherRange.lower; if (upper < otherRange.upper) upper = otherRange.upper; } /*! Returns an expanded range that contains this and \a otherRange. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). \see expand */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { QCPRange result = *this; result.expand(otherRange); return result; } /*! Returns a sanitized version of the range. Sanitized means for logarithmic scales, that the range won't span the positive and negative sign domain, i.e. contain zero. Further \a lower will always be numerically smaller (or equal) to \a upper. If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the returned range will only contain the positive interval, with lower bound set to \a rangeFac or \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval is wider than the positive interval, this time by changing the \a upper bound. */ QCPRange QCPRange::sanitizedForLogScale() const { double rangeFac = 1e-3; QCPRange sanitizedRange(lower, upper); sanitizedRange.normalize(); // can't have range spanning negative and positive values in log plot, so change range to fix it //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { // case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { // case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { // find out whether negative or positive interval is wider to decide which sign domain will be chosen if (-sanitizedRange.lower > sanitizedRange.upper) { // negative is wider, do same as in case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else { // positive is wider, do same as in case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } } // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower return sanitizedRange; } /*! Returns a sanitized version of the range. Sanitized means for linear scales, that \a lower will always be numerically smaller (or equal) to \a upper. */ QCPRange QCPRange::sanitizedForLinScale() const { QCPRange sanitizedRange(lower, upper); sanitizedRange.normalize(); return sanitizedRange; } /*! Returns true when \a value lies within or exactly on the borders of the range. */ bool QCPRange::contains(double value) const { return value >= lower && value <= upper; } /*! Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(double lower, double upper) { return (lower > -maxRange && upper < maxRange && qAbs(lower-upper) > minRange && qAbs(lower-upper) < maxRange && !(lower > 0 && qIsInf(upper/lower)) && !(upper < 0 && qIsInf(lower/upper))); } /*! \overload Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(const QCPRange &range) { return (range.lower > -maxRange && range.upper < maxRange && qAbs(range.lower-range.upper) > minRange && qAbs(range.lower-range.upper) < maxRange && !(range.lower > 0 && qIsInf(range.upper/range.lower)) && !(range.upper < 0 && qIsInf(range.lower/range.upper))); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPMarginGroup //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. \section QCPMarginGroup-example Example First create a margin group: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 Then set this group on the layout element sides: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2 Here, we've used the first two axis rects of the plot and synchronized their left margins with each other and their right margins with each other. */ /* start documentation of inline functions */ /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const Returns a list of all layout elements that have their margin \a side associated with this margin group. */ /* end documentation of inline functions */ /*! Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot) { mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>()); mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>()); mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>()); mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>()); } QCPMarginGroup::~QCPMarginGroup() { clear(); } /*! Returns whether this margin group is empty. If this function returns true, no layout elements use this margin group to synchronize margin sides. */ bool QCPMarginGroup::isEmpty() const { QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren); while (it.hasNext()) { it.next(); if (!it.value().isEmpty()) return false; } return true; } /*! Clears this margin group. The synchronization of the margin sides that use this margin group is lifted and they will use their individual margin sizes again. */ void QCPMarginGroup::clear() { // make all children remove themselves from this margin group: QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren); while (it.hasNext()) { it.next(); const QList<QCPLayoutElement*> elements = it.value(); for (int i=elements.size()-1; i>=0; --i) elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild } } /*! \internal Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into account, too.) */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { // query all automatic margins of the layout elements in this margin group side and find maximum: int result = 0; const QList<QCPLayoutElement*> elements = mChildren.value(side); for (int i=0; i<elements.size(); ++i) { if (!elements.at(i)->autoMargins().testFlag(side)) continue; int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); if (m > result) result = m; } return result; } /*! \internal Adds \a element to the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].contains(element)) mChildren[side].append(element); else qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element); } /*! \internal Removes \a element from the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].removeOne(element)) qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutElement //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are invisible by themselves, because they don't draw anything. Their only purpose is to manage the position and size of other layout elements. This category of layout elements usually use QCPLayout as base class. Then there is the category of layout elements which actually draw something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does not necessarily mean that the latter category can't have child layout elements. QCPLegend for instance, actually derives from QCPLayoutGrid and the individual legend items are child layout elements in the grid layout. */ /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const Returns the inner rect of this layout element. The inner rect is the outer rect (\ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if \ref setAutoMargins is enabled) according to the space required by the labels of the axes. */ /*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event) This event is called, if the mouse was pressed while being inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event) This event is called, if the mouse is moved inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event) This event is called, if the mouse was previously pressed inside the outer rect of this layout element and is now released. */ /*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event) This event is called, if the mouse is double-clicked inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event) This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this layout element. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) mParentLayout(0), mMinimumSize(), mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), mRect(0, 0, 0, 0), mOuterRect(0, 0, 0, 0), mMargins(0, 0, 0, 0), mMinimumMargins(0, 0, 0, 0), mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any // unregister at layout: if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor mParentLayout->take(this); } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { if (mOuterRect != rect) { mOuterRect = rect; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { if (mMargins != margins) { mMargins = margins; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { if (mMinimumMargins != margins) { mMinimumMargins = margins; } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref setMarginGroup), to synchronize (align) it with other layout elements in the plot. \see setMinimumMargins, setMargins */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { mAutoMargins = sides; } /*! Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size accordingly, so violations of \a size should be exceptions. */ void QCPLayoutElement::setMinimumSize(const QSize &size) { if (mMinimumSize != size) { mMinimumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the minimum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMinimumSize(int width, int height) { setMinimumSize(QSize(width, height)); } /*! Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. */ void QCPLayoutElement::setMaximumSize(const QSize &size) { if (mMaximumSize != size) { mMaximumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the maximum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMaximumSize(int width, int height) { setMaximumSize(QSize(width, height)); } /*! Sets the margin \a group of the specified margin \a sides. Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. To unset the margin group of \a sides, set \a group to 0. Note that margin groups only work for margin sides that are set to automatic (\ref setAutoMargins). */ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) { QVector<QCP::MarginSide> sideVector; if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); for (int i=0; i<sideVector.size(); ++i) { QCP::MarginSide side = sideVector.at(i); if (marginGroup(side) != group) { QCPMarginGroup *oldGroup = marginGroup(side); if (oldGroup) // unregister at old group oldGroup->removeChild(side, this); if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there { mMarginGroups.remove(side); } else // setting to a new group { mMarginGroups[side] = group; group->addChild(side, this); } } } } /*! Updates the layout element and sub-elements. This function is automatically called before every replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { if (phase == upMargins) { if (mAutoMargins != QCP::msNone) { // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: QMargins newMargins = mMargins; QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; foreach (QCP::MarginSide side, allMarginSides) { if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically { if (mMarginGroups.contains(side)) QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group else QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly // apply minimum margin restrictions: if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); } } setMargins(newMargins); } } } /*! Returns the minimum size this layout element (the inner \ref rect) may be compressed to. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this function to determine the minimum allowed size of this layout element. (A manual minimum size is considered set if it is non-zero.) */ QSize QCPLayoutElement::minimumSizeHint() const { return mMinimumSize; } /*! Returns the maximum size this layout element (the inner \ref rect) may be expanded to. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this function to determine the maximum allowed size of this layout element. (A manual maximum size is considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) */ QSize QCPLayoutElement::maximumSizeHint() const { return mMaximumSize; } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have empty cells which yield 0 at the respective index.) */ QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const { Q_UNUSED(recursive) return QList<QCPLayoutElement*>(); } /*! Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. See \ref QCPLayerable::selectTest for a general explanation of this virtual method. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable) return -1; if (QRectF(mOuterRect).contains(pos)) { if (mParentPlot) return mParentPlot->selectionTolerance()*0.99; else { qDebug() << Q_FUNC_INFO << "parent plot not defined"; return -1; } } else return -1; } /*! \internal propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { foreach (QCPLayoutElement* el, elements(false)) { if (!el->parentPlot()) el->initializeParentPlot(parentPlot); } } /*! \internal Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayout //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayout \brief The abstract base class for layouts This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 Returns the number of elements/cells in the layout. \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check whether a cell is empty or not. \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 Removes the element with the given \a index from the layout and returns it. If the \a index is invalid or the cell with that index is empty, returns 0. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 Removes the specified \a element from the layout and returns true on success. If the \a element isn't in this layout, returns false. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see takeAt */ /* end documentation of pure virtual functions */ /*! Creates an instance of QCPLayout and sets default values. Note that since QCPLayout is an abstract base class, it can't be instantiated directly. */ QCPLayout::QCPLayout() { } /*! First calls the QCPLayoutElement::update base class implementation to update the margins on this layout. Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. Finally, \ref update is called on all child elements. */ void QCPLayout::update(UpdatePhase phase) { QCPLayoutElement::update(phase); // set child element rects according to layout: if (phase == upLayout) updateLayout(); // propagate update call to child elements: const int elCount = elementCount(); for (int i=0; i<elCount; ++i) { if (QCPLayoutElement *el = elementAt(i)) el->update(phase); } } /* inherits documentation from base class */ QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const { const int c = elementCount(); QList<QCPLayoutElement*> result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(c); #endif for (int i=0; i<c; ++i) result.append(elementAt(i)); if (recursive) { for (int i=0; i<c; ++i) { if (result.at(i)) result << result.at(i)->elements(recursive); } } return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ void QCPLayout::simplify() { } /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see remove, takeAt */ bool QCPLayout::removeAt(int index) { if (QCPLayoutElement *el = takeAt(index)) { delete el; return true; } else return false; } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { if (take(element)) { delete element; return true; } else return false; } /*! Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure all empty cells are collapsed. \see remove, removeAt */ void QCPLayout::clear() { for (int i=elementCount()-1; i>=0; --i) { if (elementAt(i)) removeAt(i); } simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, it may update itself and resize cells accordingly. */ void QCPLayout::sizeConstraintsChanged() const { if (QWidget *w = qobject_cast<QWidget*>(parent())) w->updateGeometry(); else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent())) l->sizeConstraintsChanged(); } /*! \internal Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. \ref getSectionSizes may help with the reimplementation of this function. \see update */ void QCPLayout::updateLayout() { } /*! \internal Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = this; el->setParentLayerable(this); el->setParent(this); if (!el->parentPlot()) el->initializeParentPlot(mParentPlot); } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = 0; el->setParentLayerable(0); el->setParent(mParentPlot); // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal This is a helper function for the implementation of \ref updateLayout in subclasses. It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. The QVector entries refer to the sections. Thus all QVectors must have the same size. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. The return value is a QVector containing the section sizes. */ QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const { if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) { qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; return QVector<int>(); } if (stretchFactors.isEmpty()) return QVector<int>(); int sectionCount = stretchFactors.size(); QVector<double> sectionSizes(sectionCount); // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): int minSizeSum = 0; for (int i=0; i<sectionCount; ++i) minSizeSum += minSizes.at(i); if (totalSize < minSizeSum) { // new stretch factors are minimum sizes and minimum sizes are set to zero: for (int i=0; i<sectionCount; ++i) { stretchFactors[i] = minSizes.at(i); minSizes[i] = 0; } } QList<int> minimumLockedSections; QList<int> unfinishedSections; for (int i=0; i<sectionCount; ++i) unfinishedSections.append(i); double freeSize = totalSize; int outerIterations = 0; while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens { ++outerIterations; int innerIterations = 0; while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens { ++innerIterations; // find section that hits its maximum next: int nextId = -1; double nextMax = 1e12; for (int i=0; i<unfinishedSections.size(); ++i) { int secId = unfinishedSections.at(i); double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId); if (hitsMaxAt < nextMax) { nextMax = hitsMaxAt; nextId = secId; } } // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section // actually hits its maximum, without exceeding the total size when we add up all sections) double stretchFactorSum = 0; for (int i=0; i<unfinishedSections.size(); ++i) stretchFactorSum += stretchFactors.at(unfinishedSections.at(i)); double nextMaxLimit = freeSize/stretchFactorSum; if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section { for (int i=0; i<unfinishedSections.size(); ++i) { sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i)); } unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes } else // next maximum isn't hit, just distribute rest of free space on remaining sections { for (int i=0; i<unfinishedSections.size(); ++i) sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections unfinishedSections.clear(); } } if (innerIterations == sectionCount*2) qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; // now check whether the resulting section sizes violate minimum restrictions: bool foundMinimumViolation = false; for (int i=0; i<sectionSizes.size(); ++i) { if (minimumLockedSections.contains(i)) continue; if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum { sectionSizes[i] = minSizes.at(i); // set it to minimum foundMinimumViolation = true; // make sure we repeat the whole optimization process minimumLockedSections.append(i); } } if (foundMinimumViolation) { freeSize = totalSize; for (int i=0; i<sectionCount; ++i) { if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool unfinishedSections.append(i); else freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round } // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum): for (int i=0; i<unfinishedSections.size(); ++i) sectionSizes[unfinishedSections.at(i)] = 0; } } if (outerIterations == sectionCount*2) qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; QVector<int> result(sectionCount); for (int i=0; i<sectionCount; ++i) result[i] = qRound(sectionSizes.at(i)); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutGrid \brief A layout that arranges child elements in a grid Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor, \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing). Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref hasElement, that element can be retrieved with \ref element. If rows and columns that only have empty cells shall be removed, call \ref simplify. Removal of elements is either done by just adding the element to a different layout or by using the QCPLayout interface \ref take or \ref remove. Row and column insertion can be performed with \ref insertRow and \ref insertColumn. */ /*! Creates an instance of QCPLayoutGrid and sets default values. */ QCPLayoutGrid::QCPLayoutGrid() : mColumnSpacing(5), mRowSpacing(5) { } QCPLayoutGrid::~QCPLayoutGrid() { // clear all child layout elements. This is important because only the specific layouts know how // to handle removing elements (clear calls virtual removeAt method to do that). clear(); } /*! Returns the element in the cell in \a row and \a column. Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. \see addElement, hasElement */ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const { if (row >= 0 && row < mElements.size()) { if (column >= 0 && column < mElements.first().size()) { if (QCPLayoutElement *result = mElements.at(row).at(column)) return result; else qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; return 0; } /*! Returns the number of rows in the layout. \see columnCount */ int QCPLayoutGrid::rowCount() const { return mElements.size(); } /*! Returns the number of columns in the layout. \see rowCount */ int QCPLayoutGrid::columnCount() const { if (mElements.size() > 0) return mElements.first().size(); else return 0; } /*! Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it is first removed from there. If \a row or \a column don't exist yet, the layout is expanded accordingly. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column didn't already have an element. \see element, hasElement, take, remove */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { if (element) { if (!hasElement(row, column)) { if (element->layout()) // remove from old layout first element->layout()->take(element); expandTo(row+1, column+1); mElements[row][column] = element; adoptElement(element); return true; } else qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; } else qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; return false; } /*! Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't empty. \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) return mElements.at(row).at(column); else return false; } /*! Sets the stretch \a factor of \a column. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { if (column >= 0 && column < columnCount()) { if (factor > 0) mColumnStretchFactors[column] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid column:" << column; } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors) { if (factors.size() == mColumnStretchFactors.size()) { mColumnStretchFactors = factors; for (int i=0; i<mColumnStretchFactors.size(); ++i) { if (mColumnStretchFactors.at(i) <= 0) { qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i); mColumnStretchFactors[i] = 1; } } } else qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors; } /*! Sets the stretch \a factor of \a row. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setRowStretchFactor(int row, double factor) { if (row >= 0 && row < rowCount()) { if (factor > 0) mRowStretchFactors[row] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid row:" << row; } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors) { if (factors.size() == mRowStretchFactors.size()) { mRowStretchFactors = factors; for (int i=0; i<mRowStretchFactors.size(); ++i) { if (mRowStretchFactors.at(i) <= 0) { qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i); mRowStretchFactors[i] = 1; } } } else qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors; } /*! Sets the gap that is left blank between columns to \a pixels. \see setRowSpacing */ void QCPLayoutGrid::setColumnSpacing(int pixels) { mColumnSpacing = pixels; } /*! Sets the gap that is left blank between rows to \a pixels. \see setColumnSpacing */ void QCPLayoutGrid::setRowSpacing(int pixels) { mRowSpacing = pixels; } /*! Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount, this function does nothing in that dimension. Newly created cells are empty, new rows and columns have the stretch factor 1. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the specified row and column, using this function. \see simplify */ void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount) { // add rows as necessary: while (rowCount() < newRowCount) { mElements.append(QList<QCPLayoutElement*>()); mRowStretchFactors.append(1); } // go through rows and expand columns as necessary: int newColCount = qMax(columnCount(), newColumnCount); for (int i=0; i<rowCount(); ++i) { while (mElements.at(i).size() < newColCount) mElements[i].append(0); } while (mColumnStretchFactors.size() < newColCount) mColumnStretchFactors.append(1); } /*! Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom). \see insertColumn */ void QCPLayoutGrid::insertRow(int newIndex) { if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell { expandTo(1, 1); return; } if (newIndex < 0) newIndex = 0; if (newIndex > rowCount()) newIndex = rowCount(); mRowStretchFactors.insert(newIndex, 1); QList<QCPLayoutElement*> newRow; for (int col=0; col<columnCount(); ++col) newRow.append((QCPLayoutElement*)0); mElements.insert(newIndex, newRow); } /*! Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right). \see insertRow */ void QCPLayoutGrid::insertColumn(int newIndex) { if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell { expandTo(1, 1); return; } if (newIndex < 0) newIndex = 0; if (newIndex > columnCount()) newIndex = columnCount(); mColumnStretchFactors.insert(newIndex, 1); for (int row=0; row<rowCount(); ++row) mElements[row].insert(newIndex, (QCPLayoutElement*)0); } /* inherits documentation from base class */ void QCPLayoutGrid::updateLayout() { QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); getMaximumRowColSizes(&maxColWidths, &maxRowHeights); int totalRowSpacing = (rowCount()-1) * mRowSpacing; int totalColSpacing = (columnCount()-1) * mColumnSpacing; QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); // go through cells and set rects accordingly: int yOffset = mRect.top(); for (int row=0; row<rowCount(); ++row) { if (row > 0) yOffset += rowHeights.at(row-1)+mRowSpacing; int xOffset = mRect.left(); for (int col=0; col<columnCount(); ++col) { if (col > 0) xOffset += colWidths.at(col-1)+mColumnSpacing; if (mElements.at(row).at(col)) mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); } } } /* inherits documentation from base class */ int QCPLayoutGrid::elementCount() const { return rowCount()*columnCount(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { if (index >= 0 && index < elementCount()) return mElements.at(index / columnCount()).at(index % columnCount()); else return 0; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements[index / columnCount()][index % columnCount()] = 0; return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { if (element) { for (int i=0; i<elementCount(); ++i) { if (elementAt(i) == element) { takeAt(i); return true; } } qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take"; } else qDebug() << Q_FUNC_INFO << "Can't take null element"; return false; } /* inherits documentation from base class */ QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const { QList<QCPLayoutElement*> result; int colC = columnCount(); int rowC = rowCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(colC*rowC); #endif for (int row=0; row<rowC; ++row) { for (int col=0; col<colC; ++col) { result.append(mElements.at(row).at(col)); } } if (recursive) { int c = result.size(); for (int i=0; i<c; ++i) { if (result.at(i)) result << result.at(i)->elements(recursive); } } return result; } /*! Simplifies the layout by collapsing rows and columns which only contain empty cells. */ void QCPLayoutGrid::simplify() { // remove rows with only empty cells: for (int row=rowCount()-1; row>=0; --row) { bool hasElements = false; for (int col=0; col<columnCount(); ++col) { if (mElements.at(row).at(col)) { hasElements = true; break; } } if (!hasElements) { mRowStretchFactors.removeAt(row); mElements.removeAt(row); if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) mColumnStretchFactors.clear(); } } // remove columns with only empty cells: for (int col=columnCount()-1; col>=0; --col) { bool hasElements = false; for (int row=0; row<rowCount(); ++row) { if (mElements.at(row).at(col)) { hasElements = true; break; } } if (!hasElements) { mColumnStretchFactors.removeAt(col); for (int row=0; row<rowCount(); ++row) mElements[row].removeAt(col); } } } /* inherits documentation from base class */ QSize QCPLayoutGrid::minimumSizeHint() const { QVector<int> minColWidths, minRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); QSize result(0, 0); for (int i=0; i<minColWidths.size(); ++i) result.rwidth() += minColWidths.at(i); for (int i=0; i<minRowHeights.size(); ++i) result.rheight() += minRowHeights.at(i); result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right(); result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom(); return result; } /* inherits documentation from base class */ QSize QCPLayoutGrid::maximumSizeHint() const { QVector<int> maxColWidths, maxRowHeights; getMaximumRowColSizes(&maxColWidths, &maxRowHeights); QSize result(0, 0); for (int i=0; i<maxColWidths.size(); ++i) result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX)); for (int i=0; i<maxRowHeights.size(); ++i) result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX)); result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right(); result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom(); return result; } /*! \internal Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights respectively. The minimum height of a row is the largest minimum height of any element in that row. The minimum width of a column is the largest minimum width of any element in that column. This is a helper function for \ref updateLayout. \see getMaximumRowColSizes */ void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const { *minColWidths = QVector<int>(columnCount(), 0); *minRowHeights = QVector<int>(rowCount(), 0); for (int row=0; row<rowCount(); ++row) { for (int col=0; col<columnCount(); ++col) { if (mElements.at(row).at(col)) { QSize minHint = mElements.at(row).at(col)->minimumSizeHint(); QSize min = mElements.at(row).at(col)->minimumSize(); QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); if (minColWidths->at(col) < final.width()) (*minColWidths)[col] = final.width(); if (minRowHeights->at(row) < final.height()) (*minRowHeights)[row] = final.height(); } } } } /*! \internal Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. The maximum height of a row is the smallest maximum height of any element in that row. The maximum width of a column is the smallest maximum width of any element in that column. This is a helper function for \ref updateLayout. \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const { *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX); *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX); for (int row=0; row<rowCount(); ++row) { for (int col=0; col<columnCount(); ++col) { if (mElements.at(row).at(col)) { QSize maxHint = mElements.at(row).at(col)->maximumSizeHint(); QSize max = mElements.at(row).at(col)->maximumSize(); QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); if (maxColWidths->at(col) > final.width()) (*maxColWidths)[col] = final.width(); if (maxRowHeights->at(row) > final.height()) (*maxRowHeights)[row] = final.height(); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutInset //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutInset \brief A layout that places child elements aligned to the border or arbitrarily positioned Elements are placed either aligned to the border or at arbitrary position in the area of the layout. Which placement applies is controlled with the \ref InsetPlacement (\ref setInsetPlacement). Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset placement will default to \ref ipBorderAligned and the element will be aligned according to the \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at arbitrary position and size, defined by \a rect. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. */ /* start documentation of inline functions */ /*! \fn virtual void QCPLayoutInset::simplify() The QCPInsetLayout does not need simplification since it can never have empty cells due to its linear index structure. This method does nothing. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutInset and sets default values. */ QCPLayoutInset::QCPLayoutInset() { } QCPLayoutInset::~QCPLayoutInset() { // clear all child layout elements. This is important because only the specific layouts know how // to handle removing elements (clear calls virtual removeAt method to do that). clear(); } /*! Returns the placement type of the element with the specified \a index. */ QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const { if (elementAt(index)) return mInsetPlacement.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return ipFree; } } /*! Returns the alignment of the element with the specified \a index. The alignment only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. */ Qt::Alignment QCPLayoutInset::insetAlignment(int index) const { if (elementAt(index)) return mInsetAlignment.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return 0; } } /*! Returns the rect of the element with the specified \a index. The rect only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. */ QRectF QCPLayoutInset::insetRect(int index) const { if (elementAt(index)) return mInsetRect.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return QRectF(); } } /*! Sets the inset placement type of the element with the specified \a index to \a placement. \see InsetPlacement */ void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) { if (elementAt(index)) mInsetPlacement[index] = placement; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function is used to set the alignment of the element with the specified \a index to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. */ void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) { if (elementAt(index)) mInsetAlignment[index] = alignment; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the position and size of the element with the specified \a index to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. Note that the minimum and maximum sizes of the embedded element (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. */ void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) { if (elementAt(index)) mInsetRect[index] = rect; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /* inherits documentation from base class */ void QCPLayoutInset::updateLayout() { for (int i=0; i<mElements.size(); ++i) { QRect insetRect; QSize finalMinSize, finalMaxSize; QSize minSizeHint = mElements.at(i)->minimumSizeHint(); QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); if (mInsetPlacement.at(i) == ipFree) { insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), rect().y()+rect().height()*mInsetRect.at(i).y(), rect().width()*mInsetRect.at(i).width(), rect().height()*mInsetRect.at(i).height()); if (insetRect.size().width() < finalMinSize.width()) insetRect.setWidth(finalMinSize.width()); if (insetRect.size().height() < finalMinSize.height()) insetRect.setHeight(finalMinSize.height()); if (insetRect.size().width() > finalMaxSize.width()) insetRect.setWidth(finalMaxSize.width()); if (insetRect.size().height() > finalMaxSize.height()) insetRect.setHeight(finalMaxSize.height()); } else if (mInsetPlacement.at(i) == ipBorderAligned) { insetRect.setSize(finalMinSize); Qt::Alignment al = mInsetAlignment.at(i); if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter } mElements.at(i)->setOuterRect(insetRect); } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { if (index >= 0 && index < mElements.size()) return mElements.at(index); else return 0; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements.removeAt(index); mInsetPlacement.removeAt(index); mInsetAlignment.removeAt(index); mInsetRect.removeAt(index); return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { if (element) { for (int i=0; i<elementCount(); ++i) { if (elementAt(i) == element) { takeAt(i); return true; } } qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take"; } else qDebug() << Q_FUNC_INFO << "Can't take null element"; return false; } /*! The inset layout is sensitive to events only at areas where its (visible) child elements are sensitive. If the selectTest method of any of the child elements returns a positive number for \a pos, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true, -1.0 is returned. See \ref QCPLayerable::selectTest for a general explanation of this virtual method. */ double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable) return -1; for (int i=0; i<mElements.size(); ++i) { // inset layout shall only return positive selectTest, if actually an inset object is at pos // else it would block the entire underlying QCPAxisRect with its surface. if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipBorderAligned); mInsetAlignment.append(alignment); mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add null element"; } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipFree); mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); mInsetRect.append(rect); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add null element"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLineEnding //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items \image html QCPLineEnding.png "The various ending styles currently supported" For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead */ /*! Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : mStyle(esNone), mWidth(8), mLength(10), mInverted(false) { } /*! Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : mStyle(style), mWidth(width), mLength(length), mInverted(inverted) { } /*! Sets the style of the ending decoration. */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. \see setLength */ void QCPLineEnding::setWidth(double width) { mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. \see setWidth */ void QCPLineEnding::setLength(double length) { mLength = length; } /*! Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point inward when \a inverted is set to true. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are affected by it, which can be used to control to which side the half bar points to. */ void QCPLineEnding::setInverted(bool inverted) { mInverted = inverted; } /*! \internal Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { switch (mStyle) { case esNone: return 0; case esFlatArrow: case esSpikeArrow: case esLineArrow: case esSkewedBar: return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length case esDisc: case esSquare: case esDiamond: case esBar: case esHalfBar: return mWidth*1.42; // items that only have a width -> width*sqrt(2) } return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { switch (mStyle) { case esNone: case esLineArrow: case esSkewedBar: case esBar: case esHalfBar: return 0; case esFlatArrow: return mLength; case esDisc: case esSquare: case esDiamond: return mWidth*0.5; case esSpikeArrow: return mLength*0.8; } return 0; } /*! \internal Draws the line ending with the specified \a painter at the position \a pos. The direction of the line ending is controlled with \a dir. */ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const { if (mStyle == esNone) return; QVector2D lengthVec(dir.normalized()); if (lengthVec.isNull()) lengthVec = QVector2D(1, 0); QVector2D widthVec(-lengthVec.y(), lengthVec.x()); lengthVec *= (float)(mLength*(mInverted ? -1 : 1)); widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1)); QPen penBackup = painter->pen(); QBrush brushBackup = painter->brush(); QPen miterPen = penBackup; miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey QBrush brush(painter->pen().color(), Qt::SolidPattern); switch (mStyle) { case esNone: break; case esFlatArrow: { QPointF points[3] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 3); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esSpikeArrow: { QPointF points[4] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec*0.8f).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esLineArrow: { QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), pos.toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->drawPolyline(points, 3); painter->setPen(penBackup); break; } case esDisc: { painter->setBrush(brush); painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); painter->setBrush(brushBackup); break; } case esSquare: { QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), (pos-widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esDiamond: { QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); QPointF points[4] = {(pos-widthVecPerp).toPointF(), (pos-widthVec).toPointF(), (pos+widthVecPerp).toPointF(), (pos+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esBar: { painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); break; } case esHalfBar: { painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); break; } case esSkewedBar: { if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) { // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(), (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF()); } else { // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(), (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF()); } break; } } } /*! \internal \overload Draws the line ending. The direction is controlled with the \a angle parameter in radians. */ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const { draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This described situation is the default setup, see the QCPLayer documentation. */ /*! Creates a QCPGrid instance and sets default values. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), mParentAxis(parentAxis) { // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called setParent(parentAxis); setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); setSubGridVisible(false); setAntialiased(false); setAntialiasedSubGrid(false); setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { mSubGridVisible = visible; } /*! Sets whether sub grid lines are drawn antialiased. */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { mAntialiasedSubGrid = enabled; } /*! Sets whether zero lines are drawn antialiased. */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { mAntialiasedZeroLine = enabled; } /*! Sets the pen with which (major) grid lines are drawn. */ void QCPGrid::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen with which sub grid lines are drawn. */ void QCPGrid::setSubGridPen(const QPen &pen) { mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { mZeroLinePen = pen; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } if (mSubGridVisible) drawSubGridLines(painter); drawGridLines(painter); } /*! \internal Draws the main grid lines and possibly a zero line with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } int lowTick = mParentAxis->mLowestVisibleTick; int highTick = mParentAxis->mHighestVisibleTick; double t; // helper variable, result of coordinate-to-pixel transforms if (mParentAxis->orientation() == Qt::Horizontal) { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero for (int i=lowTick; i <= highTick; ++i) { if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=lowTick; i <= highTick; ++i) { if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero for (int i=lowTick; i <= highTick; ++i) { if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=lowTick; i <= highTick; ++i) { if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } /*! \internal Draws the sub grid lines with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); double t; // helper variable, result of coordinate-to-pixel transforms painter->setPen(mSubGridPen); if (mParentAxis->orientation() == Qt::Horizontal) { for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i) { t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i) { t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxis //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxis \brief Manages a single axis inside a QCustomPlot. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png <center>Naming convention of axis parts</center> \n \image html AxisRectSpacingOverview.png <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line on the left represents the QCustomPlot widget border.</center> */ /* start of documentation of inline functions */ /*! \fn Qt::Orientation QCPAxis::orientation() const Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced from the axis type (left, top, right or bottom). \see orientation(AxisType type) */ /*! \fn QCPGrid *QCPAxis::grid() const Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) Returns the orientation of the specified axis type \see orientation() */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCPAxis::ticksRequest() This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick labels for a replot. Modifying the tick positions can be done with \ref setTickVector. If you also want to control the tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref setTickVectorLabels. If you only want static ticks you probably don't need this signal, since you can just set the tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this signal and set the vector/vectors there. */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper range shouldn't go beyond certain values. For example, the following slot would limit the x axis to only positive ranges: \code if (newRange.lower < 0) plot->xAxis->setRange(0, newRange.size()); \endcode */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ /* end of documentation of signals */ /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : QCPLayerable(parent->parentPlot(), QString(), parent), // axis base: mAxisType(type), mAxisRect(parent), mPadding(5), mOrientation(orientation(type)), mSelectableParts(spAxis | spTickLabels | spAxisLabel), mSelectedParts(spNone), mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedBasePen(QPen(Qt::blue, 2)), // axis label: mLabel(), mLabelFont(mParentPlot->font()), mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), mLabelColor(Qt::black), mSelectedLabelColor(Qt::blue), // tick labels: mTickLabels(true), mAutoTickLabels(true), mTickLabelType(ltNumber), mTickLabelFont(mParentPlot->font()), mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), mTickLabelColor(Qt::black), mSelectedTickLabelColor(Qt::blue), mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")), mDateTimeSpec(Qt::LocalTime), mNumberPrecision(6), mNumberFormatChar('g'), mNumberBeautifulPowers(true), // ticks and subticks: mTicks(true), mTickStep(1), mSubTickCount(4), mAutoTickCount(6), mAutoTicks(true), mAutoTickStep(true), mAutoSubTicks(true), mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedTickPen(QPen(Qt::blue, 2)), mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedSubTickPen(QPen(Qt::blue, 2)), // scale and range: mRange(0, 5), mRangeReversed(false), mScaleType(stLinear), mScaleLogBase(10), mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)), // internal members: mGrid(new QCPGrid(this)), mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), mLowestVisibleTick(0), mHighestVisibleTick(-1), mCachedMarginValid(false), mCachedMargin(0) { setParent(parent); mGrid->setVisible(false); setAntialiased(false); setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again if (type == atTop) { setTickLabelPadding(3); setLabelPadding(6); } else if (type == atRight) { setTickLabelPadding(7); setLabelPadding(12); } else if (type == atBottom) { setTickLabelPadding(3); setLabelPadding(3); } else if (type == atLeft) { setTickLabelPadding(5); setLabelPadding(10); } } QCPAxis::~QCPAxis() { delete mAxisPainter; delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QCPAxis::LabelSide QCPAxis::tickLabelSide() const { return mAxisPainter->tickLabelSide; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { QString result; result.append(mNumberFormatChar); if (mNumberBeautifulPowers) { result.append(QLatin1Char('b')); if (mAxisPainter->numberMultiplyCross) result.append(QLatin1Char('c')); } return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { return mAxisPainter->upperEnding; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major ticks, consider choosing a logarithm base of 100, 1000 or even higher. If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" part). To only display the decimal power, set the number precision to zero with \ref setNumberPrecision. */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { if (mScaleType != type) { mScaleType = type; if (mScaleType == stLogarithmic) setRange(mRange.sanitizedForLogScale()); mCachedMarginValid = false; emit scaleTypeChanged(mScaleType); } } /*! If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major ticks, consider choosing \a base 100, 1000 or even higher. */ void QCPAxis::setScaleLogBase(double base) { if (base > 1) { mScaleLogBase = base; mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation mCachedMarginValid = false; } else qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; } /*! Sets the range of the axis. This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { if (range.lower == mRange.lower && range.upper == mRange.upper) return; if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; if (mScaleType == stLogarithmic) { mRange = range.sanitizedForLogScale(); } else { mRange = range.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part, independent of the \ref setSelectableParts setting. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { if (mSelectedParts != selected) { mSelectedParts = selected; emit selectionChanged(mSelectedParts); } } /*! \overload Sets the lower and upper bound of the axis range. To invert the direction of an axis, use \ref setRangeReversed. There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { if (lower == mRange.lower && upper == mRange.upper) return; if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! \overload Sets the range of the axis. The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, or center of the range to be aligned with \a position. Any other values of \a alignment will default to Qt::AlignCenter. */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { if (alignment == Qt::AlignLeft) setRange(position, position+size); else if (alignment == Qt::AlignRight) setRange(position-size, position); else // alignment == Qt::AlignCenter setRange(position-size/2.0, position+size/2.0); } /*! Sets the lower bound of the axis range. The upper bound is not changed. \see setRange */ void QCPAxis::setRangeLower(double lower) { if (mRange.lower == lower) return; QCPRange oldRange = mRange; mRange.lower = lower; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets the upper bound of the axis range. The lower bound is not changed. \see setRange */ void QCPAxis::setRangeUpper(double upper) { if (mRange.upper == upper) return; QCPRange oldRange = mRange; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the direction of increasing values is inverted. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ void QCPAxis::setRangeReversed(bool reversed) { if (mRangeReversed != reversed) { mRangeReversed = reversed; mCachedMarginValid = false; } } /*! Sets whether the tick positions should be calculated automatically (either from an automatically generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep). If \a on is set to false, you must provide the tick positions manually via \ref setTickVector. For these manual ticks you may let QCPAxis generate the appropriate labels automatically by leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels manually, set \ref setAutoTickLabels to false and provide the label strings with \ref setTickVectorLabels. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the vectors in a slot connected to the \ref ticksRequest signal. \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep */ void QCPAxis::setAutoTicks(bool on) { if (mAutoTicks != on) { mAutoTicks = on; mCachedMarginValid = false; } } /*! When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be generated in the visible range, approximately. It's not guaranteed that this number of ticks is met exactly, but approximately within a tolerance of about two. Only values greater than zero are accepted as \a approximateCount. \see setAutoTickStep, setAutoTicks, setAutoSubTicks */ void QCPAxis::setAutoTickCount(int approximateCount) { if (mAutoTickCount != approximateCount) { if (approximateCount > 0) { mAutoTickCount = approximateCount; mCachedMarginValid = false; } else qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; } } /*! Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat. If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This is usually used in a combination with \ref setAutoTicks set to false for complete control over tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi" etc. as tick labels. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the vectors in a slot connected to the \ref ticksRequest signal. \see setAutoTicks */ void QCPAxis::setAutoTickLabels(bool on) { if (mAutoTickLabels != on) { mAutoTickLabels = on; mCachedMarginValid = false; } } /*! Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human readable plots. The number of ticks the algorithm aims for within the visible range can be specified with \ref setAutoTickCount. If \a on is set to false, you may set the tick step manually with \ref setTickStep. \see setAutoTicks, setAutoSubTicks, setAutoTickCount */ void QCPAxis::setAutoTickStep(bool on) { if (mAutoTickStep != on) { mAutoTickStep = on; mCachedMarginValid = false; } } /*! Sets whether the number of sub ticks in one tick interval is determined automatically. This works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is always the case. When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually. \see setAutoTickCount, setAutoTicks, setAutoTickStep */ void QCPAxis::setAutoSubTicks(bool on) { if (mAutoSubTicks != on) { mAutoSubTicks = on; mCachedMarginValid = false; } } /*! Sets whether tick marks are displayed. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve that, see \ref setTickLabels. */ void QCPAxis::setTicks(bool show) { if (mTicks != show) { mTicks = show; mCachedMarginValid = false; } } /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ void QCPAxis::setTickLabels(bool show) { if (mTickLabels != show) { mTickLabels = show; mCachedMarginValid = false; } } /*! Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ void QCPAxis::setTickLabelPadding(int padding) { if (mAxisPainter->tickLabelPadding != padding) { mAxisPainter->tickLabelPadding = padding; mCachedMarginValid = false; } } /*! Sets whether the tick labels display numbers or dates/times. If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply. If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply. In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in milliseconds. Divide its return value by 1000.0 to get a value with the format needed for date/time plotting, with a resolution of one millisecond. Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C. (represented by a negative number), unlike the toTime_t function, which works with unsigned integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes. \see setTickLabels */ void QCPAxis::setTickLabelType(LabelType type) { if (mTickLabelType != type) { mTickLabelType = type; mCachedMarginValid = false; } } /*! Sets the font of the tick labels. \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { if (font != mTickLabelFont) { mTickLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the tick labels. \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { if (color != mTickLabelColor) { mTickLabelColor = color; mCachedMarginValid = false; } } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) { mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); mCachedMarginValid = false; } } /*! Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels appear on the inside are additionally clipped to the axis rect. */ void QCPAxis::setTickLabelSide(LabelSide side) { mAxisPainter->tickLabelSide = side; mCachedMarginValid = false; } /*! Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. for details about the \a format string, see the documentation of QDateTime::toString(). Newlines can be inserted with "\n". \see setDateTimeSpec */ void QCPAxis::setDateTimeFormat(const QString &format) { if (mDateTimeFormat != format) { mDateTimeFormat = format; mCachedMarginValid = false; } } /*! Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref ltDateTime. The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However, if the date time values passed to QCustomPlot are given in the UTC spec, set \a timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels. \see setDateTimeFormat */ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) { mDateTimeSpec = timeSpec; } /*! Sets the number format for the numbers drawn as tick labels (if tick label type is \ref ltNumber). This \a formatCode is an extended version of the format code used e.g. by QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" section in the detailed description of the QString class. \a formatCode is a string of one, two or three characters. The first character is identical to the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, whichever is shorter. The second and third characters are optional and specific to QCustomPlot:\n If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b' option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" part). To only display the decimal power, set the number precision to zero with \ref setNumberPrecision. Examples for \a formatCode: \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, normal scientific format is used \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with beautifully typeset decimal powers and a dot as multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format code will not be changed. */ void QCPAxis::setNumberFormat(const QString &formatCode) { if (formatCode.isEmpty()) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } mCachedMarginValid = false; // interpret first char as number format char: QString allowedFormatChars(QLatin1String("eEfgG")); if (allowedFormatChars.contains(formatCode.at(0))) { mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if (formatCode.length() < 2) { mNumberBeautifulPowers = false; mAxisPainter->numberMultiplyCross = false; return; } // interpret second char as indicator for beautiful decimal powers: if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { mNumberBeautifulPowers = true; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; return; } if (formatCode.length() < 3) { mAxisPainter->numberMultiplyCross = false; return; } // interpret third char as indicator for dot or cross multiplication symbol: if (formatCode.at(2) == QLatin1Char('c')) { mAxisPainter->numberMultiplyCross = true; } else if (formatCode.at(2) == QLatin1Char('d')) { mAxisPainter->numberMultiplyCross = false; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; return; } } /*! Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) for details. The effect of precisions are most notably for number Formats starting with 'e', see \ref setNumberFormat If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10 [superscript] n", set \a precision to zero. */ void QCPAxis::setNumberPrecision(int precision) { if (mNumberPrecision != precision) { mNumberPrecision = precision; mCachedMarginValid = false; } } /*! If \ref setAutoTickStep is set to false, use this function to set the tick step manually. The tick step is the interval between (major) ticks, in plot coordinates. \see setSubTickCount */ void QCPAxis::setTickStep(double step) { if (mTickStep != step) { mTickStep = step; mCachedMarginValid = false; } } /*! If you want full control over what ticks (and possibly labels) the axes show, this function is used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else the provided tick vector will be overwritten with automatically generated tick coordinates upon replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels. \a vec is a vector containing the positions of the ticks, in plot coordinates. \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this. \see setTickVectorLabels */ void QCPAxis::setTickVector(const QVector<double> &vec) { // don't check whether mTickVector != vec here, because it takes longer than we would save mTickVector = vec; mCachedMarginValid = false; } /*! If you want full control over what ticks and labels the axes show, this function is used to set a number of QStrings that will be displayed at the tick positions which you need to provide with \ref setTickVector. These two vectors should have the same size. (Note that you need to disable \ref setAutoTicks and \ref setAutoTickLabels first.) \a vec is a vector containing the labels of the ticks. The entries correspond to the respective indices in the tick vector, passed via \ref setTickVector. \see setTickVector */ void QCPAxis::setTickVectorLabels(const QVector<QString> &vec) { // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save mTickVectorLabels = vec; mCachedMarginValid = false; } /*! Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { setTickLengthIn(inside); setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { if (mAxisPainter->tickLengthIn != inside) { mAxisPainter->tickLengthIn = inside; } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { if (mAxisPainter->tickLengthOut != outside) { mAxisPainter->tickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, divides the tick intervals in four sub intervals. By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is always the case. If you want to disable automatic sub tick count and use this function to set the count manually, see \ref setAutoSubTicks. */ void QCPAxis::setSubTickCount(int count) { mSubTickCount = count; } /*! Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { setSubTickLengthIn(inside); setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { if (mAxisPainter->subTickLengthIn != inside) { mAxisPainter->subTickLengthIn = inside; } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { if (mAxisPainter->subTickLengthOut != outside) { mAxisPainter->subTickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the pen, the axis base line is drawn with. \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { mSubTickPen = pen; } /*! Sets the font of the axis label. \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { if (mLabelFont != font) { mLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the axis label. \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { mLabelColor = color; } /*! Sets the text of the axis label that will be shown below/above or next to the axis, depending on its orientation. To disable axis labels, pass an empty string as \a str. */ void QCPAxis::setLabel(const QString &str) { if (mLabel != str) { mLabel = str; mCachedMarginValid = false; } } /*! Sets the distance between the tick labels and the axis label. \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { if (mAxisPainter->labelPadding != padding) { mAxisPainter->labelPadding = padding; mCachedMarginValid = false; } } /*! Sets the padding of the axis. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { if (mPadding != padding) { mPadding = padding; mCachedMarginValid = false; } } /*! Sets the offset the axis has to its axis rect side. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate positions. */ void QCPAxis::setOffset(int offset) { mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { if (font != mSelectedTickLabelFont) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } } /*! Sets the font that is used for the axis label when it is selected. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { mSelectedLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { if (color != mSelectedTickLabelColor) { mSelectedTickLabelColor = color; } } /*! Sets the color that is used for the axis label when it is selected. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { mRange.lower += diff; mRange.upper += diff; } else // mScaleType == stLogarithmic { mRange.lower *= diff; mRange.upper *= diff; } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates around 1.0 will have moved symmetrically closer to 1.0). */ void QCPAxis::scaleRange(double factor, double center) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { QCPRange newRange; newRange.lower = (mRange.lower-center)*factor + center; newRange.upper = (mRange.upper-center)*factor + center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLinScale(); } else // mScaleType == stLogarithmic { if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range { QCPRange newRange; newRange.lower = qPow(mRange.lower/center, factor)*center; newRange.upper = qPow(mRange.upper/center, factor)*center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLogScale(); } else qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will be done around the center of the current axis range. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the axis rect has. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent will follow. */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { int otherPixelSize, ownPixelSize; if (otherAxis->orientation() == Qt::Horizontal) otherPixelSize = otherAxis->axisRect()->width(); else otherPixelSize = otherAxis->axisRect()->height(); if (orientation() == Qt::Horizontal) ownPixelSize = axisRect()->width(); else ownPixelSize = axisRect()->height(); double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { QList<QCPAbstractPlottable*> p = plottables(); QCPRange newRange; bool haveRange = false; for (int i=0; i<p.size(); ++i) { if (!p.at(i)->realVisibility() && onlyVisiblePlottables) continue; QCPRange plottableRange; bool currentFoundRange; QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; if (mScaleType == stLogarithmic) signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); if (p.at(i)->keyAxis() == this) plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); else plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); if (currentFoundRange) { if (!haveRange) newRange = plottableRange; else newRange.expand(plottableRange); haveRange = true; } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mScaleType == stLinear) { newRange.lower = center-mRange.size()/2.0; newRange.upper = center+mRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mRange.upper/mRange.lower); newRange.upper = center*qSqrt(mRange.upper/mRange.lower); } } setRange(newRange); } } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ double QCPAxis::pixelToCoord(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; else return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; else return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; else return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; else return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; } } } /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ double QCPAxis::coordToPixel(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); else return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); } else // mScaleType == stLogarithmic { if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; else { if (!mRangeReversed) return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); else return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); } } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); else return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); } else // mScaleType == stLogarithmic { if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; else { if (!mRangeReversed) return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); else return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); } } } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. If the axis is not visible (\ref setVisible), this function always returns \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { if (!mVisible) return spNone; if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; else return spNone; } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; SelectablePart part = getPartAt(pos); if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; if (details) details->setValue(part); return mParentPlot->selectionTolerance()*0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. If you are only interested in plottables of type QCPGraph, see \ref graphs. \see graphs, items */ QList<QCPAbstractPlottable*> QCPAxis::plottables() const { QList<QCPAbstractPlottable*> result; if (!mParentPlot) return result; for (int i=0; i<mParentPlot->mPlottables.size(); ++i) { if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) result.append(mParentPlot->mPlottables.at(i)); } return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. \see plottables, items */ QList<QCPGraph*> QCPAxis::graphs() const { QList<QCPGraph*> result; if (!mParentPlot) return result; for (int i=0; i<mParentPlot->mGraphs.size(); ++i) { if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) result.append(mParentPlot->mGraphs.at(i)); } return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. \see plottables, graphs */ QList<QCPAbstractItem*> QCPAxis::items() const { QList<QCPAbstractItem*> result; if (!mParentPlot) return result; for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId) { QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions(); for (int posId=0; posId<positions.size(); ++posId) { if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this) { result.append(mParentPlot->mItems.at(itemId)); break; } } } return result; } /*! Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { switch (side) { case QCP::msLeft: return atLeft; case QCP::msRight: return atRight; case QCP::msTop: return atTop; case QCP::msBottom: return atBottom; default: break; } qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; return atLeft; } /*! Returns the axis type that describes the opposite axis of an axis with the specified \a type. */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { switch (type) { case atLeft: return atRight; break; case atRight: return atLeft; break; case atBottom: return atTop; break; case atTop: return atBottom; break; default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; } } /*! \internal This function is called to prepare the tick vector, sub tick vector and tick label vector. If \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to provide external tick positions. Then the sub tick vectors and tick label vectors are created. */ void QCPAxis::setupTickVectors() { if (!mParentPlot) return; if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself if (mAutoTicks) { generateAutoTicks(); } else { emit ticksRequest(); } visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); if (mTickVector.isEmpty()) { mSubTickVector.clear(); return; } // generate subticks between ticks: mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); if (mSubTickCount > 0) { double subTickStep = 0; double subTickPosition = 0; int subTickIndex = 0; bool done = false; int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick; int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick; for (int i=lowTick+1; i<=highTick; ++i) { subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1); for (int k=1; k<=mSubTickCount; ++k) { subTickPosition = mTickVector.at(i-1) + k*subTickStep; if (subTickPosition < mRange.lower) continue; if (subTickPosition > mRange.upper) { done = true; break; } mSubTickVector[subTickIndex] = subTickPosition; subTickIndex++; } if (done) break; } mSubTickVector.resize(subTickIndex); } // generate tick labels according to tick positions: if (mAutoTickLabels) { int vecsize = mTickVector.size(); mTickVectorLabels.resize(vecsize); if (mTickLabelType == ltNumber) { for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar.toLatin1(), mNumberPrecision); } else if (mTickLabelType == ltDateTime) { for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) { #if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz") mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat); #else mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat); #endif } } } else // mAutoTickLabels == false { if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels { emit ticksRequest(); } // make sure provided tick label vector has correct (minimal) length: if (mTickVectorLabels.size() < mTickVector.size()) mTickVectorLabels.resize(mTickVector.size()); } } /*! \internal If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to generate reasonable tick positions (and subtick count). The algorithm tries to create approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount). If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every power of the current logarithm base, set via \ref setScaleLogBase. */ void QCPAxis::generateAutoTicks() { if (mScaleType == stLinear) { if (mAutoTickStep) { // Generate tick positions according to linear scaling: mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. double tickStepMantissa = mTickStep/magnitudeFactor; if (tickStepMantissa < 5) { // round digit after decimal point to 0.5 mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor; } else { // round to first digit in multiples of 2 mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; } } if (mAutoSubTicks) mSubTickCount = calculateAutoSubTickCount(mTickStep); // Generate tick positions according to mTickStep: qint64 firstStep = floor(mRange.lower/mTickStep); // do not use qFloor here, or we'll lose 64 bit precision qint64 lastStep = ceil(mRange.upper/mTickStep); // do not use qCeil here, or we'll lose 64 bit precision int tickcount = lastStep-firstStep+1; if (tickcount < 0) tickcount = 0; mTickVector.resize(tickcount); for (int i=0; i<tickcount; ++i) mTickVector[i] = (firstStep+i)*mTickStep; } else // mScaleType == stLogarithmic { // Generate tick positions according to logbase scaling: if (mRange.lower > 0 && mRange.upper > 0) // positive range { double lowerMag = basePow(qFloor(baseLog(mRange.lower))); double currentMag = lowerMag; mTickVector.clear(); mTickVector.append(currentMag); while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentMag *= mScaleLogBase; mTickVector.append(currentMag); } } else if (mRange.lower < 0 && mRange.upper < 0) // negative range { double lowerMag = -basePow(qCeil(baseLog(-mRange.lower))); double currentMag = lowerMag; mTickVector.clear(); mTickVector.append(currentMag); while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentMag /= mScaleLogBase; mTickVector.append(currentMag); } } else // invalid range for logarithmic scale, because lower and upper have different sign { mTickVector.clear(); qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; } } } /*! \internal Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks, because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note that a subtick count of 4 means dividing the major tick step into 5 sections. This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is returned. */ int QCPAxis::calculateAutoSubTickCount(double tickStep) const { int result = mSubTickCount; // default to current setting, if no proper value can be found // get mantissa of tickstep: double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. double tickStepMantissa = tickStep/magnitudeFactor; // separate integer and fractional part of mantissa: double epsilon = 0.01; double intPartf; int intPart; double fracPart = modf(tickStepMantissa, &intPartf); intPart = intPartf; // handle cases with (almost) integer mantissa: if (fracPart < epsilon || 1.0-fracPart < epsilon) { if (1.0-fracPart < epsilon) ++intPart; switch (intPart) { case 1: result = 4; break; // 1.0 -> 0.2 substep case 2: result = 3; break; // 2.0 -> 0.5 substep case 3: result = 2; break; // 3.0 -> 1.0 substep case 4: result = 3; break; // 4.0 -> 1.0 substep case 5: result = 4; break; // 5.0 -> 1.0 substep case 6: result = 2; break; // 6.0 -> 2.0 substep case 7: result = 6; break; // 7.0 -> 1.0 substep case 8: result = 3; break; // 8.0 -> 2.0 substep case 9: result = 2; break; // 9.0 -> 3.0 substep } } else { // handle cases with significantly fractional mantissa: if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa { switch (intPart) { case 1: result = 2; break; // 1.5 -> 0.5 substep case 2: result = 4; break; // 2.5 -> 0.5 substep case 3: result = 4; break; // 3.5 -> 0.7 substep case 4: result = 2; break; // 4.5 -> 1.5 substep case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) case 6: result = 4; break; // 6.5 -> 1.3 substep case 7: result = 2; break; // 7.5 -> 2.5 substep case 8: result = 4; break; // 8.5 -> 1.7 substep case 9: result = 4; break; // 9.5 -> 1.9 substep } } // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default } return result; } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) SelectablePart part = details.value<SelectablePart>(); if (mSelectableParts.testFlag(part)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^part : part); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { SelectableParts selBefore = mSelectedParts; setSelectedParts(mSelectedParts & ~mSelectableParts); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. */ void QCPAxis::draw(QCPPainter *painter) { const int lowTick = mLowestVisibleTick; const int highTick = mHighestVisibleTick; QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(highTick-lowTick+1); tickLabels.reserve(highTick-lowTick+1); subTickPositions.reserve(mSubTickVector.size()); if (mTicks) { for (int i=lowTick; i<=highTick; ++i) { tickPositions.append(coordToPixel(mTickVector.at(i))); if (mTickLabels) tickLabels.append(mTickVectorLabels.at(i)); } if (mSubTickCount > 0) { const int subTickCount = mSubTickVector.size(); for (int i=0; i<subTickCount; ++i) // no need to check bounds because subticks are always only created inside current mRange subTickPositions.append(coordToPixel(mSubTickVector.at(i))); } } // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters mAxisPainter->type = mAxisType; mAxisPainter->basePen = getBasePen(); mAxisPainter->labelFont = getLabelFont(); mAxisPainter->labelColor = getLabelColor(); mAxisPainter->label = mLabel; mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; mAxisPainter->tickPen = getTickPen(); mAxisPainter->subTickPen = getSubTickPen(); mAxisPainter->tickLabelFont = getTickLabelFont(); mAxisPainter->tickLabelColor = getTickLabelColor(); mAxisPainter->axisRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; mAxisPainter->reversedEndings = mRangeReversed; mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; mAxisPainter->subTickPositions = subTickPositions; mAxisPainter->draw(painter); } /*! \internal Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in the current range. The return values are indices of the tick vector, not the positions of the ticks themselves. The actual use of this function is when an external tick vector is provided, since it might exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of subticks. If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be smaller than lowIndex. There is one case, where this function returns indices that are not really visible in the current axis range: When the tick spacing is larger than the axis range size and one tick is below the axis range and the next tick is already above the axis range. Because in such cases it is usually desirable to know the tick pair, to draw proper subticks. */ void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const { bool lowFound = false; bool highFound = false; lowIndex = 0; highIndex = -1; for (int i=0; i < mTickVector.size(); ++i) { if (mTickVector.at(i) >= mRange.lower) { lowFound = true; lowIndex = i; break; } } for (int i=mTickVector.size()-1; i >= 0; --i) { if (mTickVector.at(i) <= mRange.upper) { highFound = true; highIndex = i; break; } } if (!lowFound && highFound) lowIndex = highIndex+1; else if (lowFound && !highFound) highIndex = lowIndex-1; } /*! \internal A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation. This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase. \see basePow, setScaleLogBase, setScaleType */ double QCPAxis::baseLog(double value) const { return qLn(value)*mScaleLogBaseLogInv; } /*! \internal A power function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic scales with arbitrary log base. \see baseLog, setScaleLogBase, setScaleType */ double QCPAxis::basePow(double value) const { return qPow(mScaleLogBase, value); } /*! \internal Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis return 0; if (mCachedMarginValid) return mCachedMargin; // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels int margin = 0; int lowTick, highTick; visibleTickBounds(lowTick, highTick); QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(highTick-lowTick+1); tickLabels.reserve(highTick-lowTick+1); if (mTicks) { for (int i=lowTick; i<=highTick; ++i) { tickPositions.append(coordToPixel(mTickVector.at(i))); if (mTickLabels) tickLabels.append(mTickVectorLabels.at(i)); } } // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters mAxisPainter->type = mAxisType; mAxisPainter->labelFont = getLabelFont(); mAxisPainter->label = mLabel; mAxisPainter->tickLabelFont = mTickLabelFont; mAxisPainter->axisRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; margin += mAxisPainter->size(); margin += mPadding; mCachedMargin = margin; mCachedMarginValid = true; return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { return QCP::iSelectAxes; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisPainterPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisPainterPrivate \internal \brief (Private) This is a private class and not part of the public QCustomPlot interface. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. */ /*! Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : type(QCPAxis::atLeft), basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), lowerEnding(QCPLineEnding::esNone), upperEnding(QCPLineEnding::esNone), labelPadding(0), tickLabelPadding(0), tickLabelRotation(0), tickLabelSide(QCPAxis::lsOutside), substituteExponent(true), numberMultiplyCross(false), tickLengthIn(5), tickLengthOut(0), subTickLengthIn(2), subTickLengthOut(0), tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), offset(0), abbreviateDecimalPowers(false), reversedEndings(false), mParentPlot(parentPlot), mLabelCache(16) // cache at most 16 (tick) labels { } QCPAxisPainterPrivate::~QCPAxisPainterPrivate() { } /*! \internal Draws the axis with the specified \a painter. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { QByteArray newHash = generateLabelParameterHash(); if (newHash != mLabelParameterHash) { mLabelCache.clear(); mLabelParameterHash = newHash; } QPoint origin; switch (type) { case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; } double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) switch (type) { case QCPAxis::atTop: yCor = -1; break; case QCPAxis::atRight: xCor = 1; break; default: break; } int margin = 0; // draw baseline: QLineF baseLine; painter->setPen(basePen); if (QCPAxis::orientation(type) == Qt::Horizontal) baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); else baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); if (reversedEndings) baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later painter->drawLine(baseLine); // draw ticks: if (!tickPositions.isEmpty()) { painter->setPen(tickPen); int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) if (QCPAxis::orientation(type) == Qt::Horizontal) { for (int i=0; i<tickPositions.size(); ++i) painter->drawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); } else { for (int i=0; i<tickPositions.size(); ++i) painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); } } // draw subticks: if (!subTickPositions.isEmpty()) { painter->setPen(subTickPen); // direction of ticks ("inward" is right for left axis and left for right axis) int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; if (QCPAxis::orientation(type) == Qt::Horizontal) { for (int i=0; i<subTickPositions.size(); ++i) painter->drawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); } else { for (int i=0; i<subTickPositions.size(); ++i) painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); } } margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // draw axis base endings: bool antialiasingBackup = painter->antialiasing(); painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't painter->setBrush(QBrush(basePen.color())); QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); if (lowerEnding.style() != QCPLineEnding::esNone) lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); if (upperEnding.style() != QCPLineEnding::esNone) upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); painter->setAntialiasing(antialiasingBackup); // tick labels: QRect oldClipRect; if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect { oldClipRect = painter->clipRegion().boundingRect(); painter->setClipRect(axisRect); } QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label if (!tickLabels.isEmpty()) { if (tickLabelSide == QCPAxis::lsOutside) margin += tickLabelPadding; painter->setFont(tickLabelFont); painter->setPen(QPen(tickLabelColor)); const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); int distanceToAxis = margin; if (tickLabelSide == QCPAxis::lsInside) distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); for (int i=0; i<maxLabelIndex; ++i) placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize); if (tickLabelSide == QCPAxis::lsOutside) margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width(); } if (tickLabelSide == QCPAxis::lsInside) painter->setClipRect(oldClipRect); // axis label: QRect labelBounds; if (!label.isEmpty()) { margin += labelPadding; painter->setFont(labelFont); painter->setPen(QPen(labelColor)); labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); if (type == QCPAxis::atLeft) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); painter->rotate(-90); painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atRight) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); painter->rotate(90); painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atTop) painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); else if (type == QCPAxis::atBottom) painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); } // set selection boxes: int selectionTolerance = 0; if (mParentPlot) selectionTolerance = mParentPlot->selectionTolerance(); else qDebug() << Q_FUNC_INFO << "mParentPlot is null"; int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); int selAxisInSize = selectionTolerance; int selTickLabelSize; int selTickLabelOffset; if (tickLabelSide == QCPAxis::lsOutside) { selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; } else { selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); } int selLabelSize = labelBounds.height(); int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; if (type == QCPAxis::atLeft) { mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); } else if (type == QCPAxis::atRight) { mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); } else if (type == QCPAxis::atTop) { mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); } else if (type == QCPAxis::atBottom) { mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); } mAxisSelectionBox = mAxisSelectionBox.normalized(); mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); mLabelSelectionBox = mLabelSelectionBox.normalized(); // draw hitboxes for debug purposes: //painter->setBrush(Qt::NoBrush); //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() const { int result = 0; // get length of tick marks pointing outwards: if (!tickPositions.isEmpty()) result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // calculate size of tick labels: if (tickLabelSide == QCPAxis::lsOutside) { QSize tickLabelsSize(0, 0); if (!tickLabels.isEmpty()) { for (int i=0; i<tickLabels.size(); ++i) getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize); result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width(); result += tickLabelPadding; } } // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees): if (!label.isEmpty()) { QFontMetrics fontMetrics(labelFont); QRect bounds; bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label); result += bounds.height() + labelPadding; } return result; } /*! \internal Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This method is called automatically in \ref draw, if any parameters have changed that invalidate the cached labels, such as font, color, etc. */ void QCPAxisPainterPrivate::clearCache() { mLabelCache.clear(); } /*! \internal Returns a hash that allows uniquely identifying whether the label parameters have changed such that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the return value of this method hasn't changed since the last redraw, the respective label parameters haven't changed and cached labels may be used. */ QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const { QByteArray result; result.append(QByteArray::number(tickLabelRotation)); result.append(QByteArray::number((int)tickLabelSide)); result.append(QByteArray::number((int)substituteExponent)); result.append(QByteArray::number((int)numberMultiplyCross)); result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16)); result.append(tickLabelFont.toString().toLatin1()); return result; } /*! \internal Draws a single tick label with the provided \a painter, utilizing the internal label cache to significantly speed up drawing of labels that were drawn in previous calls. The tick label is always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), at which the label should be drawn. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently holds. The label is drawn with the font and pen that are currently set on the \a painter. To draw superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref getTickLabelData). */ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize) { // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! if (text.isEmpty()) return; QSize finalSize; QPointF labelAnchor; switch (type) { case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break; case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break; case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break; case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break; } if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled { CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache if (!cachedLabel) // no cached label existed, create it { cachedLabel = new CachedLabel; TickLabelData labelData = getTickLabelData(painter->font(), text); cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft(); cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); cachedLabel->pixmap.fill(Qt::transparent); QCPPainter cachePainter(&cachedLabel->pixmap); cachePainter.setPen(painter->pen()); drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); } // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left(); else labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); } if (!labelClippedByBorder) { painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); finalSize = cachedLabel->pixmap.size(); } mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created } else // label caching disabled, draw text directly on surface: { TickLabelData labelData = getTickLabelData(painter->font(), text); QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); else labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); } if (!labelClippedByBorder) { drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); finalSize = labelData.rotatedTotalBounds.size(); } } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } /*! \internal This is a \ref placeTickLabel helper function. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when QCP::phCacheLabels plotting hint is not set. */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { // backup painter settings that we're about to change: QTransform oldTransform = painter->transform(); QFont oldFont = painter->font(); // transform painter to position/rotation: painter->translate(x, y); if (!qFuzzyIsNull(tickLabelRotation)) painter->rotate(tickLabelRotation); // draw text: if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used { painter->setFont(labelData.baseFont); painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); painter->setFont(labelData.expFont); painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); } else { painter->setFont(labelData.baseFont); painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); } // reset painter settings to what it was before: painter->setTransform(oldTransform); painter->setFont(oldFont); } /*! \internal This is a \ref placeTickLabel helper function. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { TickLabelData result; // determine whether beautiful decimal powers should be used bool useBeautifulPowers = false; int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart if (substituteExponent) { ePos = text.indexOf(QLatin1Char('e')); if (ePos > 0 && text.at(ePos-1).isDigit()) { eLast = ePos; while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit())) ++eLast; if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power useBeautifulPowers = true; } } // calculate text bounding rects and do string preparation for beautiful decimal powers: result.baseFont = font; if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding if (useBeautifulPowers) { // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: result.basePart = text.left(ePos); // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: if (abbreviateDecimalPowers && result.basePart == QLatin1String("1")) result.basePart = QLatin1String("10"); else result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10"); result.expPart = text.mid(ePos+1); // clip "+" and leading zeros off expPart: while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e' result.expPart.remove(1, 1); if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) result.expPart.remove(0, 1); // prepare smaller font for exponent: result.expFont = font; if (result.expFont.pointSize() > 0) result.expFont.setPointSize(result.expFont.pointSize()*0.75); else result.expFont.setPixelSize(result.expFont.pixelSize()*0.75); // calculate bounding rects of base part, exponent part and total one: result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA } else // useBeautifulPowers == false { result.basePart = text; result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); } result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler // calculate possibly different bounding rect after rotation: result.rotatedTotalBounds = result.totalBounds; if (!qFuzzyIsNull(tickLabelRotation)) { QTransform transform; transform.rotate(tickLabelRotation); result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); } return result; } /*! \internal This is a \ref placeTickLabel helper function. Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { /* calculate label offset from base point at tick (non-trivial, for best visual appearance): short explanation for bottom axis: The anchor, i.e. the point in the label that is placed horizontally under the corresponding tick is always on the label side that is closer to the axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text will be centered under the tick (i.e. displaced horizontally by half its height). At the same time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick labels. */ bool doRotation = !qFuzzyIsNull(tickLabelRotation); bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. double radians = tickLabelRotation/180.0*M_PI; int x=0, y=0; if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width(); y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = -labelData.totalBounds.width(); y = -labelData.totalBounds.height()/2.0; } } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height(); y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = 0; y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = 0; y = -labelData.totalBounds.height()/2.0; } } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); } else { x = -qSin(-radians)*labelData.totalBounds.height()/2.0; y = -qCos(-radians)*labelData.totalBounds.height(); } } else { x = -labelData.totalBounds.width()/2.0; y = -labelData.totalBounds.height(); } } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height()/2.0; y = 0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; y = +qSin(-radians)*labelData.totalBounds.width(); } } else { x = -labelData.totalBounds.width()/2.0; y = 0; } } return QPointF(x, y); } /*! \internal Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a smaller width/height. */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { // note: this function must return the same tick label sizes as the placeTickLabel function. QSize finalSize; if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label { const CachedLabel *cachedLabel = mLabelCache.object(text); finalSize = cachedLabel->pixmap.size(); } else // label caching disabled or no label with this text cached: { TickLabelData labelData = getTickLabelData(font, text); finalSize = labelData.rotatedTotalBounds.size(); } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractPlottable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractPlottable \brief The abstract base class for all data representing objects in a plot. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new ways of displaying data (see "Creating own plottables" below). All further specifics are in the subclasses, for example: \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph (typically created with \ref QCustomPlot::addGraph) \li A parametric curve: \ref QCPCurve \li A bar chart: \ref QCPBars \li A statistical box plot: \ref QCPStatisticalBox \li A color encoded two-dimensional map: \ref QCPColorMap \li An OHLC/Candlestick chart: \ref QCPFinancial \section plottables-subclassing Creating own plottables To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure virtual functions, you must implement: \li \ref clearData \li \ref selectTest \li \ref draw \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange See the documentation of those functions for what they need to do. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis is vertical and the value axis horizontal). If you are worried about performance (i.e. you need to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. Here are some important members you inherit from QCPAbstractPlottable: <table> <tr> <td>QCustomPlot *\b mParentPlot</td> <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td> </tr><tr> <td>QString \b mName</td> <td>The name of the plottable.</td> </tr><tr> <td>QPen \b mPen</td> <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)</td> </tr><tr> <td>QPen \b mSelectedPen</td> <td>The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).</td> </tr><tr> <td>QBrush \b mBrush</td> <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)</td> </tr><tr> <td>QBrush \b mSelectedBrush</td> <td>The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).</td> </tr><tr> <td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td> <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.</td> </tr><tr> <td>bool \b mSelected</td> <td>indicates whether the plottable is selected or not.</td> </tr> </table> */ /* start of documentation of pure virtual functions */ /*! \fn void QCPAbstractPlottable::clearData() = 0 Clears all data in the plottable. */ /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't appear outside the legend icon border. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero, which wouldn't count as a valid range. \see rescaleAxes, getValueRange */ /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero, which wouldn't count as a valid range. \see rescaleAxes, getKeyRange */ /* end of documentation of pure virtual functions */ /* start of documentation of signals */ /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelected. */ /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); This signal is emitted when the selectability of this plottable has changed. \see setSelectable */ /* end of documentation of signals */ /*! Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), mName(), mAntialiasedFill(true), mAntialiasedScatters(true), mAntialiasedErrorBars(false), mPen(Qt::black), mSelectedPen(Qt::black), mBrush(Qt::NoBrush), mSelectedBrush(Qt::NoBrush), mKeyAxis(keyAxis), mValueAxis(valueAxis), mSelectable(true), mSelected(false) { if (keyAxis->parentPlot() != valueAxis->parentPlot()) qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; if (keyAxis->orientation() == valueAxis->orientation()) qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; } /*! The name is the textual representation of this plottable as it is displayed in the legend (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. */ void QCPAbstractPlottable::setName(const QString &name) { mName = name; } /*! Sets whether fills of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedFill(bool enabled) { mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) { mAntialiasedScatters = enabled; } /*! Sets whether the error bars of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled) { mAntialiasedErrorBars = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { mPen = pen; } /*! When the plottable is selected, this pen is used to draw basic lines instead of the normal pen set via \ref setPen. \see setSelected, setSelectable, setSelectedBrush, selectTest */ void QCPAbstractPlottable::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! The brush is used to draw basic fills of the plottable representation in the plot. The Fill can be a color, gradient or texture, see the usage of QBrush. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. \see setPen */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { mBrush = brush; } /*! When the plottable is selected, this brush is used to draw fills instead of the normal brush set via \ref setBrush. \see setSelected, setSelectable, setSelectedPen, selectTest */ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setValueAxis */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { mKeyAxis = axis; } /*! The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's key axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { mValueAxis = axis; } /*! Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectPlottables.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected directly. \see setSelected */ void QCPAbstractPlottable::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this plottable is selected or not. When selected, it uses a different pen and brush to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush. The entire selection mechanism for plottables is handled automatically when \ref QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Rescales the key and value axes associated with this plottable to contain all displayed data, so the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { rescaleKeyAxis(onlyEnlarge); rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } SignDomain signDomain = sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(keyAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (keyAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-keyAxis->range().size()/2.0; newRange.upper = center+keyAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); } } keyAxis->setRange(newRange); } } /*! Rescales the value axis of the plottable so the whole plottable is visible. Returns true if the axis was actually scaled. This might not be the case if this plottable has an invalid range, e.g. because it has no data points. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const { QCPAxis *valueAxis = mValueAxis.data(); if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } SignDomain signDomain = sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(valueAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (valueAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-valueAxis->range().size()/2.0; newRange.upper = center+valueAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); } } valueAxis->setRange(newRange); } } /*! Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable needs a more specialized representation in the legend, this function will take this into account and instead create the specialized subclass of QCPAbstractLegendItem. Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in the legend. \see removeFromLegend, QCPLegend::addItem */ bool QCPAbstractPlottable::addToLegend() { if (!mParentPlot || !mParentPlot->legend) return false; if (!mParentPlot->legend->hasItemWithPlottable(this)) { mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); return true; } else return false; } /*! Removes the plottable from the legend of the parent QCustomPlot. This means the QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable is removed. Returns true on success, i.e. if the legend exists and a legend item associated with this plottable was found and removed. \see addToLegend, QCPLegend::removeItem */ bool QCPAbstractPlottable::removeFromLegend() const { if (!mParentPlot->legend) return false; if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) return mParentPlot->legend->removeItem(lip); else return false; } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { if (mKeyAxis && mValueAxis) return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); else return QRect(); } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { return QCP::iSelectPlottables; } /*! \internal Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. \see pixelsToCoords, QCPAxis::coordToPixel */ void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { x = keyAxis->coordToPixel(key); y = valueAxis->coordToPixel(value); } else { y = keyAxis->coordToPixel(key); x = valueAxis->coordToPixel(value); } } /*! \internal \overload Returns the input as pixel coordinates in a QPointF. */ const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } if (keyAxis->orientation() == Qt::Horizontal) return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); else return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); } /*! \internal Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. \see coordsToPixels, QCPAxis::coordToPixel */ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { key = keyAxis->pixelToCoord(x); value = valueAxis->pixelToCoord(y); } else { key = keyAxis->pixelToCoord(y); value = valueAxis->pixelToCoord(x); } } /*! \internal \overload Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! \internal Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the graph is not selected and mSelectedPen when it is. */ QPen QCPAbstractPlottable::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the graph is not selected and mSelectedBrush when it is. */ QBrush QCPAbstractPlottable::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable error bars. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); } /*! \internal Finds the shortest squared distance of \a point to the line segment defined by \a start and \a end. This function may be used to help with the implementation of the \ref selectTest function for specific plottables. \note This function is identical to QCPAbstractItem::distSqrToLine */ double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const { QVector2D a(start); QVector2D b(end); QVector2D p(point); QVector2D v(b-a); double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; if (mu < 0) return (a-p).lengthSquared(); else if (mu > 1) return (b-p).lengthSquared(); else return ((a + mu*v)-p).lengthSquared(); } else return (a-p).lengthSquared(); } /* inherits documentation from base class */ void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemAnchor //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). */ /* end documentation of inline functions */ /*! Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : mName(name), mParentPlot(parentPlot), mParentItem(parentItem), mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { // unregister as parent at children: foreach (QCPItemPosition *child, mChildrenX.toList()) { if (child->parentAnchorX() == this) child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX } foreach (QCPItemPosition *child, mChildrenY.toList()) { if (child->parentAnchorY() == this) child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY } } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPoint() const { if (mParentItem) { if (mAnchorId > -1) { return mParentItem->anchorPixelPoint(mAnchorId); } else { qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; return QPointF(); } } else { qDebug() << Q_FUNC_INFO << "no parent item set"; return QPointF(); } } /*! \internal Adds \a pos to the childX list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildX(QCPItemPosition *pos) { if (!mChildrenX.contains(pos)) mChildrenX.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos); } /*! \internal Removes \a pos from the childX list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) { if (!mChildrenX.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos); } /*! \internal Adds \a pos to the childY list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildY(QCPItemPosition *pos) { if (!mChildrenY.contains(pos)) mChildrenY.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos); } /*! \internal Removes \a pos from the childY list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) { if (!mChildrenY.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPosition //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPosition \brief Manages the position of an item. Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y direction, while following a plot coordinate in the X direction. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords) are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line always be centered under the text label, no matter where the text is moved to. For more advanced plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B in Y. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other positions. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified pixel values. */ /* start documentation of inline functions */ /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const Returns the current position type. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the type of the X coordinate. In that case rather use \a typeX() and \a typeY(). \see setType */ /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const Returns the current parent anchor. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), this method returns the parent anchor of the Y coordinate. In that case rather use \a parentAnchorX() and \a parentAnchorY(). \see setParentAnchor */ /* end documentation of inline functions */ /*! Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : QCPItemAnchor(parentPlot, parentItem, name), mPositionTypeX(ptAbsolute), mPositionTypeY(ptAbsolute), mKey(0), mValue(0), mParentAnchorX(0), mParentAnchorY(0) { } QCPItemPosition::~QCPItemPosition() { // unregister as parent at children: // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint foreach (QCPItemPosition *child, mChildrenX.toList()) { if (child->parentAnchorX() == this) child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX } foreach (QCPItemPosition *child, mChildrenY.toList()) { if (child->parentAnchorY() == this) child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY } // unregister as child in parent: if (mParentAnchorX) mParentAnchorX->removeChildX(this); if (mParentAnchorY) mParentAnchorY->removeChildY(this); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. This method sets the type for both X and Y directions. It is also possible to set different types for X and Y, see \ref setTypeX, \ref setTypeY. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { setTypeX(type); setTypeY(type); } /*! This method sets the position type of the X coordinate to \a type. For a detailed description of what a position type is, see the documentation of \ref setType. \see setType, setTypeY */ void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type) { if (mPositionTypeX != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. bool retainPixelPosition = true; if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) retainPixelPosition = false; if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) retainPixelPosition = false; QPointF pixel; if (retainPixelPosition) pixel = pixelPoint(); mPositionTypeX = type; if (retainPixelPosition) setPixelPoint(pixel); } } /*! This method sets the position type of the Y coordinate to \a type. For a detailed description of what a position type is, see the documentation of \ref setType. \see setType, setTypeX */ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) { if (mPositionTypeY != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. bool retainPixelPosition = true; if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) retainPixelPosition = false; if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) retainPixelPosition = false; QPointF pixel; if (retainPixelPosition) pixel = pixelPoint(); mPositionTypeY = type; if (retainPixelPosition) setPixelPoint(pixel); } } /*! Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. This method sets the parent anchor for both X and Y directions. It is also possible to set different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); return successX && successY; } /*! This method sets the parent anchor of the X coordinate to \a parentAnchor. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. \see setParentAnchor, setParentAnchorY */ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor); return false; } currentParent = currentParentPos->parentAnchorX(); } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) setTypeX(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPoint(); // unregister at current parent anchor: if (mParentAnchorX) mParentAnchorX->removeChildX(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChildX(this); mParentAnchorX = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPoint(pixelP); else setCoords(0, coords().y()); return true; } /*! This method sets the parent anchor of the Y coordinate to \a parentAnchor. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. \see setParentAnchor, setParentAnchorX */ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor); return false; } currentParent = currentParentPos->parentAnchorY(); } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) setTypeY(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPoint(); // unregister at current parent anchor: if (mParentAnchorY) mParentAnchorY->removeChildY(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChildY(this); mParentAnchorY = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPoint(pixelP); else setCoords(coords().x(), 0); return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType, \ref setTypeX, \ref setTypeY). For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a value must also be provided in the different coordinate systems. Here, the X type refers to \a key, and the Y type refers to \a value. \see setPixelPoint */ void QCPItemPosition::setCoords(double key, double value) { mKey = key; mValue = value; } /*! \overload Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the meaning of \a value of the \ref setCoords(double key, double value) method. */ void QCPItemPosition::setCoords(const QPointF &pos) { setCoords(pos.x(), pos.y()); } /*! Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). \see setPixelPoint */ QPointF QCPItemPosition::pixelPoint() const { QPointF result; // determine X: switch (mPositionTypeX) { case ptAbsolute: { result.rx() = mKey; if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPoint().x(); break; } case ptViewportRatio: { result.rx() = mKey*mParentPlot->viewport().width(); if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPoint().x(); else result.rx() += mParentPlot->viewport().left(); break; } case ptAxisRectRatio: { if (mAxisRect) { result.rx() = mKey*mAxisRect.data()->width(); if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPoint().x(); else result.rx() += mAxisRect.data()->left(); } else qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) result.rx() = mKeyAxis.data()->coordToPixel(mKey); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) result.rx() = mValueAxis.data()->coordToPixel(mValue); else qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; break; } } // determine Y: switch (mPositionTypeY) { case ptAbsolute: { result.ry() = mValue; if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPoint().y(); break; } case ptViewportRatio: { result.ry() = mValue*mParentPlot->viewport().height(); if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPoint().y(); else result.ry() += mParentPlot->viewport().top(); break; } case ptAxisRectRatio: { if (mAxisRect) { result.ry() = mValue*mAxisRect.data()->height(); if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPoint().y(); else result.ry() += mAxisRect.data()->top(); } else qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) result.ry() = mKeyAxis.data()->coordToPixel(mKey); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) result.ry() = mValueAxis.data()->coordToPixel(mValue); else qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; break; } } return result; } /*! When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and yAxis of the QCustomPlot. */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { mKeyAxis = keyAxis; mValueAxis = valueAxis; } /*! When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of the QCustomPlot. */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { mAxisRect = axisRect; } /*! Sets the apparent pixel position. This works no matter what type (\ref setType) this QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed appropriately, to make the position finally appear at the specified pixel values. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is identical to that of \ref setCoords. \see pixelPoint, setCoords */ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) { double x = pixelPoint.x(); double y = pixelPoint.y(); switch (mPositionTypeX) { case ptAbsolute: { if (mParentAnchorX) x -= mParentAnchorX->pixelPoint().x(); break; } case ptViewportRatio: { if (mParentAnchorX) x -= mParentAnchorX->pixelPoint().x(); else x -= mParentPlot->viewport().left(); x /= (double)mParentPlot->viewport().width(); break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchorX) x -= mParentAnchorX->pixelPoint().x(); else x -= mAxisRect.data()->left(); x /= (double)mAxisRect.data()->width(); } else qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) x = mKeyAxis.data()->pixelToCoord(x); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) y = mValueAxis.data()->pixelToCoord(x); else qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; break; } } switch (mPositionTypeY) { case ptAbsolute: { if (mParentAnchorY) y -= mParentAnchorY->pixelPoint().y(); break; } case ptViewportRatio: { if (mParentAnchorY) y -= mParentAnchorY->pixelPoint().y(); else y -= mParentPlot->viewport().top(); y /= (double)mParentPlot->viewport().height(); break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchorY) y -= mParentAnchorY->pixelPoint().y(); else y -= mAxisRect.data()->top(); y /= (double)mAxisRect.data()->height(); } else qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) x = mKeyAxis.data()->pixelToCoord(y); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) y = mValueAxis.data()->pixelToCoord(y); else qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; break; } } setCoords(x, y); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. The built-in items are: <table> <tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr> <tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr> <tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr> <tr><td>QCPItemRect</td><td>A rectangle</td></tr> <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr> <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr> <tr><td>QCPItemText</td><td>A text label</td></tr> <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr> <tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr> </table> \section items-clipping Clipping Items are by default clipped to the main axis rect (they are only visible inside the axis rect). To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect "setClipToAxisRect(false)". On the other hand if you want the item to be clipped to a different axis rect, specify it via \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and in principle is independent of the coordinate axes the item might be tied to via its position members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping also contains the axes used for the item positions. \section items-using Using items First you instantiate the item you want to use and add it to the plot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just set the plot coordinates where the line should start/end: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2 If we don't want the line to be positioned in plot coordinates but a different coordinate system, e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3 Then we can set the coordinates, this time in pixels: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 For more advanced plots, it is even possible to set different types and parent anchors per X/Y coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. \section items-subclassing Creating own items To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw See the documentation of those functions for what they need to do. \subsection items-positioning Allowing the item to be positioned As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: \code QCPItemPosition * const myPosition;\endcode the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), myPosition(createPosition("myPosition")) { // other constructor code } \endcode \subsection items-drawing The draw function To give your item a visual representation, reimplement the \ref draw function and use the passed QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the position member(s) via \ref QCPItemPosition::pixelPoint. To optimize performance you should calculate a bounding rect first (don't forget to take the pen width into account), check whether it intersects the \ref clipRect, and only draw the item at all if this is the case. \subsection items-selection The selectTest function Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and \ref rectSelectTest. With these, the implementation of the selection test becomes significantly simpler for most items. See the documentation of \ref selectTest for what the function parameters mean and what the function should return. \subsection anchors Providing anchors Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). Since anchors can be placed anywhere, relative to the item's position(s), your item needs to provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int anchorId) function. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ /* start of documentation of inline functions */ /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const Returns all positions of the item in a list. \see anchors, position */ /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. \see positions, anchor */ /* end of documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal Draws this item with the provided \a painter. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPAbstractItem::selectionChanged(bool selected) This signal is emitted when the selection state of this item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end documentation of signals */ /*! Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), mClipToAxisRect(false), mSelectable(true), mSelected(false) { QList<QCPAxisRect*> rects = parentPlot->axisRects(); if (rects.size() > 0) { setClipToAxisRect(true); setClipAxisRect(rects.first()); } } QCPAbstractItem::~QCPAbstractItem() { // don't delete mPositions because every position is also an anchor and thus in mAnchors qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { mClipToAxisRect = clip; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { mClipAxisRect = rect; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this item is selected or not. When selected, it might use a different visual appearance (e.g. pen and brush), this depends on the specific item though. The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns 0. This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { for (int i=0; i<mPositions.size(); ++i) { if (mPositions.at(i)->name() == name) return mPositions.at(i); } qDebug() << Q_FUNC_INFO << "position with name not found:" << name; return 0; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns 0. This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { for (int i=0; i<mAnchors.size(); ++i) { if (mAnchors.at(i)->name() == name) return mAnchors.at(i); } qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; return 0; } /*! Returns whether this item has an anchor with the specified \a name. Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { for (int i=0; i<mAnchors.size(); ++i) { if (mAnchors.at(i)->name() == name) return true; } return false; } /*! \internal Returns the rect the visual representation of this item is clipped to. This depends on the current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned. \see draw */ QRect QCPAbstractItem::clipRect() const { if (mClipToAxisRect && mClipAxisRect) return mClipAxisRect.data()->rect(); else return mParentPlot->viewport(); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } /*! \internal Finds the shortest squared distance of \a point to the line segment defined by \a start and \a end. This function may be used to help with the implementation of the \ref selectTest function for specific items. \note This function is identical to QCPAbstractPlottable::distSqrToLine \see rectSelectTest */ double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const { QVector2D a(start); QVector2D b(end); QVector2D p(point); QVector2D v(b-a); double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; if (mu < 0) return (a-p).lengthSquared(); else if (mu > 1) return (b-p).lengthSquared(); else return ((a + mu*v)-p).lengthSquared(); } else return (a-p).lengthSquared(); } /*! \internal A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. This function may be used to help with the implementation of the \ref selectTest function for specific items. For example, if your item consists of four rects, call this function four times, once for each rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned values. \see distSqrToLine */ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const { double result = -1; // distance to border: QList<QLineF> lines; lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); double minDistSqr = std::numeric_limits<double>::max(); for (int i=0; i<lines.size(); ++i) { double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos); if (distSqr < minDistSqr) minDistSqr = distSqr; } result = qSqrt(minDistSqr); // filled rect, allow click inside to count as hit: if (filledRect && result > mParentPlot->selectionTolerance()*0.99) { if (rect.contains(pos)) result = mParentPlot->selectionTolerance()*0.99; } return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const { qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; return QPointF(); } /*! \internal Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). Don't delete positions created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); mPositions.append(newPosition); mAnchors.append(newPosition); // every position is also an anchor newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); newPosition->setType(QCPItemPosition::ptPlotCoords); if (mParentPlot->axisRect()) newPosition->setAxisRect(mParentPlot->axisRect()); newPosition->setCoords(0, 0); return newPosition; } /*! \internal Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns the correct pixel coordinates for the passed anchor id. Don't delete anchors created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); mAnchors.append(newAnchor); return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { return QCP::iSelectItems; } /*! \file */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCustomPlot //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ /* start of documentation of inline functions */ /*! \fn QRect QCustomPlot::viewport() const Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger and contains also the axes themselves, their tick numbers, their labels, the plot title etc. Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily modified to allow saving plots with sizes independent of the current widget size. */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse double click event. */ /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. */ /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag axes, consider doing this in the \ref mousePress signal instead. */ /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. */ /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. */ /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) This signal is emitted when a plottable is clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. \see plottableDoubleClick */ /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) This signal is emitted when a plottable is double clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. \see plottableClick */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is double clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. \see legendClick */ /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is clicked. \a event is the mouse event that caused the click and \a title is the plot title that received the click. \see titleDoubleClick */ /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is double clicked. \a event is the mouse event that caused the click and \a title is the plot title that received the click. \see titleClick */ /*! \fn void QCustomPlot::selectionChangedByUser() This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected() on an object or by calling \ref deselectAll. In addition to this signal, selectable objects also provide individual signals, for example QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are emitted even if the selection state is changed programmatically. See the documentation of \ref setInteractions for details about the selection mechanism. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, afterReplot */ /*! \fn void QCustomPlot::afterReplot() This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, beforeReplot */ /* end of documentation of signals */ /* start of documentation of public members */ /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::xAxis2 A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::yAxis2 A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPLegend *QCustomPlot::legend A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple legends to the plot, use the layout system interface to access the new legend. For example, legends can be placed inside an axis rect's \ref QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointer becomes 0. */ /* end of documentation of public members */ /*! Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : QWidget(parent), xAxis(0), yAxis(0), xAxis2(0), yAxis2(0), legend(0), mPlotLayout(0), mAutoAddPlottableToLegend(true), mAntialiasedElements(QCP::aeNone), mNotAntialiasedElements(QCP::aeNone), mInteractions(0), mSelectionTolerance(8), mNoAntialiasingOnDrag(false), mBackgroundBrush(Qt::white, Qt::SolidPattern), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mCurrentLayer(0), mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), mMultiSelectModifier(Qt::ControlModifier), mPaintBuffer(size()), mMouseEventElement(0), mReplotting(false) { setAttribute(Qt::WA_NoMousePropagation); setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); QLocale currentLocale = locale(); currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); setLocale(currentLocale); // create initial layers: mLayers.append(new QCPLayer(this, QLatin1String("background"))); mLayers.append(new QCPLayer(this, QLatin1String("grid"))); mLayers.append(new QCPLayer(this, QLatin1String("main"))); mLayers.append(new QCPLayer(this, QLatin1String("axes"))); mLayers.append(new QCPLayer(this, QLatin1String("legend"))); updateLayerIndices(); setCurrentLayer(QLatin1String("main")); // create initial layout, axis rect and legend: mPlotLayout = new QCPLayoutGrid; mPlotLayout->initializeParentPlot(this); mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry mPlotLayout->setLayer(QLatin1String("main")); QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); mPlotLayout->addElement(0, 0, defaultAxisRect); xAxis = defaultAxisRect->axis(QCPAxis::atBottom); yAxis = defaultAxisRect->axis(QCPAxis::atLeft); xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); legend = new QCPLegend; legend->setVisible(false); defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); defaultAxisRect->setLayer(QLatin1String("background")); xAxis->setLayer(QLatin1String("axes")); yAxis->setLayer(QLatin1String("axes")); xAxis2->setLayer(QLatin1String("axes")); yAxis2->setLayer(QLatin1String("axes")); xAxis->grid()->setLayer(QLatin1String("grid")); yAxis->grid()->setLayer(QLatin1String("grid")); xAxis2->grid()->setLayer(QLatin1String("grid")); yAxis2->grid()->setLayer(QLatin1String("grid")); legend->setLayer(QLatin1String("legend")); setViewport(rect()); // needs to be called after mPlotLayout has been created replot(); } QCustomPlot::~QCustomPlot() { clearPlottables(); clearItems(); if (mPlotLayout) { delete mPlotLayout; mPlotLayout = 0; } mCurrentLayer = 0; qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { mAntialiasedElements = antialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. See \ref setAntialiasedElements for details. \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements &= ~antialiasedElement; else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements |= antialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements) { mNotAntialiasedElements = notAntialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. See \ref setNotAntialiasedElements for details. \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements &= ~notAntialiasedElement; else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements |= notAntialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the plottable to the legend (QCustomPlot::legend). \see addPlottable, addGraph, QCPLegend::addItem */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes. <b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific plottable. To find out whether a specific plottable is selected, call QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience function \ref selectedGraphs. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To find out which child items are selected, call \ref QCPLegend::selectedItems. <b>All other selectable elements</b> The selection of all other selectable objects (e.g. QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the user may select those objects by clicking on them. To find out which are currently selected, you need to check their selected state explicitly. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. For details about the interaction system, see \ref setInteractions. \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { if (!enabled && mInteractions.testFlag(interaction)) mInteractions &= ~interaction; else if (enabled && !mInteractions.testFlag(interaction)) mInteractions |= interaction; } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { mSelectionTolerance = pixels; } /*! Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { QCP::PlottingHints newHints = mPlottingHints; if (!enabled) newHints &= ~hint; else newHints |= hint; if (newHints != mPlottingHints) setPlottingHints(newHints); } /*! Sets the keyboard modifier that will be recognized as multi-select-modifier. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects by clicking on them one after the other while holding down \a modifier. By default the multi-select-modifier is set to Qt::ControlModifier. \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { mMultiSelectModifier = modifier; } /*! Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref savePdf, etc. by temporarily changing the viewport size. */ void QCustomPlot::setViewport(const QRect &rect) { mViewport = rect; if (mPlotLayout) mPlotLayout->setOuterRect(mViewport); } /*! Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn below all other objects in the plot. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! Sets the background brush of the viewport (see \ref setViewport). Before drawing everything else, the background is filled with \a brush. If a background pixmap was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { if (index >= 0 && index < mPlottables.size()) { return mPlottables.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last plottable that was added with \ref addPlottable. If there are no plottables in the plot, returns 0. \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable() { if (!mPlottables.isEmpty()) { return mPlottables.last(); } else return 0; } /*! Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the plottable's constructor). \see plottable, plottableCount, removePlottable, clearPlottables */ bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable) { if (mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable); return false; } if (plottable->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable); return false; } mPlottables.append(plottable); // possibly add plottable to legend: if (mAutoAddPlottableToLegend) plottable->addToLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable)) mGraphs.append(graph); if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) plottable->setLayer(currentLayer()); return true; } /*! Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend). Returns true on success. \see addPlottable, clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { if (!mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable); return false; } // remove plottable from legend: plottable->removeFromLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable)) mGraphs.removeOne(graph); // remove plottable: delete plottable; mPlottables.removeOne(plottable); return true; } /*! \overload Removes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { if (index >= 0 && index < mPlottables.size()) return removePlottable(mPlottables[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). Returns the number of plottables removed. \see removePlottable */ int QCustomPlot::clearPlottables() { int c = mPlottables.size(); for (int i=c-1; i >= 0; --i) removePlottable(mPlottables[i]); return c; } /*! Returns the number of currently existing plottables in the plot \see plottable, addPlottable */ int QCustomPlot::plottableCount() const { return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const { QList<QCPAbstractPlottable*> result; foreach (QCPAbstractPlottable *plottable, mPlottables) { if (plottable->selected()) result.append(plottable); } return result; } /*! Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. If there is no plottable at \a pos, the return value is 0. \see itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const { QCPAbstractPlottable *resultPlottable = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractPlottable *plottable, mPlottables) { if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable continue; if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes { double currentDistance = plottable->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultPlottable = plottable; resultDistance = currentDistance; } } } return resultPlottable; } /*! Returns whether this QCustomPlot instance contains the \a plottable. \see addPlottable */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { if (index >= 0 && index < mGraphs.size()) { return mGraphs.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns 0. \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { if (!mGraphs.isEmpty()) { return mGraphs.last(); } else return 0; } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. Returns a pointer to the newly created graph, or 0 if adding the graph failed. \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { if (!keyAxis) keyAxis = xAxis; if (!valueAxis) valueAxis = yAxis; if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; return 0; } if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; return 0; } QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); if (addPlottable(newGraph)) { newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); return newGraph; } else { delete newGraph; return 0; } } /*! Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If any other graphs in the plot have a channel fill set towards the removed graph, the channel fill property of those graphs is reset to zero (no channel fill). Returns true on success. \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { return removePlottable(graph); } /*! \overload Removes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { if (index >= 0 && index < mGraphs.size()) return removeGraph(mGraphs[index]); else return false; } /*! Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). Returns the number of graphs removed. \see removeGraph */ int QCustomPlot::clearGraphs() { int c = mGraphs.size(); for (int i=c-1; i >= 0; --i) removeGraph(mGraphs[i]); return c; } /*! Returns the number of currently existing graphs in the plot \see graph, addGraph */ int QCustomPlot::graphCount() const { return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, etc., use \ref selectedPlottables. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ QList<QCPGraph*> QCustomPlot::selectedGraphs() const { QList<QCPGraph*> result; foreach (QCPGraph *graph, mGraphs) { if (graph->selected()) result.append(graph); } return result; } /*! Returns the item with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item(int index) const { if (index >= 0 && index < mItems.size()) { return mItems.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last item, that was added with \ref addItem. If there are no items in the plot, returns 0. \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item() const { if (!mItems.isEmpty()) { return mItems.last(); } else return 0; } /*! Adds the specified item to the plot. QCustomPlot takes ownership of the item. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a item is this QCustomPlot. \see item, itemCount, removeItem, clearItems */ bool QCustomPlot::addItem(QCPAbstractItem *item) { if (!mItems.contains(item) && item->parentPlot() == this) { mItems.append(item); return true; } else { qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item); return false; } } /*! Removes the specified item from the plot. Returns true on success. \see addItem, clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { if (mItems.contains(item)) { delete item; mItems.removeOne(item); return true; } else { qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item); return false; } } /*! \overload Removes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { if (index >= 0 && index < mItems.size()) return removeItem(mItems[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all items from the plot. Returns the number of items removed. \see removeItem */ int QCustomPlot::clearItems() { int c = mItems.size(); for (int i=c-1; i >= 0; --i) removeItem(mItems[i]); return c; } /*! Returns the number of currently existing items in the plot \see item, addItem */ int QCustomPlot::itemCount() const { return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ QList<QCPAbstractItem*> QCustomPlot::selectedItems() const { QList<QCPAbstractItem*> result; foreach (QCPAbstractItem *item, mItems) { if (item->selected()) result.append(item); } return result; } /*! Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. If there is no item at \a pos, the return value is 0. \see plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { QCPAbstractItem *resultItem = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractItem *item, mItems) { if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable continue; if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it { double currentDistance = item->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultItem = item; resultDistance = currentDistance; } } } return resultItem; } /*! Returns whether this QCustomPlot contains the \a item. \see addItem */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is returned. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { foreach (QCPLayer *layer, mLayers) { if (layer->name() == name) return layer; } return 0; } /*! \overload Returns the layer by \a index. If the index is invalid, 0 is returned. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { if (index >= 0 && index < mLayers.size()) { return mLayers.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! Returns the layer that is set as current layer (see \ref setCurrentLayer). */ QCPLayer *QCustomPlot::currentLayer() const { return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { if (QCPLayer *newCurrentLayer = layer(name)) { return setCurrentLayer(newCurrentLayer); } else { qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; return false; } } /*! \overload Sets the provided \a layer to be the current layer. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer); return false; } mCurrentLayer = layer; return true; } /*! Returns the number of currently existing layers in the plot \see layer, addLayer */ int QCustomPlot::layerCount() const { return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!otherLayer) otherLayer = mLayers.last(); if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer); return false; } if (layer(name)) { qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; return false; } QCPLayer *newLayer = new QCPLayer(this, name); mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); updateLayerIndices(); return true; } /*! Removes the specified \a layer and returns true on success. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. It is not possible to remove the last layer of the plot. \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer); return false; } if (mLayers.size() < 2) { qDebug() << Q_FUNC_INFO << "can't remove last layer"; return false; } // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) int removedIndex = layer->index(); bool isFirstLayer = removedIndex==0; QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); QList<QCPLayerable*> children = layer->children(); if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) { for (int i=children.size()-1; i>=0; --i) children.at(i)->moveToLayer(targetLayer, true); } else // append normally { for (int i=0; i<children.size(); ++i) children.at(i)->moveToLayer(targetLayer, false); } // if removed layer is current layer, change current layer to layer below/above: if (layer == mCurrentLayer) setCurrentLayer(targetLayer); // remove layer: delete layer; mLayers.removeOne(layer); updateLayerIndices(); return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer); return false; } if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer); return false; } if (layer->index() > otherLayer->index()) mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); else if (layer->index() < otherLayer->index()) mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1)); updateLayerIndices(); return true; } /*! Returns the number of axis rects in the plot. All axis rects can be accessed via QCustomPlot::axisRect(). Initially, only one axis rect exists in the plot. \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { return axisRects().size(); } /*! Returns the axis rect with \a index. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). \see axisRectCount, axisRects */ QCPAxisRect *QCustomPlot::axisRect(int index) const { const QList<QCPAxisRect*> rectList = axisRects(); if (index >= 0 && index < rectList.size()) { return rectList.at(index); } else { qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; return 0; } } /*! Returns all axis rects in the plot. \see axisRectCount, axisRect */ QList<QCPAxisRect*> QCustomPlot::axisRects() const { QList<QCPAxisRect*> result; QStack<QCPLayoutElement*> elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { if (element) { elementStack.push(element); if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element)) result.append(ar); } } } return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns 0. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { QCPLayoutElement *currentElement = mPlotLayout; bool searchSubElements = true; while (searchSubElements && currentElement) { searchSubElements = false; foreach (QCPLayoutElement *subElement, currentElement->elements(false)) { if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) { currentElement = subElement; searchSubElements = true; break; } } } return currentElement; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ QList<QCPAxis*> QCustomPlot::selectedAxes() const { QList<QCPAxis*> result, allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) { if (axis->selectedParts() != QCPAxis::spNone) result.append(axis); } return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ QList<QCPLegend*> QCustomPlot::selectedLegends() const { QList<QCPLegend*> result; QStack<QCPLayoutElement*> elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { if (subElement) { elementStack.push(subElement); if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement)) { if (leg->selectedParts() != QCPLegend::spNone) result.append(leg); } } } } return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) layerable->deselectEvent(0); } } /*! Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the buffer on the QCustomPlot widget surface. This is the method that must be called to make changes, for example on the axis ranges or data points of graphs, visible. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the QCustomPlot widget and user interactions (object selection and range dragging/zooming). Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { if (mReplotting) // incase signals loop back to replot slot return; mReplotting = true; emit beforeReplot(); mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); QCPPainter painter; painter.begin(&mPaintBuffer); if (painter.isActive()) { painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); painter.end(); if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate) repaint(); else update(); } else // might happen if QCustomPlot has width or height zero qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer. This usually happens because QCustomPlot has width or height zero."; emit afterReplot(); mReplotting = false; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { QList<QCPAxis*> allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) axis->rescale(onlyVisiblePlottables); } /*! Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale of texts and lines will be derived from the specified \a width and \a height. This means, the output will look like the normal on-screen output of a QCustomPlot widget with the corresponding pixel width and height. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter and QPen documentation. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. \warning \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). \li If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting PDF file. \note On Android systems, this method does nothing and issues an according qDebug warning message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set. \see savePng, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) { bool success = false; #ifdef QT_NO_PRINTER Q_UNUSED(fileName) Q_UNUSED(noCosmeticPen) Q_UNUSED(width) Q_UNUSED(height) Q_UNUSED(pdfCreator) Q_UNUSED(pdfTitle) qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); printer.setColorMode(QPrinter::Color); printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) printer.setFullPage(true); printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); #else QPageLayout pageLayout; pageLayout.setMode(QPageLayout::FullPageMode); pageLayout.setOrientation(QPageLayout::Portrait); pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); printer.setPageLayout(pageLayout); #endif QCPPainter printpainter; if (printpainter.begin(&printer)) { printpainter.setMode(QCPPainter::pmVectorized); printpainter.setMode(QCPPainter::pmNoCaching); printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); printpainter.setWindow(mViewport); if (mBackgroundBrush.style() != Qt::NoBrush && mBackgroundBrush.color() != Qt::white && mBackgroundBrush.color() != Qt::transparent && mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent printpainter.fillRect(viewport(), mBackgroundBrush); draw(&printpainter); printpainter.end(); success = true; } setViewport(oldViewport); #endif // QT_NO_PRINTER return success; } /*! Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. Returns true on success. If this function fails, most likely the PNG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) { return saveRastered(fileName, width, height, scale, "PNG", quality); } /*! Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. Returns true on success. If this function fails, most likely the JPG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, savePng, saveBmp, saveRastered */ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) { return saveRastered(fileName, width, height, scale, "JPG", quality); } /*! Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. If this function fails, most likely the BMP format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, savePng, saveJpg, saveRastered */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) { return saveRastered(fileName, width, height, scale, "BMP"); } /*! \internal Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. This is especially important, when placed in a QLayout where other components try to take in as much space as possible (e.g. QMdiArea). */ QSize QCustomPlot::minimumSizeHint() const { return mPlotLayout->minimumSizeHint(); } /*! \internal Returns a size hint that is the same as \ref minimumSizeHint. */ QSize QCustomPlot::sizeHint() const { return mPlotLayout->minimumSizeHint(); } /*! \internal Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); painter.drawPixmap(0, 0, mPaintBuffer); } /*! \internal Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized appropriately. Finally a \ref replot is performed. */ void QCustomPlot::resizeEvent(QResizeEvent *event) { // resize and repaint the buffer: mPaintBuffer = QPixmap(event->size()); setViewport(rect()); replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts } /*! \internal Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to it. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) { emit mouseDoubleClick(event); QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // emit specialized object double click signals: if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable)) emit plottableDoubleClick(ap, event); else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable)) emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event); else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable)) emit itemDoubleClick(ai, event); else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable)) emit legendDoubleClick(lg, 0, event); else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable)) emit legendDoubleClick(li->parentLegend(), li, event); else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable)) emit titleDoubleClick(event, pt); // call double click event of affected layout element: if (QCPLayoutElement *el = layoutElementAt(event->pos())) el->mouseDoubleClickEvent(event); // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case): if (mMouseEventElement) { mMouseEventElement->mouseReleaseEvent(event); mMouseEventElement = 0; } //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. } /*! \internal Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines the affected layout element and forwards the event to it. \see mouseMoveEvent, mouseReleaseEvent */ void QCustomPlot::mousePressEvent(QMouseEvent *event) { emit mousePress(event); mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release) // call event of affected layout element: mMouseEventElement = layoutElementAt(event->pos()); if (mMouseEventElement) mMouseEventElement->mousePressEvent(event); QWidget::mousePressEvent(event); } /*! \internal Event handler for when the cursor is moved. Emits the \ref mouseMove signal. If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout element before), the mouseMoveEvent is forwarded to that element. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) { emit mouseMove(event); // call event of affected layout element: if (mMouseEventElement) mMouseEventElement->mouseMoveEvent(event); QWidget::mouseMoveEvent(event); } /*! \internal Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. If the mouse was moved less than a certain threshold in any direction since the \ref mousePressEvent, it is considered a click which causes the selection mechanism (if activated via \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout element before), the \ref mouseReleaseEvent is forwarded to that element. \see mousePressEvent, mouseMoveEvent */ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) { emit mouseRelease(event); bool doReplot = false; if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation { if (event->button() == Qt::LeftButton) { // handle selection mechanism: QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); bool selectionStateChanged = false; bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); // deselect all other layerables if not additive selection: if (!additive) { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) { if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) { bool selChanged = false; layerable->deselectEvent(&selChanged); selectionStateChanged |= selChanged; } } } } if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) { // a layerable was actually clicked, call its selectEvent: bool selChanged = false; clickedLayerable->selectEvent(event, additive, details, &selChanged); selectionStateChanged |= selChanged; } if (selectionStateChanged) { doReplot = true; emit selectionChangedByUser(); } } // emit specialized object click signals: QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable)) emit plottableClick(ap, event); else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable)) emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event); else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable)) emit itemClick(ai, event); else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable)) emit legendClick(lg, 0, event); else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable)) emit legendClick(li->parentLegend(), li, event); else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable)) emit titleClick(event, pt); } // call event of affected layout element: if (mMouseEventElement) { mMouseEventElement->mouseReleaseEvent(event); mMouseEventElement = 0; } if (doReplot || noAntialiasingOnDrag()) replot(); QWidget::mouseReleaseEvent(event); } /*! \internal Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then determines the affected layout element and forwards the event to it. */ void QCustomPlot::wheelEvent(QWheelEvent *event) { emit mouseWheel(event); // call event of affected layout element: if (QCPLayoutElement *el = layoutElementAt(event->pos())) el->wheelEvent(event); QWidget::wheelEvent(event); } /*! \internal This is the main draw function. It draws the entire plot, including background pixmap, with the specified \a painter. Note that it does not fill the background with the background brush (as the user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter). */ void QCustomPlot::draw(QCPPainter *painter) { // run through layout phases: mPlotLayout->update(QCPLayoutElement::upPreparation); mPlotLayout->update(QCPLayoutElement::upMargins); mPlotLayout->update(QCPLayoutElement::upLayout); // draw viewport background pixmap: drawBackground(painter); // draw all layered objects (grid, axes, plottables, items, legend,...): foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *child, layer->children()) { if (child->realVisibility()) { painter->save(); painter->setClipRect(child->clipRect().translated(0, -1)); child->applyDefaultAntialiasingHint(painter); child->draw(painter); painter->restore(); } } } /* Debug code to draw all layout element rects foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>()) { painter->setBrush(Qt::NoBrush); painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->rect()); painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->outerRect()); } */ } /*! \internal Draws the viewport background pixmap of the plot. If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. Note that this function does not draw a fill with the background brush (\ref setBackground(const QBrush &brush)) beneath the pixmap. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { // Note: background color is handled in individual replot/save functions // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mViewport.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); } } } /*! \internal This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { if (xAxis == axis) xAxis = 0; if (xAxis2 == axis) xAxis2 = 0; if (yAxis == axis) yAxis = 0; if (yAxis2 == axis) yAxis2 = 0; // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { if (this->legend == legend) this->legend = 0; } /*! \internal Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { for (int i=0; i<mLayers.size(); ++i) mLayers.at(i)->mIndex = i; } /*! \internal Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those layerables that are selectable will be considered. (Layerable subclasses communicate their selectability via the QCPLayerable::selectTest method, by returning -1.) \a selectionDetails is an output parameter that contains selection specifics of the affected layerable. This is useful if the respective layerable shall be given a subsequent QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains information about which part of the layerable was hit, in multi-part layerables (e.g. QCPAxis::SelectablePart). */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) { const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children(); double minimumDistance = selectionTolerance()*1.1; QCPLayerable *minimumDistanceLayerable = 0; for (int i=layerables.size()-1; i>=0; --i) { if (!layerables.at(i)->realVisibility()) continue; QVariant details; double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); if (dist >= 0 && dist < minimumDistance) { minimumDistance = dist; minimumDistanceLayerable = layerables.at(i); if (selectionDetails) *selectionDetails = details; } } if (minimumDistance < selectionTolerance()) return minimumDistanceLayerable; } return 0; } /*! Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution file with width 200.) If the \a format supports compression, \a quality may be between 0 and 100 to control it. Returns true on success. If this function fails, most likely the given \a format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see saveBmp, saveJpg, savePng, savePdf */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) { QPixmap buffer = toPixmap(width, height, scale); if (!buffer.isNull()) return buffer.save(fileName, format, quality); else return false; } /*! Renders the plot to a pixmap and returns it. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution pixmap with width 200.) \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } int scaledWidth = qRound(scale*newWidth); int scaledHeight = qRound(scale*newHeight); QPixmap result(scaledWidth, scaledHeight); result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later QCPPainter painter; painter.begin(&result); if (painter.isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter.setMode(QCPPainter::pmNoCaching); if (!qFuzzyCompare(scale, 1.0)) { if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales painter.setMode(QCPPainter::pmNonCosmetic); painter.scale(scale, scale); } if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); setViewport(oldViewport); painter.end(); } else // might happen if pixmap has width or height zero { qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; return QPixmap(); } return result; } /*! Renders the plot using the passed \a painter. The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } if (painter->isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter->setMode(QCPPainter::pmNoCaching); if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here painter->fillRect(mViewport, mBackgroundBrush); draw(painter); setViewport(oldViewport); } else qDebug() << Q_FUNC_INFO << "Passed painter is not active"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorGradient //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) with a \a position from 0 to 1. In between these defined color positions, the color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. Alternatively, load one of the preset color gradients shown in the image below, with \ref loadPreset, or by directly specifying the preset in the constructor. \image html QCPColorGradient.png The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref GradientPreset to all the \a setGradient methods, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. */ /*! Constructs a new QCPColorGradient initialized with the colors and color interpolation according to \a preset. The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient(GradientPreset preset) : mLevelCount(350), mColorInterpolation(ciRGB), mPeriodic(false), mColorBufferInvalidated(true) { mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { return ((other.mLevelCount == this->mLevelCount) && (other.mColorInterpolation == this->mColorInterpolation) && (other.mPeriodic == this->mPeriodic) && (other.mColorStops == this->mColorStops)); } /*! Sets the number of discretization levels of the color gradient to \a n. The default is 350 which is typically enough to create a smooth appearance. \image html QCPColorGradient-levelcount.png */ void QCPColorGradient::setLevelCount(int n) { if (n < 2) { qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; n = 2; } if (n != mLevelCount) { mLevelCount = n; mColorBufferInvalidated = true; } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color is interpolated according to \ref setColorInterpolation. A more convenient way to create a custom gradient may be to clear all color stops with \ref clearColorStops and then adding them one by one with \ref setColorStopAt. \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops) { mColorStops = colorStops; mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { mColorStops.insert(position, color); mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { if (interpolation != mColorInterpolation) { mColorInterpolation = interpolation; mColorBufferInvalidated = true; } } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. \image html QCPColorGradient-periodic.png As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { mPeriodic = enabled; } /*! This method is used to quickly convert a \a data array to colors. The colors will be output in the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this function. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data values shall be mapped to colors logarithmically. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data is addressed <tt>data[i*dataIndexFactor]</tt>. */ void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) { // If you change something here, make sure to also adapt ::color() if (!data) { qDebug() << Q_FUNC_INFO << "null pointer given as data"; return; } if (!scanLine) { qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; return; } if (mColorBufferInvalidated) updateColorBuffer(); if (!logarithmic) { const double posToIndexFactor = (mLevelCount-1)/range.size(); if (mPeriodic) { for (int i=0; i<n; ++i) { int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount; if (index < 0) index += mLevelCount; scanLine[i] = mColorBuffer.at(index); } } else { for (int i=0; i<n; ++i) { int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor; if (index < 0) index = 0; else if (index >= mLevelCount) index = mLevelCount-1; scanLine[i] = mColorBuffer.at(index); } } } else // logarithmic == true { if (mPeriodic) { for (int i=0; i<n; ++i) { int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount; if (index < 0) index += mLevelCount; scanLine[i] = mColorBuffer.at(index); } } else { for (int i=0; i<n; ++i) { int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1); if (index < 0) index = 0; else if (index >= mLevelCount) index = mLevelCount-1; scanLine[i] = mColorBuffer.at(index); } } } } /*! \internal This method is used to colorize a single data value given in \a position, to colors. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data value shall be mapped to a color logarithmically. If an entire array of data values shall be converted, rather use \ref colorize, for better performance. */ QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) { // If you change something here, make sure to also adapt ::colorize() if (mColorBufferInvalidated) updateColorBuffer(); int index = 0; if (!logarithmic) index = (position-range.lower)*(mLevelCount-1)/range.size(); else index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1); if (mPeriodic) { index = index % mLevelCount; if (index < 0) index += mLevelCount; } else { if (index < 0) index = 0; else if (index >= mLevelCount) index = mLevelCount-1; } return mColorBuffer.at(index); } /*! Clears the current color stops and loads the specified \a preset. A preset consists of predefined color stops and the corresponding color interpolation method. The available presets are: \image html QCPColorGradient.png */ void QCPColorGradient::loadPreset(GradientPreset preset) { clearColorStops(); switch (preset) { case gpGrayscale: setColorInterpolation(ciRGB); setColorStopAt(0, Qt::black); setColorStopAt(1, Qt::white); break; case gpHot: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(50, 0, 0)); setColorStopAt(0.2, QColor(180, 10, 0)); setColorStopAt(0.4, QColor(245, 50, 0)); setColorStopAt(0.6, QColor(255, 150, 10)); setColorStopAt(0.8, QColor(255, 255, 50)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpCold: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 50)); setColorStopAt(0.2, QColor(0, 10, 180)); setColorStopAt(0.4, QColor(0, 50, 245)); setColorStopAt(0.6, QColor(10, 150, 255)); setColorStopAt(0.8, QColor(50, 255, 255)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpNight: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(10, 20, 30)); setColorStopAt(1, QColor(250, 255, 250)); break; case gpCandy: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(0, 0, 255)); setColorStopAt(1, QColor(255, 250, 250)); break; case gpGeography: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(70, 170, 210)); setColorStopAt(0.20, QColor(90, 160, 180)); setColorStopAt(0.25, QColor(45, 130, 175)); setColorStopAt(0.30, QColor(100, 140, 125)); setColorStopAt(0.5, QColor(100, 140, 100)); setColorStopAt(0.6, QColor(130, 145, 120)); setColorStopAt(0.7, QColor(140, 130, 120)); setColorStopAt(0.9, QColor(180, 190, 190)); setColorStopAt(1, QColor(210, 210, 230)); break; case gpIon: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(50, 10, 10)); setColorStopAt(0.45, QColor(0, 0, 255)); setColorStopAt(0.8, QColor(0, 255, 255)); setColorStopAt(1, QColor(0, 255, 0)); break; case gpThermal: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 50)); setColorStopAt(0.15, QColor(20, 0, 120)); setColorStopAt(0.33, QColor(200, 30, 140)); setColorStopAt(0.6, QColor(255, 100, 0)); setColorStopAt(0.85, QColor(255, 255, 40)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpPolar: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(50, 255, 255)); setColorStopAt(0.18, QColor(10, 70, 255)); setColorStopAt(0.28, QColor(10, 10, 190)); setColorStopAt(0.5, QColor(0, 0, 0)); setColorStopAt(0.72, QColor(190, 10, 10)); setColorStopAt(0.82, QColor(255, 70, 10)); setColorStopAt(1, QColor(255, 255, 50)); break; case gpSpectrum: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(50, 0, 50)); setColorStopAt(0.15, QColor(0, 0, 255)); setColorStopAt(0.35, QColor(0, 255, 255)); setColorStopAt(0.6, QColor(255, 255, 0)); setColorStopAt(0.75, QColor(255, 30, 0)); setColorStopAt(1, QColor(50, 0, 0)); break; case gpJet: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 100)); setColorStopAt(0.15, QColor(0, 50, 255)); setColorStopAt(0.35, QColor(0, 255, 255)); setColorStopAt(0.65, QColor(255, 255, 0)); setColorStopAt(0.85, QColor(255, 30, 0)); setColorStopAt(1, QColor(100, 0, 0)); break; case gpHues: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(255, 0, 0)); setColorStopAt(1.0/3.0, QColor(0, 0, 255)); setColorStopAt(2.0/3.0, QColor(0, 255, 0)); setColorStopAt(1, QColor(255, 0, 0)); break; } } /*! Clears all color stops. \see setColorStops, setColorStopAt */ void QCPColorGradient::clearColorStops() { mColorStops.clear(); mColorBufferInvalidated = true; } /*! Returns an inverted gradient. The inverted gradient has all properties as this \ref QCPColorGradient, but the order of the color stops is inverted. \see setColorStops, setColorStopAt */ QCPColorGradient QCPColorGradient::inverted() const { QCPColorGradient result(*this); result.clearColorStops(); for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) result.setColorStopAt(1.0-it.key(), it.value()); return result; } /*! \internal Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { if (mColorBuffer.size() != mLevelCount) mColorBuffer.resize(mLevelCount); if (mColorStops.size() > 1) { double indexToPosFactor = 1.0/(double)(mLevelCount-1); for (int i=0; i<mLevelCount; ++i) { double position = i*indexToPosFactor; QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position); if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop { mColorBuffer[i] = (it-1).value().rgb(); } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop { mColorBuffer[i] = it.value().rgb(); } else // position is in between stops (or on an intermediate stop), interpolate color { QMap<double, QColor>::const_iterator high = it; QMap<double, QColor>::const_iterator low = it-1; double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 switch (mColorInterpolation) { case ciRGB: { mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(), (1-t)*low.value().green() + t*high.value().green(), (1-t)*low.value().blue() + t*high.value().blue()); break; } case ciHSV: { QColor lowHsv = low.value().toHsv(); QColor highHsv = high.value().toHsv(); double hue = 0; double hueDiff = highHsv.hueF()-lowHsv.hueF(); if (hueDiff > 0.5) hue = lowHsv.hueF() - t*(1.0-hueDiff); else if (hueDiff < -0.5) hue = lowHsv.hueF() + t*(1.0+hueDiff); else hue = lowHsv.hueF() + t*hueDiff; if (hue < 0) hue += 1.0; else if (hue >= 1.0) hue -= 1.0; mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); break; } } } } } else if (mColorStops.size() == 1) { mColorBuffer.fill(mColorStops.constBegin().value().rgb()); } else // mColorStops is empty, fill color buffer with black { mColorBuffer.fill(qRgb(0, 0, 0)); } mColorBufferInvalidated = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. \image html AxisRectSpacingOverview.png <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.</center> */ /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /* end documentation of inline functions */ /*! Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : QCPLayoutElement(parentPlot), mBackgroundBrush(Qt::NoBrush), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mInsetLayout(new QCPLayoutInset), mRangeDrag(Qt::Horizontal|Qt::Vertical), mRangeZoom(Qt::Horizontal|Qt::Vertical), mRangeZoomFactorHorz(0.85), mRangeZoomFactorVert(0.85), mDragging(false) { mInsetLayout->initializeParentPlot(mParentPlot); mInsetLayout->setParentLayerable(this); mInsetLayout->setParent(this); setMinimumSize(50, 50); setMinimumMargins(QMargins(15, 15, 15, 15)); mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>()); mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>()); mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>()); mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>()); if (setupDefaultAxes) { QCPAxis *xAxis = addAxis(QCPAxis::atBottom); QCPAxis *yAxis = addAxis(QCPAxis::atLeft); QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); setRangeDragAxes(xAxis, yAxis); setRangeZoomAxes(xAxis, yAxis); xAxis2->setVisible(false); yAxis2->setVisible(false); xAxis->grid()->setVisible(true); yAxis->grid()->setVisible(true); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); xAxis2->grid()->setZeroLinePen(Qt::NoPen); yAxis2->grid()->setZeroLinePen(Qt::NoPen); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); } } QCPAxisRect::~QCPAxisRect() { delete mInsetLayout; mInsetLayout = 0; QList<QCPAxis*> axesList = axes(); for (int i=0; i<axesList.size(); ++i) removeAxis(axesList.at(i)); } /*! Returns the number of axes on the axis rect side specified with \a type. \see axis */ int QCPAxisRect::axisCount(QCPAxis::AxisType type) const { return mAxes.value(type).size(); } /*! Returns the axis with the given \a index on the axis rect side specified with \a type. \see axisCount, axes */ QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const { QList<QCPAxis*> ax(mAxes.value(type)); if (index >= 0 && index < ax.size()) { return ax.at(index); } else { qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; return 0; } } /*! Returns all axes on the axis rect sides specified with \a types. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of multiple sides. \see axis */ QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const { QList<QCPAxis*> result; if (types.testFlag(QCPAxis::atLeft)) result << mAxes.value(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << mAxes.value(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << mAxes.value(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << mAxes.value(QCPAxis::atBottom); return result; } /*! \overload Returns all axes of this axis rect. */ QList<QCPAxis*> QCPAxisRect::axes() const { QList<QCPAxis*> result; QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes); while (it.hasNext()) { it.next(); result << it.value(); } return result; } /*! Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a new QCPAxis instance is created internally. You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership of the axis, so you may not delete it afterwards. Further, the \a axis must have been created with this axis rect as parent and with the same axis type as specified in \a type. If this is not the case, a debug output is generated, the axis is not added, and the method returns 0. This method can not be used to move \a axis between axis rects. The same \a axis instance must not be added multiple times to the same or different axis rects. If an axis rect side already contains one or more axes, the lower and upper endings of the new axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref QCPLineEnding::esHalfBar. \see addAxes, setupFullAxesBox */ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis) { QCPAxis *newAxis = axis; if (!newAxis) { newAxis = new QCPAxis(this, type); } else // user provided existing axis instance, do some sanity checks { if (newAxis->axisType() != type) { qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; return 0; } if (newAxis->axisRect() != this) { qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; return 0; } if (axes().contains(newAxis)) { qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; return 0; } } if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset { bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } mAxes[type].append(newAxis); return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. Returns a list of the added axes. \see addAxis, setupFullAxesBox */ QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { QList<QCPAxis*> result; if (types.testFlag(QCPAxis::atLeft)) result << addAxis(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << addAxis(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << addAxis(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << addAxis(QCPAxis::atBottom); return result; } /*! Removes the specified \a axis from the axis rect and deletes it. Returns true on success, i.e. if \a axis was a valid axis in this axis rect. \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes); while (it.hasNext()) { it.next(); if (it.value().contains(axis)) { mAxes[it.key()].removeOne(axis); if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) parentPlot()->axisRemoved(axis); delete axis; return true; } } qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis); return false; } /*! Convenience function to create an axis on each side that doesn't have any axes yet and set their visibility to true. Further, the top/right axes are assigned the following properties of the bottom/left axes: \li range (\ref QCPAxis::setRange) \li range reversed (\ref QCPAxis::setRangeReversed) \li scale type (\ref QCPAxis::setScaleType) \li scale log base (\ref QCPAxis::setScaleLogBase) \li ticks (\ref QCPAxis::setTicks) \li auto (major) tick count (\ref QCPAxis::setAutoTickCount) \li sub tick count (\ref QCPAxis::setSubTickCount) \li auto sub ticks (\ref QCPAxis::setAutoSubTicks) \li tick step (\ref QCPAxis::setTickStep) \li auto tick step (\ref QCPAxis::setAutoTickStep) \li number format (\ref QCPAxis::setNumberFormat) \li number precision (\ref QCPAxis::setNumberPrecision) \li tick label type (\ref QCPAxis::setTickLabelType) \li date time format (\ref QCPAxis::setDateTimeFormat) \li date time spec (\ref QCPAxis::setDateTimeSpec) Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; if (axisCount(QCPAxis::atBottom) == 0) xAxis = addAxis(QCPAxis::atBottom); else xAxis = axis(QCPAxis::atBottom); if (axisCount(QCPAxis::atLeft) == 0) yAxis = addAxis(QCPAxis::atLeft); else yAxis = axis(QCPAxis::atLeft); if (axisCount(QCPAxis::atTop) == 0) xAxis2 = addAxis(QCPAxis::atTop); else xAxis2 = axis(QCPAxis::atTop); if (axisCount(QCPAxis::atRight) == 0) yAxis2 = addAxis(QCPAxis::atRight); else yAxis2 = axis(QCPAxis::atRight); xAxis->setVisible(true); yAxis->setVisible(true); xAxis2->setVisible(true); yAxis2->setVisible(true); xAxis2->setTickLabels(false); yAxis2->setTickLabels(false); xAxis2->setRange(xAxis->range()); xAxis2->setRangeReversed(xAxis->rangeReversed()); xAxis2->setScaleType(xAxis->scaleType()); xAxis2->setScaleLogBase(xAxis->scaleLogBase()); xAxis2->setTicks(xAxis->ticks()); xAxis2->setAutoTickCount(xAxis->autoTickCount()); xAxis2->setSubTickCount(xAxis->subTickCount()); xAxis2->setAutoSubTicks(xAxis->autoSubTicks()); xAxis2->setTickStep(xAxis->tickStep()); xAxis2->setAutoTickStep(xAxis->autoTickStep()); xAxis2->setNumberFormat(xAxis->numberFormat()); xAxis2->setNumberPrecision(xAxis->numberPrecision()); xAxis2->setTickLabelType(xAxis->tickLabelType()); xAxis2->setDateTimeFormat(xAxis->dateTimeFormat()); xAxis2->setDateTimeSpec(xAxis->dateTimeSpec()); yAxis2->setRange(yAxis->range()); yAxis2->setRangeReversed(yAxis->rangeReversed()); yAxis2->setScaleType(yAxis->scaleType()); yAxis2->setScaleLogBase(yAxis->scaleLogBase()); yAxis2->setTicks(yAxis->ticks()); yAxis2->setAutoTickCount(yAxis->autoTickCount()); yAxis2->setSubTickCount(yAxis->subTickCount()); yAxis2->setAutoSubTicks(yAxis->autoSubTicks()); yAxis2->setTickStep(yAxis->tickStep()); yAxis2->setAutoTickStep(yAxis->autoTickStep()); yAxis2->setNumberFormat(yAxis->numberFormat()); yAxis2->setNumberPrecision(yAxis->numberPrecision()); yAxis2->setTickLabelType(yAxis->tickLabelType()); yAxis2->setDateTimeFormat(yAxis->dateTimeFormat()); yAxis2->setDateTimeSpec(yAxis->dateTimeSpec()); if (connectRanges) { connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); } } /*! Returns a list of all the plottables that are associated with this axis rect. A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see graphs, items */ QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const { // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries QList<QCPAbstractPlottable*> result; for (int i=0; i<mParentPlot->mPlottables.size(); ++i) { if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) result.append(mParentPlot->mPlottables.at(i)); } return result; } /*! Returns a list of all the graphs that are associated with this axis rect. A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see plottables, items */ QList<QCPGraph*> QCPAxisRect::graphs() const { // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries QList<QCPGraph*> result; for (int i=0; i<mParentPlot->mGraphs.size(); ++i) { if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) result.append(mParentPlot->mGraphs.at(i)); } return result; } /*! Returns a list of all the items that are associated with this axis rect. An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. \see plottables, graphs */ QList<QCPAbstractItem *> QCPAxisRect::items() const { // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries // and miss those items that have this axis rect as clipAxisRect. QList<QCPAbstractItem*> result; for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId) { if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) { result.append(mParentPlot->mItems.at(itemId)); continue; } QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions(); for (int posId=0; posId<positions.size(); ++posId) { if (positions.at(posId)->axisRect() == this || positions.at(posId)->keyAxis()->axisRect() == this || positions.at(posId)->valueAxis()->axisRect() == this) { result.append(mParentPlot->mItems.at(itemId)); break; } } } return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its QCPInsetLayout::update function. */ void QCPAxisRect::update(UpdatePhase phase) { QCPLayoutElement::update(phase); switch (phase) { case upPreparation: { QList<QCPAxis*> allAxes = axes(); for (int i=0; i<allAxes.size(); ++i) allAxes.at(i)->setupTickVectors(); break; } case upLayout: { mInsetLayout->setOuterRect(rect()); break; } default: break; } // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): mInsetLayout->update(phase); } /* inherits documentation from base class */ QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const { QList<QCPLayoutElement*> result; if (mInsetLayout) { result << mInsetLayout; if (recursive) result << mInsetLayout->elements(recursive); } return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { drawBackground(painter); } /*! Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! \overload Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. The brush will be drawn before (under) any background pixmap, which may be specified with \ref setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. \see setBackground, setBackgroundScaled */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the range drag axis of the \a orientation provided. \see setRangeDragAxes */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); } /*! Returns the range zoom axis of the \a orientation provided. \see setRangeZoomAxes */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); } /*! Returns the range zoom factor of the \a orientation provided. \see setRangeZoomFactor */ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); } /*! Sets which axis orientation may be range dragged by the user with mouse interaction. What orientation corresponds to which specific axis can be set with \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { mRangeDrag = orientations; } /*! Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { mRangeZoom = orientations; } /*! Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. \see setRangeZoomAxes */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { mRangeDragHorzAxis = horizontal; mRangeDragVertAxis = vertical; } /*! Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). \see setRangeDragAxes */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { mRangeZoomHorzAxis = horizontal; mRangeZoomVertAxis = vertical; } /*! Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal and which is vertical, can be set with \ref setRangeZoomAxes. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the same scrolling direction will zoom out. */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { mRangeZoomFactorHorz = horizontalFactor; mRangeZoomFactorVert = verticalFactor; } /*! \overload Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { mRangeZoomFactorHorz = factor; mRangeZoomFactorVert = factor; } /*! \internal Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was set. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { // draw background fill: if (mBackgroundBrush != Qt::NoBrush) painter->fillRect(mRect, mBackgroundBrush); // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mRect.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); } } } /*! \internal This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { const QList<QCPAxis*> axesList = mAxes.value(type); if (axesList.isEmpty()) return; bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false for (int i=1; i<axesList.size(); ++i) { int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin(); if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) { if (!isFirstVisible) offset += axesList.at(i)->tickLengthIn(); isFirstVisible = false; } axesList.at(i)->setOffset(offset); } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { if (!mAutoMargins.testFlag(side)) qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; updateAxesOffset(QCPAxis::marginSideToAxisType(side)); // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); if (axesList.size() > 0) return axesList.last()->offset() + axesList.last()->calculateMargin(); else return 0; } /*! \internal Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event) { mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release) if (event->buttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDragHorzAxis) mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); if (mRangeDragVertAxis) mDragStartVertRange = mRangeDragVertAxis.data()->range(); } } } /*! \internal Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. \see mousePressEvent, mouseReleaseEvent */ void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) { // Mouse range dragging interaction: if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDrag.testFlag(Qt::Horizontal)) { if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) { if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) { double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x()); rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff); } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) { double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); } } } if (mRangeDrag.testFlag(Qt::Vertical)) { if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) { if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) { double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y()); rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff); } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) { double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); } } } if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot { if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(); } } } /* inherits documentation from base class */ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of the scaling operation is the current cursor position inside the axis rect. The scaling factor is dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of the range zoom factor. This takes care of the wheel direction automatically, by inverting the factor, when the wheel step is negative (f^-1 = 1/f). */ void QCPAxisRect::wheelEvent(QWheelEvent *event) { // Mouse range zooming interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { if (mRangeZoom != 0) { double factor; double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually if (mRangeZoom.testFlag(Qt::Horizontal)) { factor = qPow(mRangeZoomFactorHorz, wheelSteps); if (mRangeZoomHorzAxis.data()) mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); } if (mRangeZoom.testFlag(Qt::Vertical)) { factor = qPow(mRangeZoomFactorVert, wheelSteps); if (mRangeZoomVertAxis.data()) mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); } mParentPlot->replot(); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) You inherit the following members you may use: <table> <tr> <td>QCPLegend *\b mParentLegend</td> <td>A pointer to the parent QCPLegend.</td> </tr><tr> <td>QFont \b mFont</td> <td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td> </tr> </table> */ /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end of documentation of signals */ /*! Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : QCPLayoutElement(parent->parentPlot()), mParentLegend(parent), mFont(parent->font()), mTextColor(parent->textColor()), mSelectedFont(parent->selectedFont()), mSelectedTextColor(parent->selectedTextColor()), mSelectable(true), mSelected(false) { setLayer(QLatin1String("legend")); setMargins(QMargins(8, 2, 8, 2)); } /*! Sets the default font of this specific legend item to \a font. \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { mFont = font; } /*! Sets the default text color of this specific legend item to \a color. \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this specific legend item is selected. It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (!mParentPlot) return -1; if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) return -1; if (mRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlottableLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend creates/removes legend items of this type in the default implementation. However, these functions may be reimplemented such that a different kind of legend item (e.g a direct subclass of QCPAbstractLegendItem) is used for that plottable. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the documentation of \ref QCPLegend. */ /*! Creates a new legend item associated with \a plottable. Once it's created, it can be added to the legend via \ref QCPLegend::addItem. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : QCPAbstractLegendItem(parent), mPlottable(plottable) { } /*! \internal Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { if (!mPlottable) return; painter->setFont(getFont()); painter->setPen(QPen(getTextColor())); QSizeF iconSize = mParentLegend->iconSize(); QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); QRectF iconRect(mRect.topLeft(), iconSize); int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); // draw icon: painter->save(); painter->setClipRect(iconRect, Qt::IntersectClip); mPlottable->drawLegendIcon(painter, iconRect); painter->restore(); // draw icon border: if (getIconBorderPen().style() != Qt::NoPen) { painter->setPen(getIconBorderPen()); painter->setBrush(Qt::NoBrush); painter->drawRect(iconRect); } } /*! \internal Calculates and returns the size of this item. This includes the icon, the text and the padding in between. */ QSize QCPPlottableLegendItem::minimumSizeHint() const { if (!mPlottable) return QSize(); QSize result(0, 0); QRect textRect; QFontMetrics fontMetrics(getFont()); QSize iconSize = mParentLegend->iconSize(); textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLegend //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLegend \brief Manages a legend inside a QCustomPlot. A legend is a small box somewhere in the plot which lists plottables with their name and icon. Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are placed in the grid layout of the legend. QCPLegend only adds an interface specialized for handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will only return the number of items with QCPAbstractLegendItems type). By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface. */ /* start of documentation of signals */ /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. \see setSelectedParts, setSelectableParts */ /* end of documentation of signals */ /*! Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. Note that by default, QCustomPlot already contains a legend ready to be used as QCustomPlot::legend */ QCPLegend::QCPLegend() { setRowSpacing(0); setColumnSpacing(10); setMargins(QMargins(2, 3, 2, 2)); setAntialiased(false); setIconSize(32, 18); setIconTextPadding(7); setSelectableParts(spLegendBox | spItems); setSelectedParts(spNone); setBorderPen(QPen(Qt::black)); setSelectedBorderPen(QPen(Qt::blue, 2)); setIconBorderPen(Qt::NoPen); setSelectedIconBorderPen(QPen(Qt::blue, 2)); setBrush(Qt::white); setSelectedBrush(Qt::white); setTextColor(Qt::black); setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { clearItems(); if (qobject_cast<QCustomPlot*>(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) mParentPlot->legendRemoved(this); } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { // check whether any legend elements selected, if yes, add spItems to return value bool hasSelectedItems = false; for (int i=0; i<itemCount(); ++i) { if (item(i) && item(i)->selected()) { hasSelectedItems = true; break; } } if (hasSelectedItems) return mSelectedParts | spItems; else return mSelectedParts & ~spItems; } /*! Sets the pen, the border of the entire legend is drawn with. */ void QCPLegend::setBorderPen(const QPen &pen) { mBorderPen = pen; } /*! Sets the brush of the legend background. */ void QCPLegend::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a font on all already existing legend items. \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { mFont = font; for (int i=0; i<itemCount(); ++i) { if (item(i)) item(i)->setFont(mFont); } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a color on all already existing legend items. \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { mTextColor = color; for (int i=0; i<itemCount(); ++i) { if (item(i)) item(i)->setTextColor(color); } } /*! Sets the size of legend icons. Legend items that draw an icon (e.g. a visual representation of the graph) will use this size by default. */ void QCPLegend::setIconSize(const QSize &size) { mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { mIconSize.setWidth(width); mIconSize.setHeight(height); } /*! Sets the horizontal space in pixels between the legend icon and the text next to it. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the name of the graph) will use this space by default. */ void QCPLegend::setIconTextPadding(int padding) { mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { SelectableParts newSelected = selected; mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed if (mSelectedParts != newSelected) { if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) { qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; newSelected &= ~spItems; } if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection { for (int i=0; i<itemCount(); ++i) { if (item(i)) item(i)->setSelected(false); } } mSelectedParts = newSelected; emit selectionChanged(mSelectedParts); } } /*! When the legend box is selected, this pen is used to draw the border instead of the normal pen set via \ref setBorderPen. \see setSelectedParts, setSelectableParts, setSelectedBrush */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { mSelectedBorderPen = pen; } /*! Sets the pen legend items will use to draw their icon borders, when they are selected. \see setSelectedParts, setSelectableParts, setSelectedFont */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { mSelectedIconBorderPen = pen; } /*! When the legend box is selected, this brush is used to draw the legend background instead of the normal brush set via \ref setBrush. \see setSelectedParts, setSelectableParts, setSelectedBorderPen */ void QCPLegend::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { mSelectedFont = font; for (int i=0; i<itemCount(); ++i) { if (item(i)) item(i)->setSelectedFont(font); } } /*! Sets the default text color that is used by legend items when they are selected. This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; for (int i=0; i<itemCount(); ++i) { if (item(i)) item(i)->setSelectedTextColor(color); } } /*! Returns the item with index \a i. \see itemCount */ QCPAbstractLegendItem *QCPLegend::item(int index) const { return qobject_cast<QCPAbstractLegendItem*>(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns 0. \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { for (int i=0; i<itemCount(); ++i) { if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i))) { if (pli->plottable() == plottable) return pli; } } return 0; } /*! Returns the number of items currently in the legend. \see item */ int QCPLegend::itemCount() const { return elementCount(); } /*! Returns whether the legend contains \a itm. */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { for (int i=0; i<itemCount(); ++i) { if (item == this->item(i)) return true; } return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { return itemWithPlottable(plottable); } /*! Adds \a item to the legend, if it's not present already. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. The legend takes ownership of the item. */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { if (!hasItem(item)) { return addElement(rowCount(), 0, item); } else return false; } /*! Removes the item with index \a index from the legend. Returns true, if successful. \see itemCount, clearItems */ bool QCPLegend::removeItem(int index) { if (QCPAbstractLegendItem *ali = item(index)) { bool success = remove(ali); simplify(); return success; } else return false; } /*! \overload Removes \a item from the legend. Returns true, if successful. \see clearItems */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { bool success = remove(item); simplify(); return success; } /*! Removes all items from the legend. */ void QCPLegend::clearItems() { for (int i=itemCount()-1; i>=0; --i) removeItem(i); } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. \see QCPAbstractLegendItem::setSelected, setSelectable */ QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const { QList<QCPAbstractLegendItem*> result; for (int i=0; i<itemCount(); ++i) { if (QCPAbstractLegendItem *ali = item(i)) { if (ali->selected()) result.append(ali); } } return result; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { // draw background rect: painter->setBrush(getBrush()); painter->setPen(getBorderPen()); painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) return -1; if (mOuterRect.contains(pos.toPoint())) { if (details) details->setValue(spLegendBox); return mParentPlot->selectionTolerance()*0.99; } return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) mSelectedParts = selectedParts(); // in case item selection has changed if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { mSelectedParts = selectedParts(); // in case item selection has changed if (mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(selectedParts() & ~spLegendBox); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlotTitle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlotTitle \brief A layout element displaying a plot title text The text may be specified with \ref setText, theformatting can be controlled with \ref setFont and \ref setTextColor. A plot title can be added as follows: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpplottitle-creation Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref QCustomPlot::titleDoubleClick signal. */ /* start documentation of signals */ /*! \fn void QCPPlotTitle::selectionChanged(bool selected) This signal is emitted when the selection state has changed to \a selected, either by user interaction or by a direct call to \ref setSelected. \see setSelected, setSelectable */ /* end documentation of signals */ /*! Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mFont(QFont(QLatin1String("sans serif"), 13*1.5, QFont::Bold)), mTextColor(Qt::black), mSelectedFont(QFont(QLatin1String("sans serif"), 13*1.6, QFont::Bold)), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { if (parentPlot) { setLayer(parentPlot->currentLayer()); mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold); mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold); } setMargins(QMargins(5, 5, 5, 0)); } /*! \overload Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : QCPLayoutElement(parentPlot), mText(text), mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), mTextColor(Qt::black), mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { setLayer(QLatin1String("axes")); setMargins(QMargins(5, 5, 5, 0)); } /*! Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". \see setFont, setTextColor */ void QCPPlotTitle::setText(const QString &text) { mText = text; } /*! Sets the \a font of the title text. \see setTextColor, setSelectedFont */ void QCPPlotTitle::setFont(const QFont &font) { mFont = font; } /*! Sets the \a color of the title text. \see setFont, setSelectedTextColor */ void QCPPlotTitle::setTextColor(const QColor &color) { mTextColor = color; } /*! Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). \see setFont */ void QCPPlotTitle::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). \see setTextColor */ void QCPPlotTitle::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether the user may select this plot title to \a selectable. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed programmatically via \ref setSelected. */ void QCPPlotTitle::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets the selection state of this plot title to \a selected. If the selection has changed, \ref selectionChanged is emitted. Note that this function can change the selection state independently of the current \ref setSelectable state. */ void QCPPlotTitle::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); } /* inherits documentation from base class */ void QCPPlotTitle::draw(QCPPainter *painter) { painter->setFont(mainFont()); painter->setPen(QPen(mainTextColor())); painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPPlotTitle::minimumSizeHint() const { QFontMetrics metrics(mFont); QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); result.rwidth() += mMargins.left() + mMargins.right(); result.rheight() += mMargins.top() + mMargins.bottom(); return result; } /* inherits documentation from base class */ QSize QCPPlotTitle::maximumSizeHint() const { QFontMetrics metrics(mFont); QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); result.rheight() += mMargins.top() + mMargins.bottom(); result.setWidth(QWIDGETSIZE_MAX); return result; } /* inherits documentation from base class */ void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (mTextBoundingRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /*! \internal Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to <tt>true</tt>, else mFont is returned. */ QFont QCPPlotTitle::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to <tt>true</tt>, else mTextColor is returned. */ QColor QCPPlotTitle::mainTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScale //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. To have finer control over the number display and axis behaviour, you can directly access the \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if you want to change the number of automatically generated ticks, call \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-autotickcount Placing a color scale next to the main axis rect works like with any other layout element: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>. */ /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ /* end documentation of signals */ /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); This signal is emitted when the data range changes. \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the data scale type changes. \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); This signal is emitted when the gradient changes. \see setGradient */ /* end documentation of signals */ /*! Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight mDataScaleType(QCPAxis::stLinear), mBarWidth(20), mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) setType(QCPAxis::atRight); setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return QString(); } return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. Note that after setting \a type to a different value, the axis returned by \ref axis() will be a different one. The new axis will adopt the following properties from the previous axis: The range, scale type, log base and label. */ void QCPColorScale::setType(QCPAxis::AxisType type) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (mType != type) { mType = type; QCPRange rangeTransfer(0, 6); double logBaseTransfer = 10; QString labelTransfer; // revert some settings on old axis: if (mColorAxis) { rangeTransfer = mColorAxis.data()->range(); labelTransfer = mColorAxis.data()->label(); logBaseTransfer = mColorAxis.data()->scaleLogBase(); mColorAxis.data()->setLabel(QString()); disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; foreach (QCPAxis::AxisType atype, allAxisTypes) { mAxisRect.data()->axis(atype)->setTicks(atype == mType); mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); } // set new mColorAxis pointer: mColorAxis = mAxisRect.data()->axis(mType); // transfer settings to new axis: mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa) mColorAxis.data()->setLabel(labelTransfer); mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0, QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0); } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { mDataRange = dataRange; if (mColorAxis) mColorAxis.data()->setRange(mDataRange); emit dataRangeChanged(mDataRange); } } /*! Sets the scale type of the color scale, i.e. whether values are linearly associated with colors or logarithmically. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; if (mColorAxis) mColorAxis.data()->setScaleType(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); emit dataScaleTypeChanged(mDataScaleType); } } /*! Sets the color gradient that will be used to represent data values. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; if (mAxisRect) mAxisRect.data()->mGradientImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on the internal \ref axis. */ void QCPColorScale::setLabel(const QString &str) { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return; } mColorAxis.data()->setLabel(str); } /*! Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed will have. */ void QCPColorScale::setBarWidth(int width) { mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); else mAxisRect.data()->setRangeDrag(0); } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); else mAxisRect.data()->setRangeZoom(0); } /*! Returns a list of all the color maps associated with this color scale. */ QList<QCPColorMap*> QCPColorScale::colorMaps() const { QList<QCPColorMap*> result; for (int i=0; i<mParentPlot->plottableCount(); ++i) { if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i))) if (cm->colorScale() == this) result.append(cm); } return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. \see setDataRange */ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) { QList<QCPColorMap*> maps = colorMaps(); QCPRange newRange; bool haveRange = false; int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) if (mDataScaleType == QCPAxis::stLogarithmic) sign = (mDataRange.upper < 0 ? -1 : 1); for (int i=0; i<maps.size(); ++i) { if (!maps.at(i)->realVisibility() && onlyVisibleMaps) continue; QCPRange mapRange; if (maps.at(i)->colorScale() == this) { bool currentFoundRange = true; mapRange = maps.at(i)->data()->dataBounds(); if (sign == 1) { if (mapRange.lower <= 0 && mapRange.upper > 0) mapRange.lower = mapRange.upper*1e-3; else if (mapRange.lower <= 0 && mapRange.upper <= 0) currentFoundRange = false; } else if (sign == -1) { if (mapRange.upper >= 0 && mapRange.lower < 0) mapRange.upper = mapRange.lower*1e-3; else if (mapRange.upper >= 0 && mapRange.lower >= 0) currentFoundRange = false; } if (currentFoundRange) { if (!haveRange) newRange = mapRange; else newRange.expand(mapRange); haveRange = true; } } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mDataScaleType == QCPAxis::stLinear) { newRange.lower = center-mDataRange.size()/2.0; newRange.upper = center+mDataRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); } } setDataRange(newRange); } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { QCPLayoutElement::update(phase); if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->update(phase); switch (phase) { case upMargins: { if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); } else { setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); } break; } case upLayout: { mAxisRect.data()->setOuterRect(rect()); break; } default: break; } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mousePressEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseMoveEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseReleaseEvent(event); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScaleAxisRectPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScaleAxisRectPrivate \internal \brief An axis rect subclass for use in a QCPColorScale This is a private class and not part of the public QCustomPlot interface. It provides the axis rect functionality for the QCPColorScale class. */ /*! Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : QCPAxisRect(parentColorScale->parentPlot(), true), mParentColorScale(parentColorScale), mGradientImageInvalidated(true) { setParentLayerable(parentColorScale); setMinimumMargins(QMargins(0, 0, 0, 0)); QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { axis(type)->setVisible(true); axis(type)->grid()->setVisible(false); axis(type)->setPadding(0); connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); } connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); // make layer transfers of color scale transfer to axis rect and axes // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); foreach (QCPAxis::AxisType type, allAxisTypes) connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); } /*! \internal Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. */ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) { if (mGradientImageInvalidated) updateGradientImage(); bool mirrorHorz = false; bool mirrorVert = false; if (mParentColorScale->mColorAxis) { mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); } painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); QCPAxisRect::draw(painter); } /*! \internal Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to generate a gradient image. This gradient image will be used in the \ref draw method. */ void QCPColorScaleAxisRectPrivate::updateGradientImage() { if (rect().isEmpty()) return; int n = mParentColorScale->mGradient.levelCount(); int w, h; QVector<double> data(n); for (int i=0; i<n; ++i) data[i] = i; if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { w = n; h = rect().height(); mGradientImage = QImage(w, h, QImage::Format_RGB32); QVector<QRgb*> pixels; for (int y=0; y<h; ++y) pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y))); mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); for (int y=1; y<h; ++y) memcpy(pixels.at(y), pixels.first(), n*sizeof(QRgb)); } else { w = rect().width(); h = n; mGradientImage = QImage(w, h, QImage::Format_RGB32); for (int y=0; y<h; ++y) { QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)); const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); for (int x=0; x<w; ++x) pixels[x] = lineColor; } } mGradientImageInvalidated = false; } /*! \internal This slot is connected to the selectionChanged signals of the four axes in the constructor. It synchronizes the selection state of the axes. */ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts) { // axis bases of four axes shall always (de-)selected synchronously: QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectedParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); else axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); } } } /*! \internal This slot is connected to the selectableChanged signals of the four axes in the constructor. It synchronizes the selectability of the axes. */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { // synchronize axis base selectability: QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectableParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); else axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPData \brief Holds the data of one single data point for QCPGraph. The container for storing multiple data points is \ref QCPDataMap. The stored data is: \li \a key: coordinate on the key axis of this data point \li \a value: coordinate on the value axis of this data point \li \a keyErrorMinus: negative error in the key dimension (for error bars) \li \a keyErrorPlus: positive error in the key dimension (for error bars) \li \a valueErrorMinus: negative error in the value dimension (for error bars) \li \a valueErrorPlus: positive error in the value dimension (for error bars) \see QCPDataMap */ /*! Constructs a data point with key, value and all errors set to zero. */ QCPData::QCPData() : key(0), value(0), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0) { } /*! Constructs a data point with the specified \a key and \a value. All errors are set to zero. */ QCPData::QCPData(double key, double value) : key(key), value(value), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGraph //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGraph \brief A plottable representing a graph in a plot. \image html QCPGraph.png Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be accessed via QCustomPlot::graph. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. Graphs are used to display single-valued data. Single-valued means that there should only be one data point per unique key coordinate. In other words, the graph can't have \a loops. If you do want to plot non-single-valued curves, rather use the QCPCurve plottable. Gaps in the graph line can be created by adding data points with NaN as value (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be separated. \section appearance Changing the appearance The appearance of the graph is mainly determined by the line style, scatter style, brush and pen of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). \subsection filling Filling under or between graphs QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. \see QCustomPlot::addGraph, QCustomPlot::graph */ /* start of documentation of inline functions */ /*! \fn QCPDataMap *QCPGraph::data() const Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods, in certain situations. */ /* end of documentation of inline functions */ /*! Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. */ QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPDataMap; setPen(QPen(Qt::blue, 0)); setErrorPen(QPen(Qt::black)); setBrush(Qt::NoBrush); setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); setSelectedBrush(Qt::NoBrush); setLineStyle(lsLine); setErrorType(etNone); setErrorBarSize(6); setErrorBarSkipSymbol(true); setChannelFillGraph(0); setAdaptiveSampling(true); } QCPGraph::~QCPGraph() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the graph takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. */ void QCPGraph::setData(QCPDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; mData->insertMulti(newData.key, newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical value error of the data points are set to the values in \a valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueError.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; newData.valueErrorMinus = valueError[i]; newData.valueErrorPlus = valueError[i]; mData->insertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative value error of the data points are set to the values in \a valueErrorMinus, the positive value error to \a valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueErrorMinus.size()); n = qMin(n, valueErrorPlus.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; newData.valueErrorMinus = valueErrorMinus[i]; newData.valueErrorPlus = valueErrorPlus[i]; mData->insertMulti(key[i], newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical key error of the data points are set to the values in \a keyError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, keyError.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; newData.keyErrorMinus = keyError[i]; newData.keyErrorPlus = keyError[i]; mData->insertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative key error of the data points are set to the values in \a keyErrorMinus, the positive key error to \a keyErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, keyErrorMinus.size()); n = qMin(n, keyErrorPlus.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; newData.keyErrorMinus = keyErrorMinus[i]; newData.keyErrorPlus = keyErrorPlus[i]; mData->insertMulti(key[i], newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueError.size()); n = qMin(n, keyError.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; newData.keyErrorMinus = keyError[i]; newData.keyErrorPlus = keyError[i]; newData.valueErrorMinus = valueError[i]; newData.valueErrorPlus = valueError[i]; mData->insertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueErrorMinus.size()); n = qMin(n, valueErrorPlus.size()); n = qMin(n, keyErrorMinus.size()); n = qMin(n, keyErrorPlus.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; newData.keyErrorMinus = keyErrorMinus[i]; newData.keyErrorPlus = keyErrorPlus[i]; newData.valueErrorMinus = valueErrorMinus[i]; newData.valueErrorPlus = valueErrorPlus[i]; mData->insertMulti(key[i], newData); } } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data point. If you set \a errorType to something other than \ref etNone, make sure to actually pass error data via the specific setData functions along with the data points (e.g. \ref setDataValueError, \ref setDataKeyError, \ref setDataBothError). \see ErrorType */ void QCPGraph::setErrorType(ErrorType errorType) { mErrorType = errorType; } /*! Sets the pen with which the error bars will be drawn. \see setErrorBarSize, setErrorType */ void QCPGraph::setErrorPen(const QPen &pen) { mErrorPen = pen; } /*! Sets the width of the handles at both ends of an error bar in pixels. */ void QCPGraph::setErrorBarSize(double size) { mErrorBarSize = size; } /*! If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but leave some free space around the symbol. This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size of the area to leave blank. So when drawing Pixmaps as scatter points (\ref QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the size of the Pixmap, if the error bars should leave gaps to its boundaries. \ref setErrorType, setErrorBarSize, setScatterStyle */ void QCPGraph::setErrorBarSkipSymbol(bool enabled) { mErrorBarSkipSymbol = enabled; } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. \see setBrush */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { // prevent setting channel target to this graph itself: if (targetGraph == this) { qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; mChannelFillGraph = 0; return; } // prevent setting channel target to a graph not in the plot: if (targetGraph && targetGraph->mParentPlot != mParentPlot) { qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; mChannelFillGraph = 0; return; } mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is because scatter plots inherently need more data points to be preserved in order to still resemble the original, non-adaptive-sampling plot. As shown above, the results still aren't quite identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled back to true afterwards. */ void QCPGraph::setAdaptiveSampling(bool enabled) { mAdaptiveSampling = enabled; } /*! Adds the provided data points in \a dataMap to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QCPDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QCPData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(double key, double value) { QCPData newData; newData.key = key; newData.value = value; mData->insertMulti(newData.key, newData); } /*! \overload Adds the provided data points as \a key and \a value pairs to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values) { int n = qMin(keys.size(), values.size()); QCPData newData; for (int i=0; i<n; ++i) { newData.key = keys[i]; newData.value = values[i]; mData->insertMulti(newData.key, newData); } } /*! Removes all data points with keys smaller than \a key. \see addData, clearData */ void QCPGraph::removeDataBefore(double key) { QCPDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with keys greater than \a key. \see addData, clearData */ void QCPGraph::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPGraph::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPDataMap::iterator it = mData->upperBound(fromKey); QCPDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPGraph::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPGraph::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && !mSelectable) || mData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) return pointDistance(pos); else return -1; } /*! \overload Allows to define whether error bars are taken into consideration when determining the new axis range. \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const { rescaleKeyAxis(onlyEnlarge, includeErrorBars); rescaleValueAxis(onlyEnlarge, includeErrorBars); } /*! \overload Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration when determining the new axis range. \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis */ void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const { // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change // that getKeyRange is passed the includeErrorBars value. if (mData->isEmpty()) return; QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } SignDomain signDomain = sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); if (foundRange) { if (onlyEnlarge) { if (keyAxis->range().lower < newRange.lower) newRange.lower = keyAxis->range().lower; if (keyAxis->range().upper > newRange.upper) newRange.upper = keyAxis->range().upper; } keyAxis->setRange(newRange); } } /*! \overload Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration when determining the new axis range. \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis */ void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const { // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change // is that getValueRange is passed the includeErrorBars value. if (mData->isEmpty()) return; QCPAxis *valueAxis = mValueAxis.data(); if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } SignDomain signDomain = sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); if (foundRange) { if (onlyEnlarge) { if (valueAxis->range().lower < newRange.lower) newRange.lower = valueAxis->range().lower; if (valueAxis->range().upper > newRange.upper) newRange.upper = valueAxis->range().upper; } valueAxis->setRange(newRange); } } /* inherits documentation from base class */ void QCPGraph::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return; if (mLineStyle == lsNone && mScatterStyle.isNone()) return; // allocate line and (if necessary) point vectors: QVector<QPointF> *lineData = new QVector<QPointF>; QVector<QCPData> *scatterData = 0; if (!mScatterStyle.isNone()) scatterData = new QVector<QCPData>; // fill vectors with data appropriate to plot style: getPlotData(lineData, scatterData); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (QCP::isInvalidData(it.value().key, it.value().value) || QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); } #endif // draw fill of graph: if (mLineStyle != lsNone) drawFill(painter, lineData); // draw line: if (mLineStyle == lsImpulse) drawImpulsePlot(painter, lineData); else if (mLineStyle != lsNone) drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot // draw scatters: if (scatterData) drawScatterPlot(painter, scatterData); // free allocated line and point vectors: delete lineData; if (scatterData) delete scatterData; } /* inherits documentation from base class */ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal This function branches out to the line style specific "get(...)PlotData" functions, according to the line style of the graph. \a lineData will be filled with raw points that will be drawn with the according draw functions, e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data points, since for step plots for example, additional points are needed for drawing lines that make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left untouched. \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped. \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData, getStepCenterPlotData, getImpulsePlotData */ void QCPGraph::getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const { switch(mLineStyle) { case lsNone: getScatterPlotData(scatterData); break; case lsLine: getLinePlotData(lineData, scatterData); break; case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; case lsStepRight: getStepRightPlotData(lineData, scatterData); break; case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; case lsImpulse: getImpulsePlotData(lineData, scatterData); break; } } /*! \internal If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone, this function serves at providing the visible data points in \a scatterData, so the \ref drawScatterPlot function can draw the scatter points accordingly. If line style is not \ref lsNone, this function is not called and the data for the scatter points are (if needed) calculated inside the corresponding other "get(...)PlotData" functions. \see drawScatterPlot */ void QCPGraph::getScatterPlotData(QVector<QCPData> *scatterData) const { getPreparedData(0, scatterData); } /*! \internal Places the raw data points needed for a normal linearly connected graph in \a linePixelData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } QVector<QCPData> lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()); // transform lineData points to pixels: if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; i<lineData.size(); ++i) { (*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value)); (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); } } else // key axis is horizontal { for (int i=0; i<lineData.size(); ++i) { (*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key)); (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); } } } /*! \internal Places the raw data points needed for a step plot with left oriented steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector<QCPData> lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; for (int i=0; i<lineData.size(); ++i) { key = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(lastValue); (*linePixelData)[i*2+0].setY(key); lastValue = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+1].setX(lastValue); (*linePixelData)[i*2+1].setY(key); } } else // key axis is horizontal { double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; for (int i=0; i<lineData.size(); ++i) { key = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(lastValue); lastValue = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+1].setX(key); (*linePixelData)[i*2+1].setY(lastValue); } } } /*! \internal Places the raw data points needed for a step plot with right oriented steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector<QCPData> lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(lineData.first().key); double value; for (int i=0; i<lineData.size(); ++i) { value = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+0].setX(value); (*linePixelData)[i*2+0].setY(lastKey); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+1].setX(value); (*linePixelData)[i*2+1].setY(lastKey); } } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(lineData.first().key); double value; for (int i=0; i<lineData.size(); ++i) { value = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+0].setX(lastKey); (*linePixelData)[i*2+0].setY(value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+1].setX(lastKey); (*linePixelData)[i*2+1].setY(value); } } } /*! \internal Places the raw data points needed for a step plot with centered steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector<QCPData> lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(lineData.first().key); double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; (*linePixelData)[0].setX(lastValue); (*linePixelData)[0].setY(lastKey); for (int i=1; i<lineData.size(); ++i) { key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5; (*linePixelData)[i*2-1].setX(lastValue); (*linePixelData)[i*2-1].setY(key); lastValue = valueAxis->coordToPixel(lineData.at(i).value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(lastValue); (*linePixelData)[i*2+0].setY(key); } (*linePixelData)[lineData.size()*2-1].setX(lastValue); (*linePixelData)[lineData.size()*2-1].setY(lastKey); } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(lineData.first().key); double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; (*linePixelData)[0].setX(lastKey); (*linePixelData)[0].setY(lastValue); for (int i=1; i<lineData.size(); ++i) { key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5; (*linePixelData)[i*2-1].setX(key); (*linePixelData)[i*2-1].setY(lastValue); lastValue = valueAxis->coordToPixel(lineData.at(i).value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(lastValue); } (*linePixelData)[lineData.size()*2-1].setX(lastKey); (*linePixelData)[lineData.size()*2-1].setY(lastValue); } } /*! \internal Places the raw data points needed for an impulse plot in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawImpulsePlot */ void QCPGraph::getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } QVector<QCPData> lineData; getPreparedData(&lineData, scatterData); linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill // transform lineData points to pixels: if (keyAxis->orientation() == Qt::Vertical) { double zeroPointX = valueAxis->coordToPixel(0); double key; for (int i=0; i<lineData.size(); ++i) { key = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(zeroPointX); (*linePixelData)[i*2+0].setY(key); (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value)); (*linePixelData)[i*2+1].setY(key); } } else // key axis is horizontal { double zeroPointY = valueAxis->coordToPixel(0); double key; for (int i=0; i<lineData.size(); ++i) { key = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(zeroPointY); (*linePixelData)[i*2+1].setX(key); (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value)); } } } /*! \internal Draws the fill of the graph with the specified brush. If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by \ref removeFillBasePoints after the fill drawing is done). If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the more complex polygon is calculated with the \ref getChannelFillPolygon function. \see drawLinePlot */ void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const { if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return; applyFillAntialiasingHint(painter); if (!mChannelFillGraph) { // draw base fill under graph, fill goes all the way to the zero-value-line: addFillBasePoints(lineData); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(QPolygonF(*lineData)); removeFillBasePoints(lineData); } else { // draw channel fill between this graph and mChannelFillGraph: painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(getChannelFillPolygon(lineData)); } } /*! \internal Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent of the line style and are always drawn if the scatter style's shape is not \ref QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData" functions, together with the (line style dependent) line data. \see drawLinePlot, drawImpulsePlot */ void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // draw error bars: if (mErrorType != etNone) { applyErrorBarsAntialiasingHint(painter); painter->setPen(mErrorPen); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; i<scatterData->size(); ++i) drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); } else { for (int i=0; i<scatterData->size(); ++i) drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); } } // draw scatter point symbols: applyScattersAntialiasingHint(painter); mScatterStyle.applyTo(painter, mPen); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; i<scatterData->size(); ++i) if (!qIsNaN(scatterData->at(i).value)) mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); } else { for (int i=0; i<scatterData->size(); ++i) if (!qIsNaN(scatterData->at(i).value)) mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); } } /*! \internal Draws line graphs from the provided data. It connects all points in \a lineData, which was created by one of the "get(...)PlotData" functions for line styles that require simple line connections between the point vector they create. These are for example \ref getLinePlotData, \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. \see drawScatterPlot, drawImpulsePlot */ void QCPGraph::drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const { // draw line of graph: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); /* Draws polyline in batches, currently not used: int p = 0; while (p < lineData->size()) { int batch = qMin(25, lineData->size()-p); if (p != 0) { ++batch; --p; // to draw the connection lines between two batches } painter->drawPolyline(lineData->constData()+p, batch); p += batch; } */ // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { int i = 0; bool lastIsNan = false; const int lineDataSize = lineData->size(); while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN ++i; ++i; // because drawing works in 1 point retrospect while (i < lineDataSize) { if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { if (!lastIsNan) painter->drawLine(lineData->at(i-1), lineData->at(i)); else lastIsNan = false; } else lastIsNan = true; ++i; } } else { int segmentStart = 0; int i = 0; const int lineDataSize = lineData->size(); while (i < lineDataSize) { if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()) || qIsInf(lineData->at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block { painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point segmentStart = i+1; } ++i; } // draw last segment: painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); } } } /*! \internal Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was created by \ref getImpulsePlotData. \see drawScatterPlot, drawLinePlot */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const { // draw impulses: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); QPen pen = mainPen(); pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawLines(*lineData); } } /*! \internal Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point densities. 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a scatterData should be 0 to prevent unnecessary calculations. This method is used by the various "get(...)PlotData" methods to get the basic working set of data. */ void QCPGraph::getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // get visible data range: QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return; // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: int maxCount = std::numeric_limits<int>::max(); if (mAdaptiveSampling) { int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); maxCount = 2*keyPixelSpan+2; } int dataCount = countDataInBounds(lower, upper, maxCount); if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average { if (lineData) { QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator currentIntervalFirstPoint = it; int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); double lastIntervalEndKey = currentIntervalStartKey; double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != upperEnd) { if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary { if (it.value().value < minValue) minValue = it.value().value; else if (it.value().value > maxValue) maxValue = it.value().value; ++intervalDataCount; } else // new pixel interval started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value)); } else lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); lastIntervalEndKey = (it-1).value().key; minValue = it.value().value; maxValue = it.value().value; currentIntervalFirstPoint = it; currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); } else lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); } if (scatterData) { double valueMaxRange = valueAxis->range().upper; double valueMinRange = valueAxis->range().lower; QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator minValueIt = it; QCPDataMap::const_iterator maxValueIt = it; QCPDataMap::const_iterator currentIntervalStart = it; int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != upperEnd) { if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary { if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { minValue = it.value().value; minValueIt = it; } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { maxValue = it.value().value; maxValueIt = it; } ++intervalDataCount; } else // new pixel started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPDataMap::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) scatterData->append(intervalIt.value()); ++c; ++intervalIt; } } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) scatterData->append(currentIntervalStart.value()); minValue = it.value().value; maxValue = it.value().value; currentIntervalStart = it; currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPDataMap::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) scatterData->append(intervalIt.value()); ++c; ++intervalIt; } } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) scatterData->append(currentIntervalStart.value()); } } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters { QVector<QCPData> *dataVector = 0; if (lineData) dataVector = lineData; else if (scatterData) dataVector = scatterData; if (dataVector) { QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; dataVector->reserve(dataCount+2); // +2 for possible fill end points while (it != upperEnd) { dataVector->append(it.value()); ++it; } } if (lineData && scatterData) *scatterData = *dataVector; } } /*! \internal called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data point. \a x and \a y pixel positions of the data point are passed since they are already known in pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a data is therefore only used for the errors, not key and value. */ void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const { if (qIsNaN(data.value)) return; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } double a, b; // positions of error bar bounds in pixels double barWidthHalf = mErrorBarSize*0.5; double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true if (keyAxis->orientation() == Qt::Vertical) { // draw key error vertically and value error horizontally if (mErrorType == etKey || mErrorType == etBoth) { a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); if (keyAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); if (y-b > skipSymbolMargin) painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); } else painter->drawLine(QLineF(x, a, x, b)); // draw handles: painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); } if (mErrorType == etValue || mErrorType == etBoth) { a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); if (valueAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); if (b-x > skipSymbolMargin) painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); } else painter->drawLine(QLineF(a, y, b, y)); // draw handles: painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); } } else // mKeyAxis->orientation() is Qt::Horizontal { // draw value error vertically and key error horizontally if (mErrorType == etKey || mErrorType == etBoth) { a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); if (keyAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); if (b-x > skipSymbolMargin) painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); } else painter->drawLine(QLineF(a, y, b, y)); // draw handles: painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); } if (mErrorType == etValue || mErrorType == etBoth) { a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); if (valueAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); if (y-b > skipSymbolMargin) painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); } else painter->drawLine(QLineF(x, a, x, b)); // draw handles: painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); } } } /*! \internal called by \ref getPreparedData to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie just outside of the visible range. if the graph contains no data, both \a lower and \a upper point to constEnd. */ void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upper = mData->constEnd(); return; } // get visible data range as QMap iterators QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn } /*! \internal Counts the number of data points between \a lower and \a upper (including them), up to a maximum of \a maxCount. This function is used by \ref getPreparedData to determine whether adaptive sampling shall be used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points only needs to be done until \a maxCount is reached, which should be set to the number of data points at which adaptive sampling sets in. */ int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const { if (upper == mData->constEnd() && lower == mData->constEnd()) return 0; QCPDataMap::const_iterator it = lower; int count = 1; while (it != upper && count < maxCount) { ++it; ++count; } return count; } /*! \internal The line data vector generated by e.g. getLinePlotData contains only the line that connects the data points. If the graph needs to be filled, two additional points need to be added at the value-zero-line in the lower and upper key positions of the graph. This function calculates these points and adds them to the end of \a lineData. Since the fill is typically drawn before the line stroke, these added points need to be removed again after the fill is done, with the removeFillBasePoints function. The expanding of \a lineData by two points will not cause unnecessary memory reallocations, because the data vector generation functions (getLinePlotData etc.) reserve two extra points when they allocate memory for \a lineData. \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::addFillBasePoints(QVector<QPointF> *lineData) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; } if (lineData->isEmpty()) return; // append points that close the polygon fill at the key axis: if (mKeyAxis.data()->orientation() == Qt::Vertical) { *lineData << upperFillBasePoint(lineData->last().y()); *lineData << lowerFillBasePoint(lineData->first().y()); } else { *lineData << upperFillBasePoint(lineData->last().x()); *lineData << lowerFillBasePoint(lineData->first().x()); } } /*! \internal removes the two points from \a lineData that were added by \ref addFillBasePoints. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const { if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; } if (lineData->isEmpty()) return; lineData->remove(lineData->size()-2, 2); } /*! \internal called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned point, respectively. \see upperFillBasePoint, addFillBasePoints */ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } QPointF point; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->axisType() == QCPAxis::atLeft) { point.setX(valueAxis->coordToPixel(0)); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atRight) { point.setX(valueAxis->coordToPixel(0)); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atTop) { point.setX(lowerKey); point.setY(valueAxis->coordToPixel(0)); } else if (keyAxis->axisType() == QCPAxis::atBottom) { point.setX(lowerKey); point.setY(valueAxis->coordToPixel(0)); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value zero so we just fill all the way // to the axis which is in the direction towards zero if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setX(keyAxis->axisRect()->right()); else point.setX(keyAxis->axisRect()->left()); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { point.setX(lowerKey); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setY(keyAxis->axisRect()->top()); else point.setY(keyAxis->axisRect()->bottom()); } } return point; } /*! \internal called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned point, respectively. \see lowerFillBasePoint, addFillBasePoints */ QPointF QCPGraph::upperFillBasePoint(double upperKey) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } QPointF point; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->axisType() == QCPAxis::atLeft) { point.setX(valueAxis->coordToPixel(0)); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atRight) { point.setX(valueAxis->coordToPixel(0)); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atTop) { point.setX(upperKey); point.setY(valueAxis->coordToPixel(0)); } else if (keyAxis->axisType() == QCPAxis::atBottom) { point.setX(upperKey); point.setY(valueAxis->coordToPixel(0)); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value 0 so we just fill all the way // to the axis which is in the direction towards 0 if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setX(keyAxis->axisRect()->right()); else point.setX(keyAxis->axisRect()->left()); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { point.setX(upperKey); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setY(keyAxis->axisRect()->top()); else point.setY(keyAxis->axisRect()->bottom()); } } return point; } /*! \internal Generates the polygon needed for drawing channel fills between this graph (data passed via \a lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref getPlotData function). May return an empty polygon if the key ranges have no overlap or fill target graph and this graph don't have same orientation (i.e. both key axes horizontal or both key axes vertical). For increased performance (due to implicit sharing), keep the returned QPolygonF const. */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData) const { if (!mChannelFillGraph) return QPolygonF(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) if (lineData->isEmpty()) return QPolygonF(); QVector<QPointF> otherData; mChannelFillGraph.data()->getPlotData(&otherData, 0); if (otherData.isEmpty()) return QPolygonF(); QVector<QPointF> thisData; thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function for (int i=0; i<lineData->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() thisData << lineData->at(i); // pointers to be able to swap them, depending which data range needs cropping: QVector<QPointF> *staticData = &thisData; QVector<QPointF> *croppedData = &otherData; // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): if (keyAxis->orientation() == Qt::Horizontal) { // x is key // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: if (staticData->first().x() > staticData->last().x()) { int size = staticData->size(); for (int i=0; i<size/2; ++i) qSwap((*staticData)[i], (*staticData)[size-1-i]); } if (croppedData->first().x() > croppedData->last().x()) { int size = croppedData->size(); for (int i=0; i<size/2; ++i) qSwap((*croppedData)[i], (*croppedData)[size-1-i]); } // crop lower bound: if (staticData->first().x() < croppedData->first().x()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexBelowX(croppedData, staticData->first().x()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (croppedData->at(1).x()-croppedData->at(0).x() != 0) slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); else slope = 0; (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); (*croppedData)[0].setX(staticData->first().x()); // crop upper bound: if (staticData->last().x() > croppedData->last().x()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexAboveX(croppedData, staticData->last().x()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); else slope = 0; (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); (*croppedData)[li].setX(staticData->last().x()); } else // mKeyAxis->orientation() == Qt::Vertical { // y is key // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: if (staticData->first().y() < staticData->last().y()) { int size = staticData->size(); for (int i=0; i<size/2; ++i) qSwap((*staticData)[i], (*staticData)[size-1-i]); } if (croppedData->first().y() < croppedData->last().y()) { int size = croppedData->size(); for (int i=0; i<size/2; ++i) qSwap((*croppedData)[i], (*croppedData)[size-1-i]); } // crop lower bound: if (staticData->first().y() > croppedData->first().y()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexAboveY(croppedData, staticData->first().y()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); else slope = 0; (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); (*croppedData)[0].setY(staticData->first().y()); // crop upper bound: if (staticData->last().y() < croppedData->last().y()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexBelowY(croppedData, staticData->last().y()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); else slope = 0; (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); (*croppedData)[li].setY(staticData->last().y()); } // return joined: for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted thisData << otherData.at(i); return QPolygonF(thisData); } /*! \internal Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).x() < x) { if (i<data->size()-1) return i+1; else return data->size()-1; } } return -1; } /*! \internal Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const { for (int i=0; i<data->size(); ++i) { if (data->at(i).x() > x) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const { for (int i=0; i<data->size(); ++i) { if (data->at(i).y() < y) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in \ref selectTest. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0. */ double QCPGraph::pointDistance(const QPointF &pixelPoint) const { if (mData->isEmpty()) return -1.0; if (mLineStyle == lsNone && mScatterStyle.isNone()) return -1.0; // calculate minimum distances to graph representation: if (mLineStyle == lsNone) { // no line displayed, only calculate distance to scatter points: QVector<QCPData> scatterData; getScatterPlotData(&scatterData); if (scatterData.size() > 0) { double minDistSqr = std::numeric_limits<double>::max(); for (int i=0; i<scatterData.size(); ++i) { double currentDistSqr = QVector2D(coordsToPixels(scatterData.at(i).key, scatterData.at(i).value)-pixelPoint).lengthSquared(); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } return qSqrt(minDistSqr); } else // no data available in view to calculate distance to return -1.0; } else { // line displayed, calculate distance to line segments: QVector<QPointF> lineData; getPlotData(&lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here if (lineData.size() > 1) // at least one line segment, compare distance to line segments { double minDistSqr = std::numeric_limits<double>::max(); if (mLineStyle == lsImpulse) { // impulse plot differs from other line styles in that the lineData points are only pairwise connected: for (int i=0; i<lineData.size()-1; i+=2) // iterate pairs { double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } else { // all other line plots (line and step) connect points directly: for (int i=0; i<lineData.size()-1; ++i) { double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } return qSqrt(minDistSqr); } else if (lineData.size() > 0) // only single data point, calculate distance to that point { return QVector2D(lineData.at(0)-pixelPoint).length(); } else // no data available in view to calculate distance to return -1.0; } } /*! \internal Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis (since keys are ordered ascending). Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).y() > y) { if (i<data->size()-1) return i+1; else return data->size()-1; } } return -1; } /* inherits documentation from base class */ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { // just call the specialized version which takes an additional argument whether error bars // should also be taken into consideration for range calculation. We set this to true here. return getKeyRange(foundRange, inSignDomain, true); } /* inherits documentation from base class */ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const { // just call the specialized version which takes an additional argument whether error bars // should also be taken into consideration for range calculation. We set this to true here. return getValueRange(foundRange, inSignDomain, true); } /*! \overload Allows to specify whether the error bars should be included in the range calculation. \see getKeyRange(bool &foundRange, SignDomain inSignDomain) */ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current, currentErrorMinus, currentErrorPlus; if (inSignDomain == sdBoth) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { if (!qIsNaN(it.value().value)) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if (current-currentErrorMinus < range.lower || !haveLower) { range.lower = current-currentErrorMinus; haveLower = true; } if (current+currentErrorPlus > range.upper || !haveUpper) { range.upper = current+currentErrorPlus; haveUpper = true; } } ++it; } } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { if (!qIsNaN(it.value().value)) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. { if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } } ++it; } } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { if (!qIsNaN(it.value().value)) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. { if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } } ++it; } } foundRange = haveLower && haveUpper; return range; } /*! \overload Allows to specify whether the error bars should be included in the range calculation. \see getValueRange(bool &foundRange, SignDomain inSignDomain) */ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current, currentErrorMinus, currentErrorPlus; if (inSignDomain == sdBoth) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current)) { currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if (current-currentErrorMinus < range.lower || !haveLower) { range.lower = current-currentErrorMinus; haveLower = true; } if (current+currentErrorPlus > range.upper || !haveUpper) { range.upper = current+currentErrorPlus; haveUpper = true; } } ++it; } } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current)) { currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. { if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } } ++it; } } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current)) { currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. { if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } } ++it; } } foundRange = haveLower && haveUpper; return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurveData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. The container for storing multiple data points is \ref QCPCurveDataMap. The stored data is: \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector <em>(x(t), y(t))</em>) \li \a key: coordinate on the key axis of this curve point \li \a value: coordinate on the value axis of this curve point \see QCPCurveDataMap */ /*! Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : t(0), key(0), value(0) { } /*! Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : t(t), key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. \image html QCPCurve.png Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third coordinate \a t, which defines the order of the points described by the other two coordinates \a x and \a y. To plot data, assign it with the \ref setData or \ref addData functions. Gaps in the curve can be created by adding data points with NaN as key and value (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be separated. \section appearance Changing the appearance The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). \section usage Usage Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance and add it to the customPlot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 and then modify the properties of the newly created plottable, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2 */ /*! Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. */ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPCurveDataMap; mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(Qt::blue); mBrush.setStyle(Qt::NoBrush); mSelectedPen = mPen; mSelectedPen.setWidthF(2.5); mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; setScatterStyle(QCPScatterStyle()); setLineStyle(lsLine); } QCPCurve::~QCPCurve() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPCurve::setData(QCPCurveDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a t, \a key and \a value tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPCurve::setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value) { mData->clear(); int n = t.size(); n = qMin(n, key.size()); n = qMin(n, value.size()); QCPCurveData newData; for (int i=0; i<n; ++i) { newData.t = t[i]; newData.key = key[i]; newData.value = value[i]; mData->insertMulti(newData.t, newData); } } /*! \overload Replaces the current data with the provided \a key and \a value pairs. The t parameter of each data point will be set to the integer index of the respective key/value pair. */ void QCPCurve::setData(const QVector<double> &key, const QVector<double> &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPCurveData newData; for (int i=0; i<n; ++i) { newData.t = i; // no t vector given, so we assign t the index of the key/value pair newData.key = key[i]; newData.value = value[i]; mData->insertMulti(newData.t, newData); } } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { mLineStyle = style; } /*! Adds the provided data points in \a dataMap to the current data. \see removeData */ void QCPCurve::addData(const QCPCurveDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. \see removeData */ void QCPCurve::addData(const QCPCurveData &data) { mData->insertMulti(data.t, data); } /*! \overload Adds the provided single data point as \a t, \a key and \a value tuple to the current data \see removeData */ void QCPCurve::addData(double t, double key, double value) { QCPCurveData newData; newData.t = t; newData.key = key; newData.value = value; mData->insertMulti(newData.t, newData); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data The t parameter of the data point is set to the t of the last data point plus 1. If there is no last data point, t will be set to 0. \see removeData */ void QCPCurve::addData(double key, double value) { QCPCurveData newData; if (!mData->isEmpty()) newData.t = (mData->constEnd()-1).key()+1; else newData.t = 0; newData.key = key; newData.value = value; mData->insertMulti(newData.t, newData); } /*! \overload Adds the provided data points as \a t, \a key and \a value tuples to the current data. \see removeData */ void QCPCurve::addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values) { int n = ts.size(); n = qMin(n, keys.size()); n = qMin(n, values.size()); QCPCurveData newData; for (int i=0; i<n; ++i) { newData.t = ts[i]; newData.key = keys[i]; newData.value = values[i]; mData->insertMulti(newData.t, newData); } } /*! Removes all data points with curve parameter t smaller than \a t. \see addData, clearData */ void QCPCurve::removeDataBefore(double t) { QCPCurveDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < t) it = mData->erase(it); } /*! Removes all data points with curve parameter t greater than \a t. \see addData, clearData */ void QCPCurve::removeDataAfter(double t) { if (mData->isEmpty()) return; QCPCurveDataMap::iterator it = mData->upperBound(t); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is greater or equal to \a tot, the function does nothing. To remove a single data point with known t, use \ref removeData(double t). \see addData, clearData */ void QCPCurve::removeData(double fromt, double tot) { if (fromt >= tot || mData->isEmpty()) return; QCPCurveDataMap::iterator it = mData->upperBound(fromt); QCPCurveDataMap::iterator itEnd = mData->upperBound(tot); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at curve parameter \a t. If the position is not known with absolute precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness interval around the suspected position, depeding on the precision with which the curve parameter is known. \see addData, clearData */ void QCPCurve::removeData(double t) { mData->remove(t); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPCurve::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && !mSelectable) || mData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) return pointDistance(pos); else return -1; } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { if (mData->isEmpty()) return; // allocate line vector: QVector<QPointF> *lineData = new QVector<QPointF>; // fill with curve data: getCurveData(lineData); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPCurveDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (QCP::isInvalidData(it.value().t) || QCP::isInvalidData(it.value().key, it.value().value)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); } #endif // draw curve fill: if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) { applyFillAntialiasingHint(painter); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(QPolygonF(*lineData)); } // draw curve line: if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { int i = 0; bool lastIsNan = false; const int lineDataSize = lineData->size(); while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN ++i; ++i; // because drawing works in 1 point retrospect while (i < lineDataSize) { if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { if (!lastIsNan) painter->drawLine(lineData->at(i-1), lineData->at(i)); else lastIsNan = false; } else lastIsNan = true; ++i; } } else { int segmentStart = 0; int i = 0; const int lineDataSize = lineData->size(); while (i < lineDataSize) { if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point segmentStart = i+1; } ++i; } // draw last segment: painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); } } // draw scatters: if (!mScatterStyle.isNone()) drawScatterPlot(painter, lineData); // free allocated line data: delete lineData; } /* inherits documentation from base class */ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone. */ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const { // draw scatter point symbols: applyScattersAntialiasingHint(painter); mScatterStyle.applyTo(painter, mPen); for (int i=0; i<pointData->size(); ++i) if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y())) mScatterStyle.drawShape(painter, pointData->at(i)); } /*! \internal called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the line of the curve. Line segments that aren't visible in the current axis rect are handled in an optimized way. They are projected onto a rectangle slightly larger than the visible axis rect and simplified regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside the visible axis rect by generating new temporary points on the outer rect if necessary. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints. */ void QCPCurve::getCurveData(QVector<QPointF> *lineData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // add margins to rect to compensate for stroke width double strokeMargin = qMax(qreal(1.0), qreal(mainPen().widthF()*0.75)); // stroke radius + 50% safety if (!mScatterStyle.isNone()) strokeMargin = qMax(strokeMargin, mScatterStyle.size()); double rectLeft = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); double rectRight = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); double rectBottom = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)+strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); double rectTop = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)-strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); int currentRegion; QCPCurveDataMap::const_iterator it = mData->constBegin(); QCPCurveDataMap::const_iterator prevIt = mData->constEnd()-1; int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom); QVector<QPointF> trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right) while (it != mData->constEnd()) { currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R { if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal { QPointF crossA, crossB; if (prevRegion == 5) // we're coming from R, so add this point optimized { lineData->append(getOptimizedPoint(currentRegion, it.value().key, it.value().value, prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom)); // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); } else if (mayTraverse(prevRegion, currentRegion) && getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, crossA, crossB)) { // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point: QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints; getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight, rectBottom, beforeTraverseCornerPoints, afterTraverseCornerPoints); if (it != mData->constBegin()) { *lineData << beforeTraverseCornerPoints; lineData->append(crossA); lineData->append(crossB); *lineData << afterTraverseCornerPoints; } else { lineData->append(crossB); *lineData << afterTraverseCornerPoints; trailingPoints << beforeTraverseCornerPoints << crossA ; } } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s) { *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); } } else // segment does end in R, so we add previous point optimized and this point at original position { if (it == mData->constBegin()) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end trailingPoints << getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); else lineData->append(getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom)); lineData->append(coordsToPixels(it.value().key, it.value().value)); } } else // region didn't change { if (currentRegion == 5) // still in R, keep adding original points { lineData->append(coordsToPixels(it.value().key, it.value().value)); } else // still outside R, no need to add anything { // see how this is not doing anything? That's the main optimization... } } prevIt = it; prevRegion = currentRegion; ++it; } *lineData << trailingPoints; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a rectLeft, \a rectTop, \a rectRight, and \a rectBottom. The regions are enumerated from top to bottom and left to right: <table style="width:10em; text-align:center"> <tr><td>1</td><td>4</td><td>7</td></tr> <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr> <tr><td>3</td><td>6</td><td>9</td></tr> </table> With the rectangle being region 5, and the outer regions extending infinitely outwards. In the curve optimization algorithm, region 5 is considered to be the visible portion of the plot. */ int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const { if (x < rectLeft) // region 123 { if (y > rectTop) return 1; else if (y < rectBottom) return 3; else return 2; } else if (x > rectRight) // region 789 { if (y > rectTop) return 7; else if (y < rectBottom) return 9; else return 8; } else // region 456 { if (y > rectTop) return 4; else if (y < rectBottom) return 6; else return 5; } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method is used in case the current segment passes from inside the visible rect (region 5, see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). It returns the intersection point of the segment with the border of region 5. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or leaving it. It is important though that \a otherRegion correctly identifies the other region not equal to 5. */ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const { double intersectKey = rectLeft; // initial value is just fail-safe double intersectValue = rectTop; // initial value is just fail-safe switch (otherRegion) { case 1: // top and left edge { intersectValue = rectTop; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectLeft; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 2: // left edge { intersectKey = rectLeft; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); break; } case 3: // bottom and left edge { intersectValue = rectBottom; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectLeft; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 4: // top edge { intersectValue = rectTop; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); break; } case 5: { break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table } case 6: // bottom edge { intersectValue = rectBottom; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); break; } case 7: // top and right edge { intersectValue = rectTop; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectRight; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 8: // right edge { intersectKey = rectRight; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); break; } case 9: // bottom and right edge { intersectValue = rectBottom; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectRight; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } } return coordsToPixels(intersectKey, intersectValue); } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. In situations where a single segment skips over multiple regions it might become necessary to add extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. This method provides these points that must be added, assuming the original segment doesn't start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by \ref getTraverseCornerPoints.) For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. Naively optimizing these points by projecting them on the top and left borders of region 5 will create a segment that surely crosses 5, creating a visual artifact in the plot. This method prevents this by providing extra points at the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without traversing 5. */ QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const { QVector<QPointF> result; switch (prevRegion) { case 1: { switch (currentRegion) { case 2: { result << coordsToPixels(rectLeft, rectTop); break; } case 4: { result << coordsToPixels(rectLeft, rectTop); break; } case 3: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); break; } case 7: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); break; } case 6: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } else { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } break; } } break; } case 2: { switch (currentRegion) { case 1: { result << coordsToPixels(rectLeft, rectTop); break; } case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } case 4: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 6: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 7: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } case 9: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } } break; } case 3: { switch (currentRegion) { case 2: { result << coordsToPixels(rectLeft, rectBottom); break; } case 6: { result << coordsToPixels(rectLeft, rectBottom); break; } case 1: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); break; } case 9: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); break; } case 4: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } else { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } break; } } break; } case 4: { switch (currentRegion) { case 1: { result << coordsToPixels(rectLeft, rectTop); break; } case 7: { result << coordsToPixels(rectRight, rectTop); break; } case 2: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 3: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } case 9: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } } break; } case 5: { switch (currentRegion) { case 1: { result << coordsToPixels(rectLeft, rectTop); break; } case 7: { result << coordsToPixels(rectRight, rectTop); break; } case 9: { result << coordsToPixels(rectRight, rectBottom); break; } case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 6: { switch (currentRegion) { case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } case 9: { result << coordsToPixels(rectRight, rectBottom); break; } case 2: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 1: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } case 7: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } } break; } case 7: { switch (currentRegion) { case 4: { result << coordsToPixels(rectRight, rectTop); break; } case 8: { result << coordsToPixels(rectRight, rectTop); break; } case 1: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); break; } case 9: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); break; } case 2: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 6: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } else { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } break; } } break; } case 8: { switch (currentRegion) { case 7: { result << coordsToPixels(rectRight, rectTop); break; } case 9: { result << coordsToPixels(rectRight, rectBottom); break; } case 4: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 6: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 1: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } case 3: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 9: { switch (currentRegion) { case 6: { result << coordsToPixels(rectRight, rectBottom); break; } case 8: { result << coordsToPixels(rectRight, rectBottom); break; } case 3: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); break; } case 7: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); break; } case 2: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 4: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } else { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } break; } } break; } } return result; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion nor \a currentRegion is 5 itself. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref getTraverse). */ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const { switch (prevRegion) { case 1: { switch (currentRegion) { case 4: case 7: case 2: case 3: return false; default: return true; } } case 2: { switch (currentRegion) { case 1: case 3: return false; default: return true; } } case 3: { switch (currentRegion) { case 1: case 2: case 6: case 9: return false; default: return true; } } case 4: { switch (currentRegion) { case 1: case 7: return false; default: return true; } } case 5: return false; // should never occur case 6: { switch (currentRegion) { case 3: case 9: return false; default: return true; } } case 7: { switch (currentRegion) { case 1: case 4: case 8: case 9: return false; default: return true; } } case 8: { switch (currentRegion) { case 7: case 9: return false; default: return true; } } case 9: { switch (currentRegion) { case 3: case 6: case 8: case 7: return false; default: return true; } } default: return true; } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible region 5. The return value of this method indicates whether the segment actually traverses region 5 or not. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and exit points of region 5. They will become the optimized points for that segment. */ bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const { QList<QPointF> intersections; // x of QPointF corresponds to key and y to value if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis { // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here intersections.append(QPointF(key, rectBottom)); // direction will be taken care of at end of method intersections.append(QPointF(key, rectTop)); } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis { // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here intersections.append(QPointF(rectLeft, value)); // direction will be taken care of at end of method intersections.append(QPointF(rectRight, value)); } else // line is skewed { double gamma; double keyPerValue = (key-prevKey)/(value-prevValue); // check top of rect: gamma = prevKey + (rectTop-prevValue)*keyPerValue; if (gamma >= rectLeft && gamma <= rectRight) intersections.append(QPointF(gamma, rectTop)); // check bottom of rect: gamma = prevKey + (rectBottom-prevValue)*keyPerValue; if (gamma >= rectLeft && gamma <= rectRight) intersections.append(QPointF(gamma, rectBottom)); double valuePerKey = 1.0/keyPerValue; // check left of rect: gamma = prevValue + (rectLeft-prevKey)*valuePerKey; if (gamma >= rectBottom && gamma <= rectTop) intersections.append(QPointF(rectLeft, gamma)); // check right of rect: gamma = prevValue + (rectRight-prevKey)*valuePerKey; if (gamma >= rectBottom && gamma <= rectTop) intersections.append(QPointF(rectRight, gamma)); } // handle cases where found points isn't exactly 2: if (intersections.size() > 2) { // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: double distSqrMax = 0; QPointF pv1, pv2; for (int i=0; i<intersections.size()-1; ++i) { for (int k=i+1; k<intersections.size(); ++k) { QPointF distPoint = intersections.at(i)-intersections.at(k); double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y(); if (distSqr > distSqrMax) { pv1 = intersections.at(i); pv2 = intersections.at(k); distSqrMax = distSqr; } } } intersections = QList<QPointF>() << pv1 << pv2; } else if (intersections.size() != 2) { // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment return false; } // possibly re-sort points so optimized point segment has same direction as original segment: if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction intersections.move(0, 1); crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y()); crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y()); return true; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method assumes that the \ref getTraverse test has returned true, so the segment definitely traverses the visible region 5 when going from \a prevRegion to \a currentRegion. In certain situations it is not sufficient to merely generate the entry and exit points of the segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in addition to traversing region 5, skips another region outside of region 5, which makes it necessary to add an optimized corner point there (very similar to the job \ref getOptimizedCornerPoints does for segments that are completely in outside regions and don't traverse 5). As an example, consider a segment going from region 1 to region 6, traversing the lower left corner of region 5. In this configuration, the segment additionally crosses the border between region 1 and 2 before entering region 5. This makes it necessary to add an additional point in the top left corner, before adding the optimized traverse points. So in this case, the output parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be empty. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse return the respective corner points. */ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const { switch (prevRegion) { case 1: { switch (currentRegion) { case 6: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } case 9: { beforeTraverse << coordsToPixels(rectLeft, rectTop); afterTraverse << coordsToPixels(rectRight, rectBottom); break; } case 8: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } } break; } case 2: { switch (currentRegion) { case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } } break; } case 3: { switch (currentRegion) { case 4: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } case 7: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); afterTraverse << coordsToPixels(rectRight, rectTop); break; } case 8: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 4: { switch (currentRegion) { case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } } break; } case 5: { break; } // shouldn't happen because this method only handles full traverses case 6: { switch (currentRegion) { case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } } break; } case 7: { switch (currentRegion) { case 2: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } case 3: { beforeTraverse << coordsToPixels(rectRight, rectTop); afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } case 6: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } } break; } case 8: { switch (currentRegion) { case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 9: { switch (currentRegion) { case 2: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } case 1: { beforeTraverse << coordsToPixels(rectRight, rectBottom); afterTraverse << coordsToPixels(rectLeft, rectTop); break; } case 4: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } } break; } } } /*! \internal Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in \ref selectTest. */ double QCPCurve::pointDistance(const QPointF &pixelPoint) const { if (mData->isEmpty()) { qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; return 500; } if (mData->size() == 1) { QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); return QVector2D(dataPoint-pixelPoint).length(); } // calculate minimum distance to line segments: QVector<QPointF> *lineData = new QVector<QPointF>; getCurveData(lineData); double minDistSqr = std::numeric_limits<double>::max(); for (int i=0; i<lineData->size()-1; ++i) { double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } delete lineData; return qSqrt(minDistSqr); } /* inherits documentation from base class */ QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPCurveDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (!qIsNaN(current) && !qIsNaN(it.value().value)) { if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } ++it; } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPCurveDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current) && !qIsNaN(it.value().key)) { if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } ++it; } foundRange = haveLower && haveUpper; return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBarsGroup //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBarsGroup \brief Groups multiple QCPBars together so they appear side by side \image html QCPBarsGroup.png When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable to have them appearing next to each other at each key. This is what adding the respective QCPBars plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each other, see \ref QCPBars::moveAbove.) \section qcpbarsgroup-usage Usage To add a QCPBars plottable to the group, create a new group and then add the respective bars intances: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation Alternatively to appending to the group like shown above, you can also set the group on the QCPBars plottable via \ref QCPBars::setBarsGroup. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The bars in this group appear in the plot in the order they were appended. To insert a bars plottable at a certain index position, or to reposition a bars plottable which is already in the group, use \ref insert. To remove specific bars from the group, use either \ref remove or call \ref QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. To clear the entire group, call \ref clear, or simply delete the group. \section qcpbarsgroup-example Example The image above is generated with the following code: \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example */ /* start of documentation of inline functions */ /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const Returns all bars currently in this group. \see bars(int index) */ /*! \fn int QCPBarsGroup::size() const Returns the number of QCPBars plottables that are part of this group. */ /*! \fn bool QCPBarsGroup::isEmpty() const Returns whether this bars group is empty. \see size */ /*! \fn bool QCPBarsGroup::contains(QCPBars *bars) Returns whether the specified \a bars plottable is part of this group. */ /* end of documentation of inline functions */ /*! Constructs a new bars group for the specified QCustomPlot instance. */ QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot), mSpacingType(stAbsolute), mSpacing(4) { } QCPBarsGroup::~QCPBarsGroup() { clear(); } /*! Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. The actual spacing can then be specified with \ref setSpacing. \see setSpacing */ void QCPBarsGroup::setSpacingType(SpacingType spacingType) { mSpacingType = spacingType; } /*! Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is defined by the current \ref SpacingType, which can be set with \ref setSpacingType. \see setSpacingType */ void QCPBarsGroup::setSpacing(double spacing) { mSpacing = spacing; } /*! Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars exists, returns 0. \see bars(), size */ QCPBars *QCPBarsGroup::bars(int index) const { if (index >= 0 && index < mBars.size()) { return mBars.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! Removes all QCPBars plottables from this group. \see isEmpty */ void QCPBarsGroup::clear() { foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay bars->setBarsGroup(0); // removes itself via removeBars } /*! Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref QCPBars::setBarsGroup on the \a bars instance. \see insert, remove */ void QCPBarsGroup::append(QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } if (!mBars.contains(bars)) bars->setBarsGroup(this); else qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars); } /*! Inserts the specified \a bars plottable into this group at the specified index position \a i. This gives you full control over the ordering of the bars. \a bars may already be part of this group. In that case, \a bars is just moved to the new index position. \see append, remove */ void QCPBarsGroup::insert(int i, QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } // first append to bars list normally: if (!mBars.contains(bars)) bars->setBarsGroup(this); // then move to according position: mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); } /*! Removes the specified \a bars plottable from this group. \see contains, clear */ void QCPBarsGroup::remove(QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } if (mBars.contains(bars)) bars->setBarsGroup(0); else qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars); } /*! \internal Adds the specified \a bars to the internal mBars list of bars. This method does not change the barsGroup property on \a bars. \see unregisterBars */ void QCPBarsGroup::registerBars(QCPBars *bars) { if (!mBars.contains(bars)) mBars.append(bars); } /*! \internal Removes the specified \a bars from the internal mBars list of bars. This method does not change the barsGroup property on \a bars. \see registerBars */ void QCPBarsGroup::unregisterBars(QCPBars *bars) { mBars.removeOne(bars); } /*! \internal Returns the pixel offset in the key dimension the specified \a bars plottable should have at the given key coordinate \a keyCoord. The offset is relative to the pixel position of the key coordinate \a keyCoord. */ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) { // find list of all base bars in case some mBars are stacked: QList<const QCPBars*> baseBars; foreach (const QCPBars *b, mBars) { while (b->barBelow()) b = b->barBelow(); if (!baseBars.contains(b)) baseBars.append(b); } // find base bar this "bars" is stacked on: const QCPBars *thisBase = bars; while (thisBase->barBelow()) thisBase = thisBase->barBelow(); // determine key pixel offset of this base bars considering all other base bars in this barsgroup: double result = 0; int index = baseBars.indexOf(thisBase); if (index >= 0) { int startIndex; double lowerPixelWidth, upperPixelWidth; if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) { return result; } else if (index < (baseBars.size()-1)/2.0) // bar is to the left of center { if (baseBars.size() % 2 == 0) // even number of bars { startIndex = baseBars.size()/2-1; result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing } else // uneven number of bars { startIndex = (baseBars.size()-1)/2-1; baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar result -= getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing } for (int i=startIndex; i>index; --i) // add widths and spacings of bars in between center and our bars { baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result -= qAbs(upperPixelWidth-lowerPixelWidth); result -= getPixelSpacing(baseBars.at(i), keyCoord); } // finally half of our bars width: baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; } else // bar is to the right of center { if (baseBars.size() % 2 == 0) // even number of bars { startIndex = baseBars.size()/2; result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing } else // uneven number of bars { startIndex = (baseBars.size()-1)/2+1; baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing } for (int i=startIndex; i<index; ++i) // add widths and spacings of bars in between center and our bars { baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth); result += getPixelSpacing(baseBars.at(i), keyCoord); } // finally half of our bars width: baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; } } return result; } /*! \internal Returns the spacing in pixels which is between this \a bars and the following one, both at the key coordinate \a keyCoord. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only needed to get acces to the key axis transformation and axis rect for the modes \ref stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in \ref stPlotCoords on a logarithmic axis. */ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) { switch (mSpacingType) { case stAbsolute: { return mSpacing; } case stAxisRectRatio: { if (bars->keyAxis()->orientation() == Qt::Horizontal) return bars->keyAxis()->axisRect()->width()*mSpacing; else return bars->keyAxis()->axisRect()->height()*mSpacing; } case stPlotCoords: { double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel; } } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBarData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBarData \brief Holds the data of one single data point (one bar) for QCPBars. The container for storing multiple data points is \ref QCPBarDataMap. The stored data is: \li \a key: coordinate on the key axis of this bar \li \a value: height coordinate on the value axis of this bar \see QCPBarDataaMap */ /*! Constructs a bar data point with key and value set to zero. */ QCPBarData::QCPBarData() : key(0), value(0) { } /*! Constructs a bar data point with the specified \a key and \a value. */ QCPBarData::QCPBarData(double key, double value) : key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBars //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBars \brief A plottable representing a bar chart in a plot. \image html QCPBars.png To plot data, assign it with the \ref setData or \ref addData functions. \section appearance Changing the appearance The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear stacked. If you would like to group multiple QCPBars plottables together so they appear side by side as shown below, use QCPBarsGroup. \image html QCPBarsGroup.png \section usage Usage Like all data representing objects in QCustomPlot, the QCPBars is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 add it to the customPlot with QCustomPlot::addPlottable: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2 and then modify the properties of the newly created plottable, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-3 */ /* start of documentation of inline functions */ /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns 0. \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns 0. \see barBelow, moveBelow, moveAbove */ /* end of documentation of inline functions */ /*! Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the bar chart. */ QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mData(new QCPBarDataMap), mWidth(0.75), mWidthType(wtPlotCoords), mBarsGroup(0), mBaseValue(0) { // modify inherited properties from abstract plottable: mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(QColor(40, 50, 255, 30)); mBrush.setStyle(Qt::SolidPattern); mSelectedPen = mPen; mSelectedPen.setWidthF(2.5); mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; } QCPBars::~QCPBars() { setBarsGroup(0); if (mBarBelow || mBarAbove) connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking delete mData; } /*! Sets the width of the bars. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...), depends on the currently set width type, see \ref setWidthType and \ref WidthType. */ void QCPBars::setWidth(double width) { mWidth = width; } /*! Sets how the width of the bars is defined. See the documentation of \ref WidthType for an explanation of the possible values for \a widthType. The default value is \ref wtPlotCoords. \see setWidth */ void QCPBars::setWidthType(QCPBars::WidthType widthType) { mWidthType = widthType; } /*! Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref QCPBarsGroup::append. To remove this QCPBars from any group, set \a barsGroup to 0. */ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) { // deregister at old group: if (mBarsGroup) mBarsGroup->unregisterBars(this); mBarsGroup = barsGroup; // register at new group: if (mBarsGroup) mBarsGroup->registerBars(this); } /*! Sets the base value of this bars plottable. The base value defines where on the value coordinate the bars start. How far the bars extend from the base value is given by their individual value data. For example, if the base value is set to 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at 3. For stacked bars, only the base value of the bottom-most QCPBars has meaning. The default base value is 0. */ void QCPBars::setBaseValue(double baseValue) { mBaseValue = baseValue; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPBars::setData(QCPBarDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a key and \a value tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPBars::setData(const QVector<double> &key, const QVector<double> &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPBarData newData; for (int i=0; i<n; ++i) { newData.key = key[i]; newData.value = value[i]; mData->insertMulti(newData.key, newData); } } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object below itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to 0. \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar below it: if (bars) { if (bars->mBarBelow) connectBars(bars->mBarBelow.data(), this); connectBars(this, bars); } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object above itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to 0. \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar above it: if (bars) { if (bars->mBarAbove) connectBars(this, bars->mBarAbove.data()); connectBars(bars, this); } } /*! Adds the provided data points in \a dataMap to the current data. \see removeData */ void QCPBars::addData(const QCPBarDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. \see removeData */ void QCPBars::addData(const QCPBarData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value tuple to the current data \see removeData */ void QCPBars::addData(double key, double value) { QCPBarData newData; newData.key = key; newData.value = value; mData->insertMulti(newData.key, newData); } /*! \overload Adds the provided data points as \a key and \a value tuples to the current data. \see removeData */ void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values) { int n = keys.size(); n = qMin(n, values.size()); QCPBarData newData; for (int i=0; i<n; ++i) { newData.key = keys[i]; newData.value = values[i]; mData->insertMulti(newData.key, newData); } } /*! Removes all data points with key smaller than \a key. \see addData, clearData */ void QCPBars::removeDataBefore(double key) { QCPBarDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with key greater than \a key. \see addData, clearData */ void QCPBars::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPBarDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPBars::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPBarDataMap::iterator it = mData->upperBound(fromKey); QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPBars::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPBars::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { QCPBarDataMap::ConstIterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) return mParentPlot->selectionTolerance()*0.99; } } return -1; } /* inherits documentation from base class */ void QCPBars::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mData->isEmpty()) return; QCPBarDataMap::const_iterator it, lower, upperEnd; getVisibleDataBounds(lower, upperEnd); for (it = lower; it != upperEnd; ++it) { // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(it.value().key, it.value().value)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); #endif QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); // draw bar fill: if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) { applyFillAntialiasingHint(painter); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(barPolygon); } // draw bar line: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); painter->drawPolyline(barPolygon); } } } /* inherits documentation from base class */ void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setBrush(mBrush); painter->setPen(mPen); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal called by \ref draw to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. It also takes into account the bar width. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a upperEnd may also lie just outside of the visible range. if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd. */ void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upperEnd = mData->constEnd(); return; } // get visible data range as QMap iterators lower = mData->lowerBound(mKeyAxis.data()->range().lower); upperEnd = mData->upperBound(mKeyAxis.data()->range().upper); double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower); double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper); bool isVisible = false; // walk left from lbound to find lower bar that actually is completely outside visible pixel range: QCPBarDataMap::const_iterator it = lower; while (it != mData->constBegin()) { --it; QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); if (mKeyAxis.data()->orientation() == Qt::Horizontal) isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); else // keyaxis is vertical isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); if (isVisible) lower = it; else break; } // walk right from ubound to find upper bar that actually is completely outside visible pixel range: it = upperEnd; while (it != mData->constEnd()) { QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); if (mKeyAxis.data()->orientation() == Qt::Horizontal) isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); else // keyaxis is vertical isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); if (isVisible) upperEnd = it+1; else break; ++it; } } /*! \internal Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref setBaseValue). */ QPolygonF QCPBars::getBarPolygon(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } QPolygonF result; double lowerPixelWidth, upperPixelWidth; getPixelWidth(key, lowerPixelWidth, upperPixelWidth); double base = getStackedBaseValue(key, value >= 0); double basePixel = valueAxis->coordToPixel(base); double valuePixel = valueAxis->coordToPixel(base+value); double keyPixel = keyAxis->coordToPixel(key); if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, key); if (keyAxis->orientation() == Qt::Horizontal) { result << QPointF(keyPixel+lowerPixelWidth, basePixel); result << QPointF(keyPixel+lowerPixelWidth, valuePixel); result << QPointF(keyPixel+upperPixelWidth, valuePixel); result << QPointF(keyPixel+upperPixelWidth, basePixel); } else { result << QPointF(basePixel, keyPixel+lowerPixelWidth); result << QPointF(valuePixel, keyPixel+lowerPixelWidth); result << QPointF(valuePixel, keyPixel+upperPixelWidth); result << QPointF(basePixel, keyPixel+upperPixelWidth); } return result; } /*! \internal This function is used to determine the width of the bar at coordinate \a key, according to the specified width (\ref setWidth) and width type (\ref setWidthType). The output parameters \a lower and \a upper return the number of pixels the bar extends to lower and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a lower is negative and \a upper positive). */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { switch (mWidthType) { case wtAbsolute: { upper = mWidth*0.5; lower = -upper; if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) qSwap(lower, upper); break; } case wtAxisRectRatio: { if (mKeyAxis && mKeyAxis.data()->axisRect()) { if (mKeyAxis.data()->orientation() == Qt::Horizontal) upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5; else upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5; lower = -upper; if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) qSwap(lower, upper); } else qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; break; } case wtPlotCoords: { if (mKeyAxis) { double keyPixel = mKeyAxis.data()->coordToPixel(key); upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by // coordinate transform which includes range direction } else qDebug() << Q_FUNC_INFO << "No key axis defined"; break; } } } /*! \internal This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). positive and negative bars are separated per stack (positive are stacked above baseValue upwards, negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ double QCPBars::getStackedBaseValue(double key, bool positive) const { if (mBarBelow) { double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has meaning in a bar stack // find bars of mBarBelow that are approximately at key and find largest one: double epsilon = qAbs(key)*1e-6; // should be safe even when changed to use float at some point if (key == 0) epsilon = 1e-6; QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-epsilon); QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+epsilon); while (it != itEnd) { if ((positive && it.value().value > max) || (!positive && it.value().value < max)) max = it.value().value; ++it; } // recurse down the bar-stack to find the total height: return max + mBarBelow.data()->getStackedBaseValue(key, positive); } else return mBaseValue; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently above lower and below upper will become disconnected to lower/upper. If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { if (!lower && !upper) return; if (!lower) // disconnect upper at bottom { // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = 0; upper->mBarBelow = 0; } else if (!upper) // disconnect lower at top { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = 0; lower->mBarAbove = 0; } else // connect lower and upper { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = 0; // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = 0; lower->mBarAbove = upper; upper->mBarBelow = lower; } } /* inherits documentation from base class */ QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPBarDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } // determine exact range of bars by including bar width and barsgroup offset: if (haveLower && mKeyAxis) { double lowerPixelWidth, upperPixelWidth, keyPixel; getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); range.lower = mKeyAxis.data()->pixelToCoord(keyPixel); } if (haveUpper && mKeyAxis) { double lowerPixelWidth, upperPixelWidth, keyPixel; getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); range.upper = mKeyAxis.data()->pixelToCoord(keyPixel); } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; range.lower = mBaseValue; range.upper = mBaseValue; bool haveLower = true; // set to true, because baseValue should always be visible in bar charts bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts double current; QCPBarDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0); if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } foundRange = true; // return true because bar charts always have the 0-line visible return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPStatisticalBox //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPStatisticalBox \brief A plottable representing a single statistical box in a plot. \image html QCPStatisticalBox.png To plot data, assign it with the individual parameter functions or use \ref setData to set all parameters at once. The individual functions are: \li \ref setMinimum \li \ref setLowerQuartile \li \ref setMedian \li \ref setUpperQuartile \li \ref setMaximum Additionally you can define a list of outliers, drawn as scatter datapoints: \li \ref setOutliers \section appearance Changing the appearance The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change the width of the box with \ref setWidth in plot coordinates (not pixels). Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top (maximum) and bottom (minimum). The median indicator line has its own pen, \ref setMedianPen. If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the backbone line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat. The Outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle \section usage Usage Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable. Usually, you first create an instance and add it to the customPlot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1 and then modify the properties of the newly created plottable, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2 */ /*! Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed statistical box can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the statistical box. */ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mKey(0), mMinimum(0), mLowerQuartile(0), mMedian(0), mUpperQuartile(0), mMaximum(0) { setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); setWhiskerWidth(0.2); setWidth(0.5); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2.5)); setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); setWhiskerBarPen(QPen(Qt::black)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } /*! Sets the key coordinate of the statistical box. */ void QCPStatisticalBox::setKey(double key) { mKey = key; } /*! Sets the parameter "minimum" of the statistical box plot. This is the position of the lower whisker, typically the minimum measurement of the sample that's not considered an outlier. \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMinimum(double value) { mMinimum = value; } /*! Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they contain 50% of the sample data. \see setUpperQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setLowerQuartile(double value) { mLowerQuartile = value; } /*! Sets the parameter "median" of the statistical box plot. This is the value of the median mark inside the quartile box. The median separates the sample data in half (50% of the sample data is below/above the median). \see setMedianPen */ void QCPStatisticalBox::setMedian(double value) { mMedian = value; } /*! Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they contain 50% of the sample data. \see setLowerQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setUpperQuartile(double value) { mUpperQuartile = value; } /*! Sets the parameter "maximum" of the statistical box plot. This is the position of the upper whisker, typically the maximum measurement of the sample that's not considered an outlier. \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMaximum(double value) { mMaximum = value; } /*! Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers and displayed as such. \see setOutlierStyle */ void QCPStatisticalBox::setOutliers(const QVector<double> &values) { mOutliers = values; } /*! Sets all parameters of the statistical box plot at once. \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum */ void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) { setKey(key); setMinimum(minimum); setLowerQuartile(lowerQuartile); setMedian(median); setUpperQuartile(upperQuartile); setMaximum(maximum); } /*! Sets the width of the box in key coordinates. \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { mWidth = width; } /*! Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. \see setWidth */ void QCPStatisticalBox::setWhiskerWidth(double width) { mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching a few pixels past the whisker bars, when using a non-zero pen width. \see setWhiskerBarPen */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { mWhiskerPen = pen; } /*! Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at each end of the whisker backbone). \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { mWhiskerBarPen = pen; } /*! Sets the pen used for drawing the median indicator line inside the statistical box. */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { mMedianPen = pen; } /*! Sets the appearance of the outlier data points. \see setOutliers */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { mOutlierStyle = style; } /* inherits documentation from base class */ void QCPStatisticalBox::clearData() { setOutliers(QVector<double>()); setKey(0); setMinimum(0); setLowerQuartile(0); setMedian(0); setUpperQuartile(0); setMaximum(0); } /* inherits documentation from base class */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); // quartile box: QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); QCPRange valueRange(mLowerQuartile, mUpperQuartile); if (keyRange.contains(posKey) && valueRange.contains(posValue)) return mParentPlot->selectionTolerance()*0.99; // min/max whiskers: if (QCPRange(mMinimum, mMaximum).contains(posValue)) return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); } return -1; } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(mKey, mMedian) || QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || QCP::isInvalidData(mMinimum, mMaximum)) qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); for (int i=0; i<mOutliers.size(); ++i) if (QCP::isInvalidData(mOutliers.at(i))) qDebug() << Q_FUNC_INFO << "Data point outlier at" << mKey << "of drawn range invalid." << "Plottable name:" << name(); #endif QRectF quartileBox; drawQuartileBox(painter, &quartileBox); painter->save(); painter->setClipRect(quartileBox, Qt::IntersectClip); drawMedian(painter); painter->restore(); drawWhiskers(painter); drawOutliers(painter); } /* inherits documentation from base class */ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->setBrush(mBrush); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so the median doesn't draw outside the quartile box). */ void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const { QRectF box; box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(box); if (quartileBox) *quartileBox = box; } /*! \internal Draws the median line inside the quartile box. */ void QCPStatisticalBox::drawMedian(QCPPainter *painter) const { QLineF medianLine; medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); applyDefaultAntialiasingHint(painter); painter->setPen(mMedianPen); painter->drawLine(medianLine); } /*! \internal Draws both whisker backbones and bars. */ void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const { QLineF backboneMin, backboneMax, barMin, barMax; backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); applyErrorBarsAntialiasingHint(painter); painter->setPen(mWhiskerPen); painter->drawLine(backboneMin); painter->drawLine(backboneMax); painter->setPen(mWhiskerBarPen); painter->drawLine(barMin); painter->drawLine(barMax); } /*! \internal Draws the outlier scatter points. */ void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const { applyScattersAntialiasingHint(painter); mOutlierStyle.applyTo(painter, mPen); for (int i=0; i<mOutliers.size(); ++i) mOutlierStyle.drawShape(painter, coordsToPixels(mKey, mOutliers.at(i))); } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; if (inSignDomain == sdBoth) { return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); } else if (inSignDomain == sdNegative) { if (mKey+mWidth*0.5 < 0) return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); else if (mKey < 0) return QCPRange(mKey-mWidth*0.5, mKey); else { foundRange = false; return QCPRange(); } } else if (inSignDomain == sdPositive) { if (mKey-mWidth*0.5 > 0) return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); else if (mKey > 0) return QCPRange(mKey, mKey+mWidth*0.5); else { foundRange = false; return QCPRange(); } } foundRange = false; return QCPRange(); } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QVector<double> values; // values that must be considered (i.e. all outliers and the five box-parameters) values.reserve(mOutliers.size() + 5); values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; values << mOutliers; // go through values and find the ones in legal range: bool haveUpper = false; bool haveLower = false; double upper = 0; double lower = 0; for (int i=0; i<values.size(); ++i) { if ((inSignDomain == sdNegative && values.at(i) < 0) || (inSignDomain == sdPositive && values.at(i) > 0) || (inSignDomain == sdBoth)) { if (values.at(i) > upper || !haveUpper) { upper = values.at(i); haveUpper = true; } if (values.at(i) < lower || !haveLower) { lower = values.at(i); haveLower = true; } } } // return the bounds if we found some sensible values: if (haveLower && haveUpper) { foundRange = true; return QCPRange(lower, upper); } else // might happen if all values are in other sign domain { foundRange = false; return QCPRange(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorMapData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are provided by the functions \ref coordToCell and \ref cellToCoord. This class also buffers the minimum and maximum values that are in the data set, to provide QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value that is greater than the current maximum increases this maximum to the new value. However, setting the cell that currently holds the maximum value to a smaller value doesn't decrease the maximum again, because finding the true new maximum would require going through the entire data array, which might be time consuming. The same holds for the data minimum. This functionality is given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience parameter \a recalculateDataBounds which may be set to true to automatically call \ref recalculateDataBounds internally. */ /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ /* end of documentation of inline functions */ /*! Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : mKeySize(0), mValueSize(0), mKeyRange(keyRange), mValueRange(valueRange), mIsEmpty(true), mData(0), mDataModified(true) { setSize(keySize, valueSize); fill(0); } QCPColorMapData::~QCPColorMapData() { if (mData) delete[] mData; } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : mKeySize(0), mValueSize(0), mIsEmpty(true), mData(0), mDataModified(true) { *this = other; } /*! Overwrites this color map data instance with the data stored in \a other. */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { if (&other != this) { const int keySize = other.keySize(); const int valueSize = other.valueSize(); setSize(keySize, valueSize); setRange(other.keyRange(), other.valueRange()); if (!mIsEmpty) memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); mDataBounds = other.mDataBounds; mDataModified = true; } return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) return mData[valueCell*mKeySize + keyCell]; else return 0; } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) return mData[valueIndex*mKeySize + keyIndex]; else return 0; } /*! Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setRange, setKeySize, setValueSize */ void QCPColorMapData::setSize(int keySize, int valueSize) { if (keySize != mKeySize || valueSize != mValueSize) { mKeySize = keySize; mValueSize = valueSize; if (mData) delete[] mData; mIsEmpty = mKeySize == 0 || mValueSize == 0; if (!mIsEmpty) { #ifdef __EXCEPTIONS try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif mData = new double[mKeySize*mValueSize]; #ifdef __EXCEPTIONS } catch (...) { mData = 0; } #endif if (mData) fill(0); else qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; } else mData = 0; mDataModified = true; } } /*! Resizes the data array to have \a keySize cells in the key dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { setSize(keySize, mValueSize); } /*! Resizes the data array to have \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will be cells centered on the key coordinates 2, 2.5 and 3. \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { setKeyRange(keyRange); setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will be cells centered on the key coordinates 2, 2.5 and 3. \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there will be cells centered on the value coordinates 2, 2.5 and 3. \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { mData[valueCell*mKeySize + keyCell] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { mData[valueIndex*mKeySize + keyIndex] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Goes through the data and updates the buffered minimum and maximum data values. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { if (mKeySize > 0 && mValueSize > 0) { double minHeight = mData[0]; double maxHeight = mData[0]; const int dataCount = mValueSize*mKeySize; for (int i=0; i<dataCount; ++i) { if (mData[i] > maxHeight) maxHeight = mData[i]; if (mData[i] < minHeight) minHeight = mData[i]; } mDataBounds.lower = minHeight; mDataBounds.upper = maxHeight; } } /*! Frees the internal data memory. This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { setSize(0, 0); } /*! Sets all cells to the value \a z. */ void QCPColorMapData::fill(double z) { const int dataCount = mValueSize*mKeySize; for (int i=0; i<dataCount; ++i) mData[i] = z; mDataBounds = QCPRange(z, z); mDataModified = true; } /*! Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a valueIndex. The retrieved key/value cell indices can then be used for example with \ref setCell. If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a keyIndex. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to determine the cell index. \see cellToCoord, QCPAxis::coordToPixel */ void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const { if (keyIndex) *keyIndex = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; if (valueIndex) *valueIndex = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; } /*! Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData instance. The resulting coordinates are returned via the output parameters \a key and \a value. If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a value. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to determine the cell index. \see coordToCell, QCPAxis::pixelToCoord */ void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const { if (key) *key = keyIndex/(double)(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower; if (value) *value = valueIndex/(double)(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorMap //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorMap \brief A plottable representing a two-dimensional color map in a plot. \image html QCPColorMap.png The data is stored in the class \ref QCPColorMapData, which can be accessed via the data() method. A color map has three dimensions to represent a data point: The \a key dimension, the \a value dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a value). Set the number of points (or \a cells) in the key/value dimension via \ref QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range boundary and the last cell will be centered on the upper range boundary. The data can be set by either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer setCell, since it doesn't need to do any coordinate transformation and thus performs a bit better. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed) key and value axes. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is typically placed to the right of the axis rect. See the documentation there for details on how to add and use a color scale. \section appearance Changing the appearance The central part of the appearance is the color gradient, which can be specified via \ref setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color gradient. The \a data range that is mapped to the colors of the gradient can be specified with \ref setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref rescaleDataRange. \section usage Usage Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance and add it to the customPlot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1 and then modify the properties of the newly created color map, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2 \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. */ /* start documentation of inline functions */ /*! \fn QCPColorMapData *QCPColorMap::data() const Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to modify data points (cells) and the color map key/value range. \see setData */ /* end documentation of inline functions */ /* start documentation of signals */ /*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange); This signal is emitted when the data range changes. \see setDataRange */ /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the data scale type changes. \see setDataScaleType */ /*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient); This signal is emitted when the gradient changes. \see setGradient */ /* end documentation of signals */ /*! Constructs a color map with the specified \a keyAxis and \a valueAxis. The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the color map. */ QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mDataScaleType(QCPAxis::stLinear), mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))), mInterpolate(true), mTightBoundary(false), mMapImageInvalidated(true) { } QCPColorMap::~QCPColorMap() { delete mMapData; } /*! Replaces the current \ref data with the provided \a data. If \a copy is set to true, the \a data object will only be copied. if false, the color map takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPColorMap::setData(QCPColorMapData *data, bool copy) { if (mMapData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data); return; } if (copy) { *mMapData = *data; } else { delete mMapData; mMapData = data; } mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. To make the data range span the full range of the data set, use \ref rescaleDataRange. \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { if (!QCPRange::validRange(dataRange)) return; if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { if (mDataScaleType == QCPAxis::stLogarithmic) mDataRange = dataRange.sanitizedForLogScale(); else mDataRange = dataRange.sanitizedForLinScale(); mMapImageInvalidated = true; emit dataRangeChanged(mDataRange); } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; mMapImageInvalidated = true; emit dataScaleTypeChanged(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; mMapImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { mInterpolate = enabled; mMapImageInvalidated = true; // because oversampling factors might need to change } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. Pass 0 as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { if (mColorScale) // unconnect signals from old color scale { disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } mColorScale = colorScale; if (mColorScale) // connect signals to new color scale { setGradient(mColorScale.data()->gradient()); setDataRange(mColorScale.data()->dataRange()); setDataScaleType(mColorScale.data()->dataScaleType()); connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For performance reasons, however, they are only updated in an expanding fashion. So the buffered maximum can only increase and the buffered minimum can only decrease. In consequence, changes to the data that actually lower the maximum of the data set (by overwriting the cell holding the current maximum with a smaller value), aren't recognized and the buffered maximum overestimates the true maximum of the data set. The same happens for the buffered minimum. To recalculate the true minimum and maximum by explicitly looking at each cell, the method QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { if (recalculateDataBounds) mMapData->recalculateDataBounds(); setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { if (mMapImage.isNull() && !data()->isEmpty()) updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again { bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); } } /*! Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also resizes the map to 0x0 cells. */ void QCPColorMap::clearData() { mMapData->clear(); } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! \internal Updates the internal map image buffer by going through the internal \ref QCPColorMapData and turning the data values into color pixels with \ref QCPColorGradient::colorize. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). If the map cell count is low, the image created will be oversampled in order to avoid a QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images without smooth transform enabled. Accordingly, oversampling isn't performed if \ref setInterpolate is true. */ void QCPColorMap::updateMapImage() { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) return; if (mMapData->isEmpty()) return; const int keySize = mMapData->keySize(); const int valueSize = mMapData->valueSize(); int keyOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)keySize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation: if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor)) mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), QImage::Format_RGB32); else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), QImage::Format_RGB32); QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { // resize undersampled map image to actual key/value cell sizes: if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize)) mUndersampledMapImage = QImage(QSize(keySize, valueSize), QImage::Format_RGB32); else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32); localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image } else if (!mUndersampledMapImage.isNull()) mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it const double *rawData = mMapData->mData; if (keyAxis->orientation() == Qt::Horizontal) { const int lineCount = valueSize; const int rowCount = keySize; for (int line=0; line<lineCount; ++line) { QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); } } else // keyAxis->orientation() == Qt::Vertical { const int lineCount = keySize; const int rowCount = valueSize; for (int line=0; line<lineCount; ++line) { QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); } } if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { if (keyAxis->orientation() == Qt::Horizontal) mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); else mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); } mMapData->mDataModified = false; mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { if (mMapData->isEmpty()) return; if (!mKeyAxis || !mValueAxis) return; applyDefaultAntialiasingHint(painter); if (mMapData->mDataModified || mMapImageInvalidated) updateMapImage(); // use buffer if painting vectorized (PDF): bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized); QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in QPixmap mapBuffer; double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps if (useBuffer) { mapBufferTarget = painter->clipRegion().boundingRect(); mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize()); mapBuffer.fill(Qt::transparent); localPainter = new QCPPainter(&mapBuffer); localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); localPainter->translate(-mapBufferTarget.topLeft()); } QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): double halfCellWidth = 0; // in pixels double halfCellHeight = 0; // in pixels if (keyAxis()->orientation() == Qt::Horizontal) { if (mMapData->keySize() > 1) halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1); } else // keyAxis orientation is Qt::Vertical { if (mMapData->keySize() > 1) halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1); } imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); QRegion clipBackup; if (mTightBoundary) { clipBackup = localPainter->clipRegion(); QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); localPainter->setClipRect(tightClipRect, Qt::IntersectClip); } localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); if (mTightBoundary) localPainter->setClipRegion(clipBackup); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter { delete localPainter; painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); } } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { applyDefaultAntialiasingHint(painter); // draw map thumbnail: if (!mLegendIcon.isNull()) { QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); iconRect.moveCenter(rect.center()); painter->drawPixmap(iconRect.topLeft(), scaledIcon); } /* // draw frame: painter->setBrush(Qt::NoBrush); painter->setPen(Qt::black); painter->drawRect(rect.adjusted(1, 1, 0, 0)); */ } /* inherits documentation from base class */ QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->keyRange(); result.normalize(); if (inSignDomain == QCPAbstractPlottable::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCPAbstractPlottable::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } /* inherits documentation from base class */ QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->valueRange(); result.normalize(); if (inSignDomain == QCPAbstractPlottable::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCPAbstractPlottable::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancialData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPFinancialData \brief Holds the data of one single data point for QCPFinancial. The container for storing multiple data points is \ref QCPFinancialDataMap. The stored data is: \li \a key: coordinate on the key axis of this data point \li \a open: The opening value at the data point \li \a high: The high/maximum value at the data point \li \a low: The low/minimum value at the data point \li \a close: The closing value at the data point \see QCPFinancialDataMap */ /*! Constructs a data point with key and all values set to zero. */ QCPFinancialData::QCPFinancialData() : key(0), open(0), high(0), low(0), close(0) { } /*! Constructs a data point with the specified \a key and OHLC values. */ QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : key(key), open(open), high(high), low(low), close(close) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancial //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPFinancial \brief A plottable representing a financial stock chart \image html QCPFinancial.png This plottable represents time series data binned to certain intervals, mainly used for stock charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be set via \ref setChartStyle. The data is passed via \ref setData as a set of open/high/low/close values at certain keys (typically times). This means the data must be already binned appropriately. If data is only available as a series of values (e.g. \a price against \a time), you can use the static convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed to \ref setData. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. \section appearance Changing the appearance Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored, lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush). If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are represented with a different pen and brush than negative changes (\a close < \a open). These can be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used, irrespective of whether the chart is single- or two-colored. */ /* start of documentation of inline functions */ /*! \fn QCPFinancialDataMap *QCPFinancial::data() const Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods, in certain situations. */ /* end of documentation of inline functions */ /*! Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the financial chart. */ QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mData(0), mChartStyle(csOhlc), mWidth(0.5), mTwoColored(false), mBrushPositive(QBrush(QColor(210, 210, 255))), mBrushNegative(QBrush(QColor(255, 210, 210))), mPenPositive(QPen(QColor(10, 40, 180))), mPenNegative(QPen(QColor(180, 40, 10))) { mData = new QCPFinancialDataMap; setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); setSelectedBrush(QBrush(QColor(80, 80, 255))); } QCPFinancial::~QCPFinancial() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. Alternatively, you can also access and modify the plottable's data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialDataMap. \see timeSeriesToOhlc */ void QCPFinancial::setData(QCPFinancialDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided open/high/low/close data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. \see timeSeriesToOhlc */ void QCPFinancial::setData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close) { mData->clear(); int n = key.size(); n = qMin(n, open.size()); n = qMin(n, high.size()); n = qMin(n, low.size()); n = qMin(n, close.size()); for (int i=0; i<n; ++i) { mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); } } /*! Sets which representation style shall be used to display the OHLC data. */ void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) { mChartStyle = style; } /*! Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. */ void QCPFinancial::setWidth(double width) { mWidth = width; } /*! Sets whether this chart shall contrast positive from negative trends per data point by using two separate colors to draw the respective bars/candlesticks. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setTwoColored(bool twoColored) { mTwoColored = twoColored; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a positive trend (i.e. bars/candlesticks with close >= open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setBrushNegative, setPenPositive, setPenNegative */ void QCPFinancial::setBrushPositive(const QBrush &brush) { mBrushPositive = brush; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a negative trend (i.e. bars/candlesticks with close < open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setBrushPositive, setPenNegative, setPenPositive */ void QCPFinancial::setBrushNegative(const QBrush &brush) { mBrushNegative = brush; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setPenPositive(const QPen &pen) { mPenPositive = pen; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenPositive, setBrushNegative, setBrushPositive */ void QCPFinancial::setPenNegative(const QPen &pen) { mPenNegative = pen; } /*! Adds the provided data points in \a dataMap to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialDataMap. \see removeData */ void QCPFinancial::addData(const QCPFinancialDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. \see removeData */ void QCPFinancial::addData(const QCPFinancialData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. \see removeData */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { mData->insertMulti(key, QCPFinancialData(key, open, high, low, close)); } /*! \overload Adds the provided open/high/low/close data to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. \see removeData */ void QCPFinancial::addData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close) { int n = key.size(); n = qMin(n, open.size()); n = qMin(n, high.size()); n = qMin(n, low.size()); n = qMin(n, close.size()); for (int i=0; i<n; ++i) { mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); } } /*! Removes all data points with keys smaller than \a key. \see addData, clearData */ void QCPFinancial::removeDataBefore(double key) { QCPFinancialDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with keys greater than \a key. \see addData, clearData */ void QCPFinancial::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPFinancialDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPFinancial::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPFinancialDataMap::iterator it = mData->upperBound(fromKey); QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPFinancial::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPFinancial::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { // get visible data range: QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return -1; // perform select test according to configured style: switch (mChartStyle) { case QCPFinancial::csOhlc: return ohlcSelectTest(pos, lower, upper+1); break; case QCPFinancial::csCandlestick: return candlestickSelectTest(pos, lower, upper+1); break; } } return -1; } /*! A convenience function that converts time series data (\a value against \a time) to OHLC binned data points. The return value can then be passed on to \ref setData. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour each, set \a timeBinSize to 3600. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. It merely defines the mathematical offset/phase of the bins that will be used to process the data. */ QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset) { QCPFinancialDataMap map; int count = qMin(time.size(), value.size()); if (count == 0) return QCPFinancialDataMap(); QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); for (int i=0; i<count; ++i) { int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5); if (currentBinIndex == index) // data point still in current bin, extend high/low: { if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i); if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i); if (i == count-1) // last data point is in current bin, finalize bin: { currentBinData.close = value.at(i); currentBinData.key = timeBinOffset+(index)*timeBinSize; map.insert(currentBinData.key, currentBinData); } } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map: { // finalize current bin: currentBinData.close = value.at(i-1); currentBinData.key = timeBinOffset+(index-1)*timeBinSize; map.insert(currentBinData.key, currentBinData); // start next bin: currentBinIndex = index; currentBinData.open = value.at(i); currentBinData.high = value.at(i); currentBinData.low = value.at(i); } } return map; } /* inherits documentation from base class */ void QCPFinancial::draw(QCPPainter *painter) { // get visible data range: QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return; // draw visible data range according to configured style: switch (mChartStyle) { case QCPFinancial::csOhlc: drawOhlcPlot(painter, lower, upper+1); break; case QCPFinancial::csCandlestick: drawCandlestickPlot(painter, lower, upper+1); break; } } /* inherits documentation from base class */ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing if (mChartStyle == csOhlc) { if (mTwoColored) { // draw upper left half icon with positive color: painter->setBrush(mBrushPositive); painter->setPen(mPenPositive); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); // draw bottom right hald icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); } else { painter->setBrush(mBrush); painter->setPen(mPen); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); } } else if (mChartStyle == csCandlestick) { if (mTwoColored) { // draw upper left half icon with positive color: painter->setBrush(mBrushPositive); painter->setPen(mPenPositive); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); // draw bottom right hald icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); } else { painter->setBrush(mBrush); painter->setPen(mPen); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); } } } /* inherits documentation from base class */ QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPFinancialDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } // determine exact range by including width of bars/flags: if (haveLower && mKeyAxis) range.lower = range.lower-mWidth*0.5; if (haveUpper && mKeyAxis) range.upper = range.upper+mWidth*0.5; foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPFinancial::getValueRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; QCPFinancialDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { // high: if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0) || (inSignDomain == sdPositive && it.value().high > 0)) { if (it.value().high < range.lower || !haveLower) { range.lower = it.value().high; haveLower = true; } if (it.value().high > range.upper || !haveUpper) { range.upper = it.value().high; haveUpper = true; } } // low: if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0) || (inSignDomain == sdPositive && it.value().low > 0)) { if (it.value().low < range.lower || !haveLower) { range.lower = it.value().low; haveLower = true; } if (it.value().low > range.upper || !haveUpper) { range.upper = it.value().low; haveUpper = true; } } ++it; } foundRange = haveLower && haveUpper; return range; } /*! \internal Draws the data from \a begin to \a end as OHLC bars with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc. */ void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QPen linePen; if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) linePen = mSelectedPen; else if (mTwoColored) linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; else linePen = mPen; painter->setPen(linePen); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw backbone: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low))); // draw open: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides painter->drawLine(QPointF(keyPixel-keyWidthPixels, openPixel), QPointF(keyPixel, openPixel)); // draw close: painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel)); } } else { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) linePen = mSelectedPen; else if (mTwoColored) linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; else linePen = mPen; painter->setPen(linePen); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw backbone: painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel)); // draw open: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides painter->drawLine(QPointF(openPixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel)); // draw close: painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels)); } } } /*! \internal Draws the data from \a begin to \a end as Candlesticks with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick. */ void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QPen linePen; QBrush boxBrush; if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) { linePen = mSelectedPen; boxBrush = mSelectedBrush; } else if (mTwoColored) { if (it.value().close >= it.value().open) { linePen = mPenPositive; boxBrush = mBrushPositive; } else { linePen = mPenNegative; boxBrush = mBrushNegative; } } else { linePen = mPen; boxBrush = mBrush; } painter->setPen(linePen); painter->setBrush(boxBrush); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw high: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); // draw low: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close)))); // draw open-close box: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); painter->drawRect(QRectF(QPointF(keyPixel-keyWidthPixels, closePixel), QPointF(keyPixel+keyWidthPixels, openPixel))); } } else // keyAxis->orientation() == Qt::Vertical { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) { linePen = mSelectedPen; boxBrush = mSelectedBrush; } else if (mTwoColored) { if (it.value().close >= it.value().open) { linePen = mPenPositive; boxBrush = mBrushPositive; } else { linePen = mPenNegative; boxBrush = mBrushNegative; } } else { linePen = mPen; boxBrush = mBrush; } painter->setPen(linePen); painter->setBrush(boxBrush); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw high: painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); // draw low: painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel)); // draw open-close box: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); painter->drawRect(QRectF(QPointF(closePixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel+keyWidthPixels))); } } } /*! \internal This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end. */ double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = std::numeric_limits<double>::max(); QCPFinancialDataMap::const_iterator it; if (keyAxis->orientation() == Qt::Horizontal) { for (it = begin; it != end; ++it) { double keyPixel = keyAxis->coordToPixel(it.value().key); // calculate distance to backbone: double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } else // keyAxis->orientation() == Qt::Vertical { for (it = begin; it != end; ++it) { double keyPixel = keyAxis->coordToPixel(it.value().key); // calculate distance to backbone: double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } return qSqrt(minDistSqr); } /*! \internal This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a end. */ double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = std::numeric_limits<double>::max(); QCPFinancialDataMap::const_iterator it; if (keyAxis->orientation() == Qt::Horizontal) { for (it = begin; it != end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); QCPRange boxValueRange(it.value().close, it.value().open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box { currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; } else { // calculate distance to high/low lines: double keyPixel = keyAxis->coordToPixel(it.value().key); double highLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))), pos); double lowLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))), pos); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } else // keyAxis->orientation() == Qt::Vertical { for (it = begin; it != end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); QCPRange boxValueRange(it.value().close, it.value().open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box { currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; } else { // calculate distance to high/low lines: double keyPixel = keyAxis->coordToPixel(it.value().key); double highLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel), pos); double lowLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel), pos); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } return qSqrt(minDistSqr); } /*! \internal called by the drawing methods to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie just outside of the visible range. if the plottable contains no data, both \a lower and \a upper point to constEnd. \see QCPGraph::getVisibleDataBounds */ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upper = mData->constEnd(); return; } // get visible data range as QMap iterators QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); QCPFinancialDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemStraightLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemStraightLine \brief A straight line that spans infinitely in both directions \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a point1 and \a point2, which define the straight line. */ /*! Creates a straight line item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), point1(createPosition(QLatin1String("point1"))), point2(createPosition(QLatin1String("point2"))) { point1->setCoords(0, 0); point2->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemStraightLine::~QCPItemStraightLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { QVector2D start(point1->pixelPoint()); QVector2D end(point2->pixelPoint()); // get visible segment of straight line inside clipRect: double clipPad = mainPen().widthF(); QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); } } /*! \internal finds the shortest distance of \a point to the straight line defined by the base point \a base and the direction vector \a vec. This is a helper function for \ref selectTest. */ double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const { return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); } /*! \internal Returns the section of the straight line defined by \a base and direction vector \a vec, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const { double bx, by; double gamma; QLineF result; if (vec.x() == 0 && vec.y() == 0) return result; if (qFuzzyIsNull(vec.x())) // line is vertical { // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical } else if (qFuzzyIsNull(vec.y())) // line is horizontal { // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal } else // line is skewed { QList<QVector2D> pointVectors; // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); // check bottom of rect: bx = rect.left(); by = rect.bottom(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); // check right of rect: bx = rect.right(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QVector2D pv1, pv2; for (int i=0; i<pointVectors.size()-1; ++i) { for (int k=i+1; k<pointVectors.size(); ++k) { double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared(); if (distSqr > distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemStraightLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemLine \brief A line from one point to another \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition(QLatin1String("start"))), end(createPosition(QLatin1String("end"))) { start->setCoords(0, 0); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemLine::~QCPItemLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { QVector2D startVec(start->pixelPoint()); QVector2D endVec(end->pixelPoint()); if (startVec.toPoint() == endVec.toPoint()) return; // get visible segment of straight line inside clipRect: double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); clipPad = qMax(clipPad, (double)mainPen().widthF()); QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, startVec, startVec-endVec); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, endVec, endVec-startVec); } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const { bool containsStart = rect.contains(start.x(), start.y()); bool containsEnd = rect.contains(end.x(), end.y()); if (containsStart && containsEnd) return QLineF(start.toPointF(), end.toPointF()); QVector2D base = start; QVector2D vec = end-start; double bx, by; double gamma, mu; QLineF result; QList<QVector2D> pointVectors; if (!qFuzzyIsNull(vec.y())) // line is not horizontal { // check top of rect: bx = rect.left(); by = rect.top(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); } // check bottom of rect: bx = rect.left(); by = rect.bottom(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); } } if (!qFuzzyIsNull(vec.x())) // line is not vertical { // check left of rect: bx = rect.left(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); } // check right of rect: bx = rect.right(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); } } if (containsStart) pointVectors.append(start); if (containsEnd) pointVectors.append(end); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QVector2D pv1, pv2; for (int i=0; i<pointVectors.size()-1; ++i) { for (int k=i+1; k<pointVectors.size(); ++k) { double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared(); if (distSqr > distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemCurve \brief A curved line from one point to another \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. */ /*! Creates a curve item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition(QLatin1String("start"))), startDir(createPosition(QLatin1String("startDir"))), endDir(createPosition(QLatin1String("endDir"))), end(createPosition(QLatin1String("end"))) { start->setCoords(0, 0); startDir->setCoords(0.5, 0); endDir->setCoords(0, 0.5); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemCurve::~QCPItemCurve() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF startVec(start->pixelPoint()); QPointF startDirVec(startDir->pixelPoint()); QPointF endDirVec(endDir->pixelPoint()); QPointF endVec(end->pixelPoint()); QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); QPolygonF polygon = cubicPath.toSubpathPolygons().first(); double minDistSqr = std::numeric_limits<double>::max(); for (int i=1; i<polygon.size(); ++i) { double distSqr = distSqrToLine(polygon.at(i-1), polygon.at(i), pos); if (distSqr < minDistSqr) minDistSqr = distSqr; } return qSqrt(minDistSqr); } /* inherits documentation from base class */ void QCPItemCurve::draw(QCPPainter *painter) { QPointF startVec(start->pixelPoint()); QPointF startDirVec(startDir->pixelPoint()); QPointF endDirVec(endDir->pixelPoint()); QPointF endVec(end->pixelPoint()); if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash return; QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); // paint visible segment, if existent: QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); QRect cubicRect = cubicPath.controlPointRect().toRect(); if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position cubicRect.adjust(0, 0, 1, 1); if (clip.intersects(cubicRect)) { painter->setPen(mainPen()); painter->drawPath(cubicPath); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemCurve::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemRect \brief A rectangle \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle. */ /*! Creates a rectangle item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() { } /*! Sets the pen that will be used to draw the line of the rectangle \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectSelectTest(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); if (p1.toPoint() == p2.toPoint()) return; QRectF rect = QRectF(p1, p2).normalized(); double clipPad = mainPen().widthF(); QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(rect); } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPoint(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemRect::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemRect::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemText //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemText \brief A text label \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)) { position->setCoords(0, 0); setRotation(0); setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); setPositionAlignment(Qt::AlignCenter); setText(QLatin1String("text")); setPen(Qt::NoPen); setSelectedPen(Qt::NoPen); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setColor(Qt::black); setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() { } /*! Sets the color of the text. */ void QCPItemText::setColor(const QColor &color) { mColor = color; } /*! Sets the color of the text that will be used when the item is selected. */ void QCPItemText::setSelectedColor(const QColor &color) { mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the font of the text. \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { mFont = font; } /*! Sets the font of the text that will be used when the item is selected. \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. Examples: \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the bottom left corner of the text rect. If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { mPositionAlignment = alignment; } /*! Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { mTextAlignment = alignment; } /*! Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated around \a position. */ void QCPItemText::setRotation(double degrees) { mRotation = degrees; } /*! Sets the distance between the border of the text rectangle and the text. The appearance (and visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. */ void QCPItemText::setPadding(const QMargins &padding) { mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; // The rect may be rotated, so we transform the actual clicked pos to the rotated // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: QPointF positionPixels(position->pixelPoint()); QTransform inputTransform; inputTransform.translate(positionPixels.x(), positionPixels.y()); inputTransform.rotate(-mRotation); inputTransform.translate(-positionPixels.x(), -positionPixels.y()); QPointF rotatedPos = inputTransform.map(pos); QFontMetrics fontMetrics(mFont); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); textBoxRect.moveTopLeft(textPos.toPoint()); return rectSelectTest(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { QPointF pos(position->pixelPoint()); QTransform transform = painter->transform(); transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); painter->setFont(mainFont()); QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); textBoxRect.moveTopLeft(textPos.toPoint()); double clipPad = mainPen().widthF(); QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { painter->setTransform(transform); if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(textBoxRect); } painter->setBrush(Qt::NoBrush); painter->setPen(QPen(mainColor())); painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPoint(int anchorId) const { // get actual rect points (pretty much copied from draw function): QPointF pos(position->pixelPoint()); QTransform transform; transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); QFontMetrics fontMetrics(mainFont()); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textBoxRect.moveTopLeft(textPos.toPoint()); QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); switch (anchorId) { case aiTopLeft: return rectPoly.at(0); case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; case aiTopRight: return rectPoly.at(1); case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; case aiBottomRight: return rectPoly.at(2); case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; case aiBottomLeft: return rectPoly.at(3); case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) return pos; QPointF result = pos; // start at top left if (positionAlignment.testFlag(Qt::AlignHCenter)) result.rx() -= rect.width()/2.0; else if (positionAlignment.testFlag(Qt::AlignRight)) result.rx() -= rect.width(); if (positionAlignment.testFlag(Qt::AlignVCenter)) result.ry() -= rect.height()/2.0; else if (positionAlignment.testFlag(Qt::AlignBottom)) result.ry() -= rect.height(); return result; } /*! \internal Returns the font that should be used for drawing text. Returns mFont when the item is not selected and mSelectedFont when it is. */ QFont QCPItemText::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the color that should be used for drawing text. Returns mColor when the item is not selected and mSelectedColor when it is. */ QColor QCPItemText::mainColor() const { return mSelected ? mSelectedColor : mColor; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemText::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemText::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemEllipse //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemEllipse \brief An ellipse \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. */ /*! Creates an ellipse item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), top(createAnchor(QLatin1String("top"), aiTop)), topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), right(createAnchor(QLatin1String("right"), aiRight)), bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), left(createAnchor(QLatin1String("left"), aiLeft)), center(createAnchor(QLatin1String("center"), aiCenter)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() { } /*! Sets the pen that will be used to draw the line of the ellipse \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; double result = -1; QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); QPointF center((p1+p2)/2.0); double a = qAbs(p1.x()-p2.x())/2.0; double b = qAbs(p1.y()-p2.y())/2.0; double x = pos.x()-center.x(); double y = pos.y()-center.y(); // distance to border: double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); result = qAbs(c-1)*qSqrt(x*x+y*y); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (x*x/(a*a) + y*y/(b*b) <= 1) result = mParentPlot->selectionTolerance()*0.99; } return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); if (p1.toPoint() == p2.toPoint()) return; QRectF ellipseRect = QRectF(p1, p2).normalized(); QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); #ifdef __EXCEPTIONS try // drawEllipse sometimes throws exceptions if ellipse is too big { #endif painter->drawEllipse(ellipseRect); #ifdef __EXCEPTIONS } catch (...) { qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; setVisible(false); } #endif } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); switch (anchorId) { case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemEllipse::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemEllipse::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPixmap \brief An arbitrary pixmap \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. */ /*! Creates a rectangle item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)), mScaledPixmapInvalidated(true) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(Qt::NoPen); setSelectedPen(QPen(Qt::blue)); setScaled(false, Qt::KeepAspectRatio, Qt::SmoothTransformation); } QCPItemPixmap::~QCPItemPixmap() { } /*! Sets the pixmap that will be displayed. */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { mPixmap = pixmap; mScaledPixmapInvalidated = true; if (mPixmap.isNull()) qDebug() << Q_FUNC_INFO << "pixmap is null"; } /*! Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a bottomRight positions. */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) { mScaled = scaled; mAspectRatioMode = aspectRatioMode; mTransformationMode = transformationMode; mScaledPixmapInvalidated = true; } /*! Sets the pen that will be used to draw a border around the pixmap. \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return rectSelectTest(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { bool flipHorz = false; bool flipVert = false; QRect rect = getFinalRect(&flipHorz, &flipVert); double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) { updateScaledPixmap(rect, flipHorz, flipVert); painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); QPen pen = mainPen(); if (pen.style() != Qt::NoPen) { painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawRect(rect); } } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const { bool flipHorz; bool flipVert; QRect rect = getFinalRect(&flipHorz, &flipVert); // we actually want denormal rects (negative width/height) here, so restore // the flipped state: if (flipHorz) rect.adjust(rect.width(), 0, -rect.width(), 0); if (flipVert) rect.adjust(0, rect.height(), 0, -rect.height()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { if (mPixmap.isNull()) return; if (mScaled) { if (finalRect.isNull()) finalRect = getFinalRect(&flipHorz, &flipVert); if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()) { mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode); if (flipHorz || flipVert) mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); } } else if (!mScaledPixmap.isNull()) mScaledPixmap = QPixmap(); mScaledPixmapInvalidated = false; } /*! \internal Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const { QRect result; bool flipHorz = false; bool flipVert = false; QPoint p1 = topLeft->pixelPoint().toPoint(); QPoint p2 = bottomRight->pixelPoint().toPoint(); if (p1 == p2) return QRect(p1, QSize(0, 0)); if (mScaled) { QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); QPoint topLeft = p1; if (newSize.width() < 0) { flipHorz = true; newSize.rwidth() *= -1; topLeft.setX(p2.x()); } if (newSize.height() < 0) { flipVert = true; newSize.rheight() *= -1; topLeft.setY(p2.y()); } QSize scaledSize = mPixmap.size(); scaledSize.scale(newSize, mAspectRatioMode); result = QRect(topLeft, scaledSize); } else { result = QRect(p1, mPixmap.size()); } if (flippedHorz) *flippedHorz = flipHorz; if (flippedVert) *flippedVert = flipVert; return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemPixmap::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemTracer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemTracer \brief Item that sticks to QCPGraph data points \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt the coordinate axes of the graph and update its \a position to be on the graph's data. This means the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref QCPItemPosition::setParentAnchor. \note The tracer position is only automatically updated upon redraws. So when the data of the graph changes and immediately afterwards (without a redraw) the a position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref updatePosition must be called manually, prior to reading the tracer coordinates. */ /*! Creates a tracer item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), mGraph(0) { position->setCoords(0, 0); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setStyle(tsCrosshair); setSize(6); setInterpolating(false); setGraphKey(0); } QCPItemTracer::~QCPItemTracer() { } /*! Sets the pen that will be used to draw the line of the tracer \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare does, \ref tsCrosshair does not). */ void QCPItemTracer::setSize(double size) { mSize = size; } /*! Sets the style/visual appearance of the tracer. If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { if (graph) { if (graph->parentPlot() == mParentPlot) { position->setType(QCPItemPosition::ptPlotCoords); position->setAxes(graph->keyAxis(), graph->valueAxis()); mGraph = graph; updatePosition(); } else qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; } else { mGraph = 0; } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF center(position->pixelPoint()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return -1; case tsPlus: { if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); break; } case tsCrosshair: { return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { // distance to border: double centerDist = QVector2D(center-pos).length(); double circleLine = w; double result = qAbs(centerDist-circleLine); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (centerDist <= circleLine) result = mParentPlot->selectionTolerance()*0.99; } return result; } break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectSelectTest(rect, pos, filledRect); } break; } } return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { updatePosition(); if (mStyle == tsNone) return; painter->setPen(mainPen()); painter->setBrush(mainBrush()); QPointF center(position->pixelPoint()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return; case tsPlus: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); } break; } case tsCrosshair: { if (center.y() > clip.top() && center.y() < clip.bottom()) painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); if (center.x() > clip.left() && center.x() < clip.right()) painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); break; } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawEllipse(center, w, w); break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); break; } } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { if (mGraph) { if (mParentPlot->hasPlottable(mGraph)) { if (mGraph->data()->size() > 1) { QCPDataMap::const_iterator first = mGraph->data()->constBegin(); QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; if (mGraphKey < first.key()) position->setCoords(first.key(), first.value().value); else if (mGraphKey > last.key()) position->setCoords(last.key(), last.value().value); else { QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); if (it != first) // mGraphKey is somewhere between iterators { QCPDataMap::const_iterator prevIt = it-1; if (mInterpolating) { // interpolate between iterators around mGraphKey: double slope = 0; if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); } else { // find iterator with key closest to mGraphKey: if (mGraphKey < (prevIt.key()+it.key())*0.5) it = prevIt; position->setCoords(it.key(), it.value().value); } } else // mGraphKey is exactly on first iterator position->setCoords(it.key(), it.value().value); } } else if (mGraph->data()->size() == 1) { QCPDataMap::const_iterator it = mGraph->data()->constBegin(); position->setCoords(it.key(), it.value().value); } else qDebug() << Q_FUNC_INFO << "graph has no data"; } else qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemTracer::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemTracer::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemBracket //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemBracket \brief A bracket for referencing/highlighting certain parts in the plot. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. \image html QCPItemBracket-length.png <center>Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center> It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), left(createPosition(QLatin1String("left"))), right(createPosition(QLatin1String("right"))), center(createAnchor(QLatin1String("center"), aiCenter)) { left->setCoords(0, 0); right->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setLength(8); setStyle(bsCalligraphic); } QCPItemBracket::~QCPItemBracket() { } /*! Sets the pen that will be used to draw the bracket. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction) \image html QCPItemBracket-length.png <center>Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center> */ void QCPItemBracket::setLength(double length) { mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return -1; QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; switch (mStyle) { case QCPItemBracket::bsSquare: case QCPItemBracket::bsRound: { double a = distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); double b = distSqrToLine((centerVec-widthVec+lengthVec).toPointF(), (centerVec-widthVec).toPointF(), pos); double c = distSqrToLine((centerVec+widthVec+lengthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); return qSqrt(qMin(qMin(a, b), c)); } case QCPItemBracket::bsCurly: case QCPItemBracket::bsCalligraphic: { double a = distSqrToLine((centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); double b = distSqrToLine((centerVec-widthVec+lengthVec*0.7f).toPointF(), (centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); double c = distSqrToLine((centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); double d = distSqrToLine((centerVec+widthVec+lengthVec*0.7f).toPointF(), (centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); return qSqrt(qMin(qMin(a, b), qMin(c, d))); } } return -1; } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return; QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; QPolygon boundingPoly; boundingPoly << leftVec.toPoint() << rightVec.toPoint() << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); if (clip.intersects(boundingPoly.boundingRect())) { painter->setPen(mainPen()); switch (mStyle) { case bsSquare: { painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); break; } case bsRound: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCurly: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCalligraphic: { painter->setPen(Qt::NoPen); painter->setBrush(QBrush(mainPen().color())); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } } } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const { QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return leftVec.toPointF(); QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; switch (anchorId) { case aiCenter: return centerVec.toPointF(); } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemBracket::mainPen() const { return mSelected ? mSelectedPen : mPen; }
851,667
C++
35.158105
243
0.697473
adegirmenci/HBL-ICEbot/License.md
MIT License Copyright (c) 2017 Alperen Degirmenci Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1,075
Markdown
47.909089
78
0.806512
adegirmenci/HBL-ICEbot/main.cpp
#include "icebot_gui.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); ICEbot_GUI w; w.show(); return a.exec(); }
172
C++
13.416666
32
0.610465
adegirmenci/HBL-ICEbot/README.md
# HBL-ICEbot Codebase for the robotic ultrasound catheter system developed at the Harvard Biorobotics Laboratory. See [project page](http://biorobotics.harvard.edu/ICEbot_.html) for description and list of publications. ## Prerequisites You will need the following libraries and drivers installed on your system: * OpenCV (2.4.1x) * Eigen * Boost * Maxon EPOS Drivers * OpenHaptics * LabJack * Ascension TrakStar Drivers * StarTech UBS3HDCAP Drivers ## Built With * Qt 5.7 * MSVC 2012 ## Authors * **Alperen Degirmenci** - *Lead developer* - [Harvard Biorobotics Lab](https://scholar.harvard.edu/adegirmenci/) * **Paul M. Loschak** - *Contributions to the controller* ## License This project is licensed under the MIT License. ## Acknowledgments * This work was supported by the Harvard University John A. Paulson School of Engineering and Applied Sciences, American Heart Association Grant #15PRE22710043, the National Institutes of Health Grant #1R21EB018938, and the NVIDIA Academic Hardware Grant Program.
1,020
Markdown
29.939393
263
0.77451
adegirmenci/HBL-ICEbot/ControllerWidget/filtfilt.h
#ifndef FILTFILT_H #define FILTFILT_H #include <vector> #include <algorithm> #include <iostream> #include <numeric> #include <Eigen/Dense> #include <Eigen/StdVector> #include <memory> #include <QElapsedTimer> #include <boost/math/special_functions/sinc.hpp> #include "kinematics_4dof.h" // for pi #include "../icebot_definitions.h" //#include <spuce/filters/design_window.h> //#include <spuce/filters/design_fir.h> //#include <spuce/typedefs.h> //#include <spuce/filters/fir_coeff.h> //#include <spuce/filters/window.h> //#include <spuce/filters/fir.h> //#include <FIR.h> // Adapted from: // http://stackoverflow.com/questions/17675053/matlabs-filtfilt-algorithm/27270420#27270420 // Mainly for CycleModel //typedef Eigen::Matrix< double, Eigen::Dynamic , 1> EigenVectorFiltered; //typedef Eigen::Matrix< double, Eigen::Dynamic , 7> EigenMatrixFiltered; typedef Eigen::VectorXd EigenVectorFiltered; typedef Eigen::MatrixXd EigenMatrixFiltered; typedef Eigen::Matrix< double, N_POLAR , 1> EigenVectorPolar; typedef Eigen::Matrix< double, N_POLAR , 7> EigenMatrixPolar; typedef Eigen::Matrix< double, N_RECT , 1> EigenVectorRectangular; typedef Eigen::Matrix< double, N_RECT , 7> EigenMatrixRectangular; // Affine Transform typedef Eigen::Transform<double,3,Eigen::Affine> EigenAffineTransform3d; typedef Eigen::Matrix<double, 7 , 1> EigenVector7d; // in order to use vector with Eigen Transform, we need this typedef typedef std::vector< EigenAffineTransform3d, Eigen::aligned_allocator<EigenAffineTransform3d> > EigenStdVecAffineTform3d; typedef std::vector< EigenVector7d, Eigen::aligned_allocator<EigenVector7d> > EigenStdVecVector7d; // most efficient would be to use shared_ptr typedef std::vector< std::shared_ptr<EigenVector7d> > EigenStdVecSharedPtrVector7d; class filtfilt { public: filtfilt(); ~filtfilt(); // X is the original data, Y is the output void run(const std::vector<double> &X, std::vector<double> &Y); void run(const std::vector<double> &X, EigenVectorFiltered &Y); void run(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y); void run(const EigenStdVecVector7d &X, EigenMatrixFiltered &Y); // TODO : add function to change the heartrate, sampling freq, and maybe filter order void setFilterCoefficients(const std::vector<double> &B, const std::vector<double> &A); private: void updateFilterParameters(); // helper functions void filter(const std::vector<double> &X, std::vector<double> &Y, std::vector<double> &Zi); void filter(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y, EigenStdVecVector7d &Zi); void add_index_range(std::vector<int> &indices, int beg, int end, int inc = 1); void add_index_const(std::vector<int> &indices, int value, size_t numel); void append_vector(std::vector<double> &vec, const std::vector<double> &tail); void append_vector(EigenStdVecVector7d &vec, const EigenStdVecVector7d &tail); std::vector<double> subvector_reverse(const std::vector<double> &vec, int idx_end, int idx_start); EigenStdVecVector7d subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start); void subvector_reverseEig(const std::vector<double> &vec, int idx_end, int idx_start, EigenVectorFiltered &Y); void subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start, EigenMatrixFiltered &Y); inline int max_val(const std::vector<int>& vec) { return std::max_element(vec.begin(), vec.end())[0]; } std::vector<double> FIR_LPF_LeastSquares(size_t L, const double deltaT); std::vector<double> genHammingWindow(const size_t L); std::vector<double> calcWindow(size_t m, size_t n); // data members std::vector<double> m_A, m_B; // filter coefficients int m_na; int m_nb; int m_nfilt; int m_nfact; std::vector<int> m_rows, m_cols; std::vector<double> m_data; std::shared_ptr<Eigen::MatrixXd> m_zzi; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; #endif // FILTFILT_H
4,049
C
35.160714
121
0.721907
adegirmenci/HBL-ICEbot/ControllerWidget/gainswidget.h
#ifndef GAINSWIDGET_H #define GAINSWIDGET_H #include <QWidget> #include <QCloseEvent> #include <QVector> struct GainsPYRT { double kPitchMin; double kPitch; double kPitchMax; double kYawMin; double kYaw; double kYawMax; double kRollMin; double kRoll; double kRollMax; double kTransMin; double kTrans; double kTransMax; }; struct ConvergenceLimits { double posMin; double posMax; double angleMin; double angleMax; }; Q_DECLARE_METATYPE(GainsPYRT) Q_DECLARE_METATYPE(ConvergenceLimits) namespace Ui { class gainsWidget; } class gainsWidget : public QWidget { Q_OBJECT public: explicit gainsWidget(QWidget *parent = 0); ~gainsWidget(); signals: void closeGainsWindow(); void setGains(GainsPYRT gains); void setLimits(ConvergenceLimits limits); public slots: void on_setGainsButton_clicked(); void on_setLimitsButton_clicked(); private slots: void on_closeButton_clicked(); private: Ui::gainsWidget *ui; void closeEvent(QCloseEvent *event); }; #endif // GAINSWIDGET_H
1,087
C
15
46
0.701012
adegirmenci/HBL-ICEbot/ControllerWidget/respmodelwidget.cpp
#include "respmodelwidget.h" #include "ui_respmodelwidget.h" respModelWidget::respModelWidget(QWidget *parent) : QWidget(parent), ui(new Ui::respModelWidget) { ui->setupUi(this); this->setWindowTitle("Respiration Modeling"); // QCustomPlot // include this section to fully disable antialiasing for higher performance: ui->plotWidget->setNotAntialiasedElements(QCP::aeAll); QFont font; font.setStyleStrategy(QFont::NoAntialias); ui->plotWidget->xAxis->setTickLabelFont(font); ui->plotWidget->yAxis->setTickLabelFont(font); ui->plotWidget->legend->setFont(font); ui->plotWidget->addGraph(); // blue line ui->plotWidget->graph(0)->setPen(QPen(Qt::blue)); //ui->plotWidget->graph(0)->setBrush(QBrush(QColor(240, 255, 200))); ui->plotWidget->graph(0)->setAntialiasedFill(false); ui->plotWidget->addGraph(); // red line ui->plotWidget->graph(1)->setPen(QPen(Qt::red)); ui->plotWidget->graph(1)->setAntialiasedFill(false); ui->plotWidget->addGraph(); // black line ui->plotWidget->graph(2)->setPen(QPen(Qt::black)); ui->plotWidget->graph(2)->setAntialiasedFill(false); ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltDateTime); ui->plotWidget->xAxis->setDateTimeFormat("hh:mm:ss"); ui->plotWidget->xAxis->setAutoTickStep(false); ui->plotWidget->xAxis->setTickStep(2); ui->plotWidget->axisRect()->setupFullAxesBox(); // make left and bottom axes transfer their ranges to right and top axes: connect(ui->plotWidget->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->xAxis2, SLOT(setRange(QCPRange))); connect(ui->plotWidget->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->yAxis2, SLOT(setRange(QCPRange))); m_lastPlotKey = 0.0; } respModelWidget::~respModelWidget() { delete ui; } void respModelWidget::on_closeButton_clicked() { emit closeRespModelWindow(); } void respModelWidget::on_initializeButton_clicked() { ui->initializeButton->setEnabled(false); ui->reInitButton->setEnabled(false); ui->stopButton->setEnabled(true); emit initializeRespModel(); } void respModelWidget::on_reInitButton_clicked() { ui->initializeButton->setEnabled(false); ui->reInitButton->setEnabled(false); ui->stopButton->setEnabled(true); emit re_initializeRespModel(); } void respModelWidget::on_stopButton_clicked() { ui->initializeButton->setEnabled(false); ui->reInitButton->setEnabled(true); ui->stopButton->setEnabled(false); emit stopRespModel(); } void respModelWidget::receiveDataFromRespModel(int numSamples, bool isTrained, bool inVivoMode, double omega0)//, //EigenVectorFiltered Bird4_filtered, //EigenVectorFiltered Bird4_filtered_new, //EigenVectorFiltered breathSignalFromModel) { // update things ui->samplesCollectedSpinBox->setValue(numSamples); ui->periodSpinBox->setValue(2.0*pi/omega0); if(inVivoMode) ui->inVivoModeLabel->setStyleSheet("QLabel { background-color : green;}"); else ui->inVivoModeLabel->setStyleSheet("QLabel { background-color : red;}"); if(isTrained) ui->modelIsTrainedLabel->setStyleSheet("QLabel { background-color : green;}"); else ui->modelIsTrainedLabel->setStyleSheet("QLabel { background-color : red;}"); // // plotting // double key = numSamples/150.0; // static double lastPointKey = 0; // if( (key - lastPointKey) > 0.01) // at most add point every 10 ms // { // if( (numSamples > 2*N_SAMPLES) && isTrained ) // { // ui->plotWidget->graph(1)->addData(key, Bird4_filtered_new(N_SAMPLES-1)); // ui->plotWidget->graph(2)->addData(key, breathSignalFromModel(N_SAMPLES-1)); // } // else // { // if( (numSamples > N_SAMPLES) && isTrained ) // { // ui->plotWidget->graph(1)->addData(key, Bird4_filtered_new(numSamples-N_SAMPLES-1)); // ui->plotWidget->graph(2)->addData(key, breathSignalFromModel(numSamples-N_SAMPLES-1)); // } // else // { // ui->plotWidget->graph(0)->addData(key, Bird4_filtered(numSamples-1)); // } // } // // remove data of lines that's outside visible range: // ui->plotWidget->graph(1)->removeDataBefore(key-8); // ui->plotWidget->graph(2)->removeDataBefore(key-8); // // rescale value (vertical) axis to fit the current data: // ui->plotWidget->graph(1)->rescaleValueAxis(); // lastPointKey = key; // } // // make key axis range scroll with the data (at a constant range size of 8): // //ui->plotWidget->xAxis->setRange(key+0.25, 8, Qt::AlignRight); // ui->plotWidget->replot(); } void respModelWidget::plotBird4(unsigned int plotID, double time, double value) { // printf(">>> plotBird4 Received\n"); ui->plotWidget->graph(plotID)->addData(time, value); if(plotID == 0) { if( (time - m_lastPlotKey) > 0.030) // plot every 30ms { // make key axis range scroll with the data (at a constant range size of 8): ui->plotWidget->xAxis->setRange(time, 15.0, Qt::AlignRight); // remove data of lines that's outside visible range: ui->plotWidget->graph(0)->removeDataBefore(time-15.0); ui->plotWidget->graph(1)->removeDataBefore(time-15.0); ui->plotWidget->graph(2)->removeDataBefore(time-15.0); //ui->plotWidget->graph(0)->rescaleValueAxis(); ui->plotWidget->yAxis->rescale(); ui->plotWidget->replot(); m_lastPlotKey = time; } } } void respModelWidget::closeEvent(QCloseEvent *event) { emit closeRespModelWindow(); event->accept(); } void respModelWidget::on_futureSamplesSpinBox_valueChanged(int arg1) { emit newFutureSamplesValue(arg1); } void respModelWidget::on_bird4RadioButton_clicked() { emit changePlotFocus(RESP_MODEL_PLOT_BIRD4); } void respModelWidget::on_CTradioButton_clicked() { emit changePlotFocus(RESP_MODEL_PLOT_CT); }
6,365
C++
33.597826
117
0.625452
adegirmenci/HBL-ICEbot/ControllerWidget/controllerwidget.h
#ifndef CONTROLLERWIDGET_H #define CONTROLLERWIDGET_H #include <QWidget> #include <QThread> #include <QFileDialog> #include <QTextStream> #include <QString> #include <QStringList> #include <QTimer> #include "controllerthread.h" #include "gainswidget.h" #include "respmodelwidget.h" namespace Ui { class ControllerWidget; } class ControllerWidget : public QWidget { Q_OBJECT public: explicit ControllerWidget(QWidget *parent = 0); ~ControllerWidget(); ControllerThread *m_worker; signals: void tellWorkerToPrintThreadID(); void updateJointSpaceCommand(double pitch, double yaw, double roll, double trans); void updateConfigSpaceCommand(double alpha, double theta, double gamma, double d); void updateTaskSpaceCommand(double x, double y, double z, double delPsi, bool isAbsolute); void tellWorkerToResetBB(); void startControlCycle(); // start control loop in worker void stopControlCycle(); // stop control loop in worker void updateModeFlags(ModeFlags flags); void updateUSangle(double usAngle); void workerStartSweep(unsigned int nSteps_, double stepAngle_, double convLimit_, qint64 imgDuration_); void workerAbortSweep(); private slots: void workerStatusChanged(int status); void receiveMsgFromWorker(QString msg, int destination); void on_testButton_clicked(); void on_taskSpaceGroupBox_toggled(bool arg1); void on_configSpaceGroupBox_toggled(bool arg1); void on_jointSpaceGroupBox_toggled(bool arg1); void on_updateJointSpaceButton_clicked(); void on_updateConfigSpaceButton_clicked(); void on_updateTaskSpaceButton_clicked(); void on_controllerToggleButton_clicked(); void on_resetBB_Button_clicked(); void on_adjustGainsButton_clicked(); void on_relativeRadiobutton_clicked(); void on_absoluteRadiobutton_clicked(); void on_updateFlagsButton_clicked(); void on_setUSangleButton_clicked(); void on_respModelButton_clicked(); void on_trajOpenFileButton_clicked(); void on_trajDriveButton_clicked(); void receiveCurrentXYZPSI(XYZPSI currXYZPSI); void driveTrajectory(); void on_sweepButton_clicked(); void on_abortSweepButton_clicked(); private: Ui::ControllerWidget *ui; gainsWidget *gainWidget; respModelWidget *m_respModelWidget; QThread m_thread; // Controller Thread will live in here XYZPSI m_currXYZPSI; unsigned int m_ctr; // trajectory std::vector<XYZPSI> m_XYZPSIs; bool m_keepDriving; size_t m_currTrajIdx; QTimer *m_trajTimer; }; #endif // CONTROLLERWIDGET_H
2,686
C
22.778761
94
0.710722
adegirmenci/HBL-ICEbot/ControllerWidget/controllerthread.cpp
#include "controllerthread.h" ControllerThread::ControllerThread(QObject *parent) : QObject(parent) { qRegisterMetaType<ModeFlags>("ModeFlags"); qRegisterMetaType<EigenVectorFiltered>("EigenVectorFiltered"); qRegisterMetaType<XYZPSI>("XYZPSI"); m_isEpochSet = false; m_isReady = false; m_keepControlling = false; m_abort = false; m_latestReading.resize(4); m_respModelInitializing = false; m_numCycles = 0; m_cathKin = Kinematics_4DOF(0.05*1000.0, 0.00135*1000.0, 0.90*0.0254*1000.0); // m_respModel = CyclicModel(); loadConstants(); // zero initialize m_targetPos = m_targetPos.Identity(); m_deltaXYZPsiToTarget << 0.0, 0.0, 0.0, 0.0; m_input_AbsXYZ << 0.0, 0.0, 0.0; m_input_RelXYZ << 0.0, 0.0, 0.0; m_input_delPsi = 0.0; m_dXYZPsi << 0.0, 0.0, 0.0, 0.0; // FOR IN VIVO EXP 6!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! setUSangle(0.0); // 75 deg for Exp 5, used 108 for ablation tracking at one point m_modeFlags.inVivoMode = IN_VIVO_OFF; // MATLAB #ifdef SVM_ON SVMregression_initialize(); #endif m_mutex = new QMutex(QMutex::NonRecursive); m_isReady = true; emit statusChanged(CONTROLLER_INITIALIZED); } ControllerThread::~ControllerThread() { // std::cout << "FwdKin\n" << m_cathKin.forwardKinematics(1,0.1,0.1,0).matrix() << std::endl; // std::cout << "Jacobian\n" << m_cathKin.JacobianNumeric(1,0.1,0.1,0).matrix() << std::endl; // std::cout << "InvKin3D\n" << m_cathKin.inverseKinematics3D(5,5,12,0.1) << std::endl; // Eigen::Transform<double, 3, Eigen::Affine> T_in(Eigen::Matrix<double, 4, 4>::Identity()); // std::cout << "T_in\n" << T_in.matrix() << std::endl; // Eigen::Vector4d configIn(0.0010, 0.0001, 0.0001, 0); // std::cout << "control_icra2016\n" << m_cathKin.control_icra2016(T_in, configIn, 0.0) << std::endl; qDebug() << "Ending ControllerThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; // stop controller stopControlCycle(); m_mutex->lock(); m_abort = true; m_mutex->unlock(); delete m_mutex; // MATLAB #ifdef SVM_ON SVMregression_terminate(); #endif emit finished(); } // ------------------------------ // SLOTS IMPLEMENTATION // ------------------------------ void ControllerThread::setEpoch(const QDateTime &epoch) { QMutexLocker locker(m_mutex); if(!m_keepControlling) { m_epoch = epoch; m_isEpochSet = true; emit logEventWithMessage(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_EPOCH_SET, m_epoch.toString("dd/MM/yyyy - hh:mm:ss.zzz")); } else emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_EPOCH_SET_FAILED); } void ControllerThread::printThreadID() { qDebug() << QTime::currentTime() << "Worker Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId()); m_respModel.testLPF(); } // THIS FUNCTION SHOULD NOT BE USED AT ALL void ControllerThread::receiveEMdata(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data) { // Data Format // | Sensor ID | Time Stamp | x | y | z | q1 | q2 | q3 | q4 | // | int | double | ... double ... | QMutexLocker locker(m_mutex); m_prevReading[sensorID] = m_latestReading[sensorID]; m_latestReading[sensorID] = data; QElapsedTimer elTimer; elTimer.start(); // TODO: emit signal to log receiveEMdata event //emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_EM_RECEIVED); switch(sensorID) { case EM_SENSOR_BB: Transform_From_EMreading(data, m_basTipPos_mobile); m_Box_BBmobile = m_basTipPos_mobile * m_BB_SBm.inverse(); m_BBfixed_BBmobile = m_BB_Box * m_Box_BBmobile; m_BBmobile_CT = m_Box_BBmobile.inverse()*m_curTipPos*m_STm_BT*m_BT_CT; break; case EM_SENSOR_BT: // process CT point Transform_From_EMreading(data, m_curTipPos); m_BB_CT_curTipPos = m_BB_Box*m_curTipPos*m_STm_BT*m_BT_CT; // convert to CT in terms of BBfixed break; case EM_SENSOR_INST: Transform_From_EMreading(data, m_targetPos); m_targetPos = m_targetPos * m_ISm_INSTR; m_BB_targetPos = m_BB_Box * m_targetPos; break; case EM_SENSOR_CHEST: Transform_From_EMreading(data, m_currChest); break; default: qDebug() << "SensorID not recognized!"; break; } qint64 elNsec = elTimer.nsecsElapsed(); qDebug() << "Nsec elapsed:" << elNsec; } void ControllerThread::receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings) { QMutexLocker locker(m_mutex); QElapsedTimer elTimer; elTimer.start(); Q_ASSERT(4 == readings.size()); m_prevReading = m_latestReading; m_latestReading = readings; // EM_SENSOR_BB: Transform_From_EMreading(readings[EM_SENSOR_BB], m_Box_SBm); // EM_SENSOR_BT Transform_From_EMreading(readings[EM_SENSOR_BT], m_curTipPos); // EM_SENSOR_INST: Transform_From_EMreading(readings[EM_SENSOR_INST], m_targetPos); // EM_SENSOR_CHEST: Transform_From_EMreading(readings[EM_SENSOR_CHEST], m_currChest); // Calculate T_BBmobile_CT m_basTipPos_mobile = m_Box_SBm; m_Box_BBmobile = m_Box_SBm * m_BB_SBm.inverse(); m_BBfixed_BBmobile = m_BB_Box * m_Box_BBmobile; // this is from MATLAB >>> Get BT w.r.t. mobile BB, rather than fixed BB // this is from MATLAB >>> m_BBmobile_BT = m_BBfixed_BBmobile.inverse() * m_BB_CT_curTipPos * m_BT_CT.inverse(); m_BBmobile_BT = m_Box_BBmobile.inverse() * m_curTipPos * m_STm_BT; // this is the original C++ >>> m_BBmobile_CT = m_Box_BBmobile.inverse() * m_curTipPos * m_STm_BT * m_BT_CT; m_BBmobile_CT = m_BBmobile_BT * m_BT_CT; //Calculate T_BB_CT_curTipPos: // process CT point m_BB_CT_curTipPos = m_BB_Box * m_curTipPos * m_STm_BT * m_BT_CT; // convert to CT in terms of BBfixed //Calculate T_BB_targetPos m_targetPos = m_targetPos * m_ISm_INSTR; // the tip of the instrument in EM coord m_BB_targetPos = m_BB_Box * m_targetPos; // the tip of the instr in BBfixed coord std::vector<double> T_BB_CT_curTipPos(m_BB_CT_curTipPos.matrix().data(), m_BB_CT_curTipPos.matrix().data() + m_BB_CT_curTipPos.matrix().size()); if(T_BB_CT_curTipPos.size() == 16) { QDateTime t; t.setMSecsSinceEpoch(readings[EM_SENSOR_BT].time*1000.0); emit logData(t.time(), m_numCycles, CONTROLLER_T_BB_CT_curTipPos, T_BB_CT_curTipPos); emit send_CT_toFrameClient(T_BB_CT_curTipPos, readings[EM_SENSOR_BT].time); } if(m_respModelInitializing) { // send training data //const EigenAffineTransform3d &T_BB_CT_curTipPos, //const EigenAffineTransform3d &T_BB_targetPos, //const EigenAffineTransform3d &T_Box_BBmobile, //const EigenAffineTransform3d &T_BB_Box, //const EigenAffineTransform3d &T_Bird4, m_respModel.addTrainingObservation(m_BB_CT_curTipPos, m_BB_targetPos, m_Box_BBmobile, m_BB_Box, m_currChest, readings[EM_SENSOR_CHEST].time); // check how many samples were sent and turn off flag if trained if(m_respModel.getNumSamples() == N_SAMPLES) { std::cout << "Train model.\n" << std::endl; m_respModel.trainModel(); if(m_respModel.isTrained()) { m_respModelInitializing = false; std::cout << "Model trained.\n" << std::endl; emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_INITIALIZED); } else { // ERROR! std::cout << "Error in training resp model!" << std::endl; emit logEvent(SRC_CONTROLLER, LOG_ERROR, QTime::currentTime(), CONTROLLER_RESP_MODEL_INIT_FAILED); } } } else if(m_respModel.isTrained()) { // send current data m_respModel.addObservation(m_currChest, readings[EM_SENSOR_CHEST].time); std::vector<double> omega = {m_respModel.getOmega()}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_PERIOD, omega); } if(!m_respModelInitializing) { controlCycle(); } // TODO : send data to resp model widget // size_t numSamples, // bool isTrained, // bool inVivoMode, // double omega0, // EigenVectorFiltered Bird4_filtered, // EigenVectorFiltered Bird4_filtered_new, // EigenVectorFiltered breathSignalFromModel); emit sendDataToRespModelWidget(m_respModel.getNumSamples(), m_respModel.isTrained(), m_respModel.isInVivoMode(), m_respModel.getOmega());//, // m_respModel.get_Bird4_filtered(), // m_respModel.get_Bird4_filtered_new(), // m_respModel.get_breathSignalFromModel()); qint64 elNsec = elTimer.nsecsElapsed(); std::cout << "EM receive Nsec elapsed: " << elNsec << std::endl; //std::cout << m_BB_CT_curTipPos.matrix() << std::endl; // display in GUI QString msg = QString("T_BBfixed_CT:\n"); msg += QString::number(m_BB_CT_curTipPos(0,0), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(0,1), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(0,2), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(0,3), 'f', 2) + "\n" + QString::number(m_BB_CT_curTipPos(1,0), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(1,1), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(1,2), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(1,3), 'f', 2) + "\n" + QString::number(m_BB_CT_curTipPos(2,0), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(2,1), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(2,2), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(2,3), 'f', 2) + "\n" + QString::number(m_BB_CT_curTipPos(3,0), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(3,1), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(3,2), 'f', 3) + " " + QString::number(m_BB_CT_curTipPos(3,3), 'f', 2) + "\n"; msg += QString("\nT_BBmobile_CT:\n") + QString::number(m_BBmobile_CT(0,0), 'f', 3) + " " + QString::number(m_BBmobile_CT(0,1), 'f', 3) + " " + QString::number(m_BBmobile_CT(0,2), 'f', 3) + " " + QString::number(m_BBmobile_CT(0,3), 'f', 2) + "\n" + QString::number(m_BBmobile_CT(1,0), 'f', 3) + " " + QString::number(m_BBmobile_CT(1,1), 'f', 3) + " " + QString::number(m_BBmobile_CT(1,2), 'f', 3) + " " + QString::number(m_BBmobile_CT(1,3), 'f', 2) + "\n" + QString::number(m_BBmobile_CT(2,0), 'f', 3) + " " + QString::number(m_BBmobile_CT(2,1), 'f', 3) + " " + QString::number(m_BBmobile_CT(2,2), 'f', 3) + " " + QString::number(m_BBmobile_CT(2,3), 'f', 2) + "\n" + QString::number(m_BBmobile_CT(3,0), 'f', 3) + " " + QString::number(m_BBmobile_CT(3,1), 'f', 3) + " " + QString::number(m_BBmobile_CT(3,2), 'f', 3) + " " + QString::number(m_BBmobile_CT(3,3), 'f', 2) + "\n"; msg += QString("\nT_BBfixed_Instr:\n") + QString::number(m_BB_targetPos(0,0), 'f', 3) + " " + QString::number(m_BB_targetPos(0,1), 'f', 3) + " " + QString::number(m_BB_targetPos(0,2), 'f', 3) + " " + QString::number(m_BB_targetPos(0,3), 'f', 2) + "\n" + QString::number(m_BB_targetPos(1,0), 'f', 3) + " " + QString::number(m_BB_targetPos(1,1), 'f', 3) + " " + QString::number(m_BB_targetPos(1,2), 'f', 3) + " " + QString::number(m_BB_targetPos(1,3), 'f', 2) + "\n" + QString::number(m_BB_targetPos(2,0), 'f', 3) + " " + QString::number(m_BB_targetPos(2,1), 'f', 3) + " " + QString::number(m_BB_targetPos(2,2), 'f', 3) + " " + QString::number(m_BB_targetPos(2,3), 'f', 2) + "\n" + QString::number(m_BB_targetPos(3,0), 'f', 3) + " " + QString::number(m_BB_targetPos(3,1), 'f', 3) + " " + QString::number(m_BB_targetPos(3,2), 'f', 3) + " " + QString::number(m_BB_targetPos(3,3), 'f', 2); emit sendMsgToWidget(msg, 0); //emit logEventWithMessage(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), 0, msg); } void ControllerThread::updateJointSpaceCommand(double pitch, double yaw, double roll, double trans) { // qDebug() << "New Joint Target Received"; QMutexLocker locker(m_mutex); // check limits // update motor QCs // emit event to DataLogger } void ControllerThread::updateConfigSpaceCommand(double alpha, double theta, double gamma, double d) { // this is not implemented at the moment, just test code // qDebug() << "New Config Target Received"; QMutexLocker locker(m_mutex); // run through kinematics Eigen::Transform<double,3,Eigen::Affine> tempT; tempT = m_cathKin.forwardKinematics(gamma, theta, alpha, d); // check limits double norm = (m_targetPos.matrix().col(3) - tempT.matrix().col(3)).norm(); qDebug() << "Norm:" << norm; if(norm < 500.0) // less than 50 cm { // update target ; } // emit event to DataLogger } void ControllerThread::updateTaskSpaceCommand(double x, double y, double z, double delPsi, bool isAbsolute) { // qDebug() << "New Task Target Received"; QMutexLocker locker(m_mutex); // Store the current tip pose as the new origin m_BBfixed_CTorig = m_BB_CT_curTipPos; // update target if(isAbsolute) { m_input_AbsXYZ(0) = x; m_input_AbsXYZ(1) = y; m_input_AbsXYZ(2) = z; m_input_RelXYZ(0) = 0.0; // TODO: this may be problematic, might want to chage the GUI to have both abs and rel editable at the same time m_input_RelXYZ(1) = 0.0; m_input_RelXYZ(2) = 0.0; // m_deltaXYZPsiToTarget(0) = x - m_BBfixed_CTorig(0,3); // m_deltaXYZPsiToTarget(1) = y - m_BBfixed_CTorig(1,3); // m_deltaXYZPsiToTarget(2) = z - m_BBfixed_CTorig(2,3); } else { m_input_RelXYZ(0) = x; m_input_RelXYZ(1) = y; m_input_RelXYZ(2) = z; m_input_AbsXYZ(0) = 0.0; // TODO: this may be problematic, might want to chage the GUI to have both abs and rel editable at the same time m_input_AbsXYZ(1) = 0.0; m_input_AbsXYZ(2) = 0.0; // m_deltaXYZPsiToTarget(0) = x; // m_deltaXYZPsiToTarget(1) = y; // m_deltaXYZPsiToTarget(2) = z; } m_input_delPsi = delPsi; // m_deltaXYZPsiToTarget(3) = delPsi; // check limits // emit event to DataLogger std::vector<double> xyzdxyzpsi = {m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2), m_input_RelXYZ(0), m_input_RelXYZ(1), m_input_RelXYZ(2), delPsi*deg180overPi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_USER_XYZDXYZPSI, xyzdxyzpsi); //std::cout << "New deltaXYZPsi : " << m_deltaXYZPsiToTarget << std::endl; std::cout << "New AbsXYZ RelXYZ DelPsi: " << m_input_AbsXYZ << m_input_RelXYZ << m_input_delPsi << std::endl; } void ControllerThread::resetBB() { QMutexLocker locker(m_mutex); // get latest BB reading, and put it into m_basTipPos_fixed ( = T_Box_SBm_fixed ) // m_basTipPos_fixed is the same as T_Box_SBm_fixed Transform_From_EMreading(m_latestReading[EM_SENSOR_BB], m_basTipPos_fixed); // update m_BB_Box m_BB_Box = m_BB_SBm * m_basTipPos_fixed.inverse(); // T_BB_Box = T_BB_SBm * T_SBm_Box // Save the fixed BB position, T_Box_BBfixed = T_Box_SBm_fixed * inv(T_BB_SBm) m_Box_BBfixed = m_basTipPos_fixed * m_BB_SBm.inverse(); std::vector<double> T_basTipPos_fixed(m_basTipPos_fixed.matrix().data(), m_basTipPos_fixed.matrix().data() + m_basTipPos_fixed.matrix().size()); emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESETBB_SUCCESS); if(T_basTipPos_fixed.size() == 16) { emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_RESETBB, T_basTipPos_fixed); } } void ControllerThread::startControlCycle() { QMutexLocker locker(m_mutex); if(m_isReady && !m_keepControlling) // ready to control { //Start the cycle m_keepControlling = true; // m_timer = new QTimer(this); // connect(m_timer, SIGNAL(timeout()), this, SLOT(controlCycle())); // m_timer->start(6); // every 6ms // if(m_timer->isActive()) // { // qDebug() << "Timer started."; // emit statusChanged(CONTROLLER_LOOP_STARTED); // emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_LOOP_STARTED); // } // else // { // qDebug() << "Timer is not active."; // emit statusChanged(CONTROLLER_LOOP_STOPPED); // emit logError(SRC_CONTROLLER, LOG_ERROR, QTime::currentTime(), CONTROLLER_INITIALIZE_FAILED, QString("Timer is not active.")); // } emit statusChanged(CONTROLLER_LOOP_STARTED); emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_LOOP_STARTED); } else { if(m_keepControlling) qDebug() << "Controller is already running."; else { qDebug() << "Controller is not ready."; emit statusChanged(CONTROLLER_INITIALIZE_FAILED); emit logError(SRC_CONTROLLER, LOG_ERROR, QTime::currentTime(), CONTROLLER_INITIALIZE_FAILED, QString("Controller is not ready.")); } } } void ControllerThread::stopControlCycle() { QMutexLocker locker(m_mutex); if(m_keepControlling) { m_keepControlling = false; // m_timer->stop(); // disconnect(m_timer, SIGNAL(timeout()), 0, 0); // delete m_timer; emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_LOOP_STOPPED); emit statusChanged(CONTROLLER_LOOP_STOPPED); qDebug() << "Timer stopped."; } else { qDebug() << "Timer already stopped."; } } void ControllerThread::setGains(GainsPYRT gains) { QMutexLocker locker(m_mutex); m_gains = gains; locker.unlock(); qDebug() << "Gains set:\nPitch:" << gains.kPitchMin << gains.kPitchMax << "\nYaw:" << gains.kYawMin << gains.kYawMax << "\nRoll:" << gains.kRollMin << gains.kRollMax << "\nTrans:" << gains.kTransMin << gains.kTransMax; } void ControllerThread::setLimits(ConvergenceLimits limits) { QMutexLocker locker(m_mutex); m_convLimits = limits; locker.unlock(); qDebug() << "Convergence limits set:\nPosition:" << limits.posMin << limits.posMax << "\nAngle:" << limits.angleMin << limits.angleMax; } void ControllerThread::setModeFlags(ModeFlags flags) { QMutexLocker locker(m_mutex); if(flags.inVivoMode) { if(!m_modeFlags.inVivoMode) // we're turning on in vivo mode { m_respModel.setInVivo(true); } } else { if(m_modeFlags.inVivoMode) // we're turning off in vivo mode { m_respModel.setInVivo(false); } } m_modeFlags = flags; unsigned int numcyc = m_numCycles; locker.unlock(); // qDebug() << "Mode flags set: " << flags.coordFrame // << flags.tethered << flags.instTrackState // << flags.instTrackMode << flags.EKFstate // << flags.inVivoMode; //emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESETBB_SUCCESS); std::vector<double> modes(6); modes.push_back(flags.coordFrame); modes.push_back(flags.tethered); modes.push_back(flags.instTrackState); modes.push_back(flags.instTrackMode); modes.push_back(flags.EKFstate); modes.push_back(flags.inVivoMode); emit logData(QTime::currentTime(), numcyc, CONTROLLER_MODES, modes); } void ControllerThread::setUSangle(double usAngle) { QMutexLocker locker(m_mutex); usAngle *= piOverDeg180; m_USangle = usAngle; m_BT_CT = m_BT_CT.Identity(); m_BT_CT(0,0) = cos(usAngle); m_BT_CT(1,1) = m_BT_CT(0,0); m_BT_CT(0,1) = -sin(usAngle); m_BT_CT(1,0) = -m_BT_CT(0,1); m_BT_CT(2,3) = 30.0; // 21.7; // m_BT_CT << cos(usAngle), -sin(usAngle), 0, 0, // sin(usAngle), cos(usAngle), 0, 0, // 0, 0, 1, 21.7; std::cout << "New m_BT_CT:\n" << m_BT_CT.matrix() << std::endl; //qInfo() << "US angle updated to" << m_USangle*deg180overPi << "degrees."; std::vector<double> usang = {m_USangle*deg180overPi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_USANGLE, usang); } void ControllerThread::initializeRespModel() { QMutexLocker locker(m_mutex); // TODO : start sending data to m_respModel m_respModelInitializing = true; emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_INIT_BEGIN); } void ControllerThread::re_initializeRespModel() { QMutexLocker locker(m_mutex); m_respModel.resetModel(); m_respModelInitializing = true; emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_INIT_BEGIN); } void ControllerThread::stopRespModel() { QMutexLocker locker(m_mutex); m_respModel.resetModel(); m_respModelInitializing = false; emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_STOPPED); } void ControllerThread::updateFutureSamples(int n) { if(n >= EDGE_EFFECT) m_respModel.updateNfutureSamples(n); else qDebug() << "updateFutureSamples: n < EDGE_EFFECT"; } void ControllerThread::startSweep(unsigned int nSteps_, double stepAngle_, double convLimit_, qint64 imgDuration_) { if(!m_sweep.getIsActive()) { m_sweep = Sweep(nSteps_, stepAngle_, convLimit_, imgDuration_); m_sweep.activate(); std::vector<double> sweepParams = {(double)nSteps_, stepAngle_*deg180overPi, convLimit_*deg180overPi, (double)imgDuration_}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_SWEEP_START, sweepParams); emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_SWEEP_STARTED); } else qDebug() << "Already sweeping!"; } void ControllerThread::abortSweep() { m_sweep.abort(); emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_SWEEP_ABORTED); } void ControllerThread::controlCycle() { //QMutexLocker locker(m_mutex); // already locked by calling function if(m_isReady && m_keepControlling) { switch(m_modeFlags.coordFrame) { case COORD_FRAME_WORLD: computeCoordFrameWorld(); break; case COORD_FRAME_MOBILE: computeCoordFrameMobile(); break; default: computeCoordFrameWorld(); qCritical() << "Unknown Coord Frame Mode! Defaulting to World"; break; } // handle sweep if(m_sweep.getIsActive()) { QString msg; std::vector<double> convd; std::vector<double> newDelPsi; int status = m_sweep.update( m_dXYZPsi(3) ); switch (status) { case SWEEP_INACTIVE: // shouldn't happen break; case SWEEP_WAIT_TO_CONVERGE: // ignore break; case SWEEP_CONVERGED: // emit signal to turn on frame transmission emit toggleFrameClientContinuousStreaming(true); convd = {(double)m_sweep.getRemainingSteps()}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_SWEEP_CONVERGED, convd); break; case SWEEP_CONVERGED_ACQUIRING: // ignore break; case SWEEP_NEXT: // done collecting // emit signal to turn off frame transmission emit toggleFrameClientContinuousStreaming(false); m_input_delPsi += m_sweep.getStepAngle(); newDelPsi = {m_input_delPsi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_NEXT_SWEEP, newDelPsi); msg = QString("%1 sweeps remaining.").arg(m_sweep.getRemainingSteps()); emit sendMsgToWidget(msg, 1); // update status text break; case SWEEP_DONE: emit toggleFrameClientContinuousStreaming(false); msg = QString("Sweep complete after %1 s.").arg(m_sweep.getOverallTimeElapsed()/1000); emit sendMsgToWidget(msg, 1); // update status text break; default: msg = QString("Sweep unknown state!"); emit sendMsgToWidget(msg, 1); // update status text break; } } // calculate gains updateGains(); // feed into control_icra2016 Eigen::Matrix<double, 4, 2> jointsCurrAndTarget; jointsCurrAndTarget = m_cathKin.control_icra2016(m_BB_CT_curTipPos, m_dXYZPsi, m_currGamma); //jointsCurrAndTarget = m_cathKin.control_icra2016(m_BBmobile_CT, m_dXYZPsi, m_currGamma); Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(m_BB_CT_curTipPos, m_currGamma); Eigen::Vector4d currTask = m_cathKin.configToTaskSpace(configCurr); // Use SVM #ifdef SVM_ON std::vector<double> inputs = {configCurr(0),configCurr(1),configCurr(2),configCurr(3), m_dXYZPsi(0),m_dXYZPsi(1),m_dXYZPsi(2),m_dXYZPsi(3)}; std::vector<double> predictions(4, 0); SVMregression(&SVMregressionStackDataGlobal, &inputs[0], &predictions[0]); #endif // get relative motor counts Eigen::Vector4d relQCs; // knob_tgt - knob_curr relQCs(0) = (jointsCurrAndTarget(0,1) - jointsCurrAndTarget(0,0)) * m_gains.kTrans * 0.001 * EPOS_TRANS_RAD2QC; relQCs(1) = (jointsCurrAndTarget(1,1) - jointsCurrAndTarget(1,0)) * m_gains.kPitch * EPOS_PITCH_RAD2QC; relQCs(2) = (jointsCurrAndTarget(2,1) - jointsCurrAndTarget(2,0)) * m_gains.kYaw * EPOS_YAW_RAD2QC; relQCs(3) = (jointsCurrAndTarget(3,1) - jointsCurrAndTarget(3,0)) * m_gains.kRoll * EPOS_ROLL_RAD2QC; // Jacobian based // Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(m_BB_CT_curTipPos, m_currGamma); // Eigen::Matrix<double, 6, 4> J = m_cathKin.JacobianNumeric(configCurr(0), configCurr(1), configCurr(2), configCurr(3)); // m_cathKin.dampedLeastSquaresStep(J, m_dXYZPsi); // // ***** // Eigen::Vector4d targetTask(m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2), m_input_delPsi); // Eigen::Vector4d targetConfig = m_cathKin.JacobianStep(currTask, targetTask, configCurr); // Eigen::Vector4d currJoint = m_cathKin.configToJointSpace(configCurr); // Eigen::Vector4d targetJoint = m_cathKin.configToJointSpace(targetConfig); std::vector<double> task = {currTask(0),currTask(1),currTask(2),currTask(3)}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_TASK, task); emit reportCurrentXYZPSI(XYZPSI(currTask(0),currTask(1),currTask(2),currTask(3))); // // ***** // FIXME: 1/20/2017: Trying to fix BBmobile discrepancy // // figure out distance from BBcurr to xy plane of BBfixed // double ratio = m_BBfixed_BBmobile(2,3)/m_BBfixed_BBmobile(2,2); // //Eigen::Vector4d offset_ = m_BBfixed_BBmobile.matrix().col(2)*ratio; // extend along z axis // Eigen::Transform<double,3,Eigen::Affine> T_BBtrans_CT(m_BBmobile_CT); // //T_BBtrans_CT.matrix().col(3) += offset_; // T_BBtrans_CT(2,3) += ratio; // Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(T_BBtrans_CT, m_currGamma); // Eigen::Vector4d currTask = m_cathKin.configToTaskSpace(configCurr); //// Eigen::Vector4d tmp = {currTask(0),currTask(1),currTask(2),1.0}; //// tmp = (m_BBfixed_BBmobile * tmp).eval(); //// currTask.segment<3>(0) = tmp.segment<3>(0); // currTask.segment<3>(0) = m_BB_CT_curTipPos.matrix().col(3).segment<3>(0); //// Eigen::Vector4d tmp(m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2),1.0); //// tmp = (m_BBfixed_BBmobile.inverse() * tmp).eval(); //// Eigen::Vector4d targetTask(tmp(0), tmp(1), tmp(2)+ratio, m_input_delPsi); // Eigen::Vector4d targetTask(m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2), m_input_delPsi); // Eigen::Vector4d targetConfig = m_cathKin.JacobianStep(currTask, targetTask, configCurr); // Eigen::Vector4d currJoint = m_cathKin.configToJointSpace(configCurr); // Eigen::Vector4d targetJoint = m_cathKin.configToJointSpace(targetConfig); //// Eigen::Vector4d deltaConfig = m_cathKin.JacobianStepSingle(currTask, targetTask, configCurr); //// Eigen::Vector4d currJoint = m_cathKin.configToJointSpace(Eigen::Vector4d::Zero()); //// Eigen::Vector4d targetJoint = m_cathKin.configToJointSpace(deltaConfig); // // get relative motor counts // Eigen::Vector4d relQCs; // knob_tgt - knob_curr // relQCs(0) = (targetJoint(0) - currJoint(0)) * m_gains.kTrans * 0.001 * EPOS_TRANS_RAD2QC; // relQCs(1) = (targetJoint(1) - currJoint(1)) * m_gains.kPitch * EPOS_PITCH_RAD2QC; // relQCs(2) = (targetJoint(2) - currJoint(2)) * m_gains.kYaw * EPOS_YAW_RAD2QC; // relQCs(3) = (targetJoint(3) - currJoint(3)) * m_gains.kRoll * EPOS_ROLL_RAD2QC; // check if QCs are finite if( !(isfinite(relQCs(0)) && isfinite(relQCs(1)) && isfinite(relQCs(2)) && isfinite(relQCs(3))) ) { relQCs = relQCs.Zero(); } std::vector<long> targetPos; targetPos.push_back((long)relQCs(0)); targetPos.push_back((long)relQCs(1)); targetPos.push_back((long)relQCs(2)); targetPos.push_back((long)relQCs(3)); // limit QCs to EPOS velocity limits // TODO : velocity is in RPMs, so we should convert this velocity to QCs/control cycle (= Ascension time = ~6ms) if(abs(targetPos[0]) > EPOS_VELOCITY[0]) targetPos[0] = boost::math::copysign(EPOS_VELOCITY[0], targetPos[0]); if(abs(targetPos[1]) > EPOS_VELOCITY[1]) targetPos[1] = boost::math::copysign(EPOS_VELOCITY[1], targetPos[1]); if(abs(targetPos[2]) > EPOS_VELOCITY[2]) targetPos[2] = boost::math::copysign(EPOS_VELOCITY[2], targetPos[2]); if(abs(targetPos[3]) > EPOS_VELOCITY[3]) targetPos[3] = boost::math::copysign(EPOS_VELOCITY[3], targetPos[3]); printf("QCs - T: %ld P: %ld Y: %ld R: %ld\n", targetPos[0], targetPos[1], targetPos[2], targetPos[3]); // TODO : check if the EPOS Servo Loop is active, if not, don't send commands emit setEPOSservoTargetPos(targetPos, false); //relative // emit logData(QTime::currentTime(), newData); std::cout << QTime::currentTime().toString().toStdString() << " Cycle:" << m_numCycles << std::endl; m_numCycles++; } else { m_currGamma = atan2(m_BBfixed_BBmobile(1,0), m_BBfixed_BBmobile(0,0)); Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(m_BB_CT_curTipPos, m_currGamma); Eigen::Vector4d currTask = m_cathKin.configToTaskSpace(configCurr); std::vector<double> task = {currTask(0),currTask(1),currTask(2),currTask(3)}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_TASK, task); } } void ControllerThread::computeCoordFrameWorld() { // Calculate the angle between the new x-axis and the original x-axis Eigen::Transform<double,3,Eigen::Affine> T_CTorig_CT = m_BBfixed_CTorig.inverse()*m_BB_CT_curTipPos; // This is the total amount of psy that has occurred at the tip since we started double total_psy = atan2(T_CTorig_CT(1,0), T_CTorig_CT(0,0)); // Existing roll in the catheter handle // Assuming the BB point has rotated about its Z axis, the amount of roll in // the handle is calculated as the angle of rotation about the base z-axis. // Here we calculate the angle between the new x-axis and the original // x-axis. m_currGamma = atan2(m_BBfixed_BBmobile(1,0), m_BBfixed_BBmobile(0,0)); //printf("Psy : %.3f Gamma : %.3f\n", total_psy * deg180overPi, m_currGamma * deg180overPi); std::vector<double> psyGamma = {total_psy*deg180overPi, m_currGamma*deg180overPi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_PSY_GAMMA, psyGamma); switch(m_modeFlags.instTrackState) { case INST_TRACK_OFF: // How much does the cath still need to move? // calculate delta x,y,z,psi // MATLAB code cycleinput5.m > lines 112-126 switch(m_modeFlags.tethered) { case MODE_TETHETERED: m_deltaXYZPsiToTarget(0) = m_input_AbsXYZ(0) - m_BBfixed_CTorig(0,3); m_deltaXYZPsiToTarget(1) = m_input_AbsXYZ(1) - m_BBfixed_CTorig(1,3); m_deltaXYZPsiToTarget(2) = m_input_AbsXYZ(2) - m_BBfixed_CTorig(2,3); break; case MODE_RELATIVE: m_deltaXYZPsiToTarget(0) = m_input_RelXYZ(0); m_deltaXYZPsiToTarget(1) = m_input_RelXYZ(1); m_deltaXYZPsiToTarget(2) = m_input_RelXYZ(2); break; default: m_deltaXYZPsiToTarget(0) = m_input_AbsXYZ(0) - m_BBfixed_CTorig(0,3); m_deltaXYZPsiToTarget(1) = m_input_AbsXYZ(1) - m_BBfixed_CTorig(1,3); m_deltaXYZPsiToTarget(2) = m_input_AbsXYZ(2) - m_BBfixed_CTorig(2,3); qCritical() << "Unknown Mode! Defaulting to tethered."; break; } m_deltaXYZPsiToTarget(3) = m_input_delPsi; m_dXYZPsi(0) = m_deltaXYZPsiToTarget(0) - (m_BB_CT_curTipPos(0,3) - m_BBfixed_CTorig(0,3)); m_dXYZPsi(1) = m_deltaXYZPsiToTarget(1) - (m_BB_CT_curTipPos(1,3) - m_BBfixed_CTorig(1,3)); m_dXYZPsi(2) = m_deltaXYZPsiToTarget(2) - (m_BB_CT_curTipPos(2,3) - m_BBfixed_CTorig(2,3)); m_dXYZPsi(3) = m_deltaXYZPsiToTarget(3) - total_psy; break; case INST_TRACK_ON: // World, IT switch(m_modeFlags.instTrackMode) { case INST_TRACK_POSITION: // World, IT, Position switch(m_modeFlags.EKFstate) { case EKF_OFF: // World, IT, Position m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = 0; break; case EKF_ON: // World, IT, Position, EKF // dx = T_BBfixed_Instr_EKF_x - T_BBfixed_CT(1,4); // dy = T_BBfixed_Instr_EKF_y - T_BBfixed_CT(2,4); // dz = T_BBfixed_Instr_EKF_z - T_BBfixed_CT(3,4); // dpsi = 0; // TODO : add EKF info here m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = 0; break; default: m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = 0; qCritical() << "Unknown EKFstate! Defaulting to EKF Off."; break; } break; // World, IT, Position ends case INST_TRACK_IMAGER: // World, IT, Imager { Eigen::Vector3d objectXYZ; switch(m_modeFlags.EKFstate) { case EKF_OFF: // World, IT, Imager objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3); break; case EKF_ON: // World, IT, Imager, EKF // object_loc = [T_BBfixed_Instr_EKF_x; // T_BBfixed_Instr_EKF_y; // T_BBfixed_Instr_EKF_z]; // TODO : add EKF info here objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3); break; default: objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3); qCritical() << "Unknown EKFstate! Defaulting to EKF Off."; break; } m_dXYZPsi(0) = m_input_AbsXYZ(0) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_input_AbsXYZ(1) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_input_AbsXYZ(2) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = computeSweep(m_BB_CT_curTipPos, objectXYZ); } break; // World, IT, Imager ends default: break; } break; // World, IT ends default: break; } //printf("dx : %.3f dy : %.3f dz : %.3f dpsi : %.3f\n", m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)* deg180overPi); std::vector<double> dxyzpsi = {m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)*deg180overPi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_DXYZPSI, dxyzpsi); } void ControllerThread::computeCoordFrameMobile() { //% Use models to reconstruct one 4x4 matrix at this time point // % Tip // T_BBfixed_CTtraj(1:3,1:3) = convert_eaa_3x3(reshape(BBfixed_CTtraj_model(4:7),1,4)); // T_BBfixed_CTtraj(1,4) = BBfixed_CTtraj_model(1); // T_BBfixed_CTtraj(2,4) = BBfixed_CTtraj_model(2); // T_BBfixed_CTtraj(3,4) = BBfixed_CTtraj_model(3); // T_BBfixed_CTtraj(4,1:4) = [0 0 0 1]; EigenVector7d CT_des = m_respModel.getT_BBfixed_CT_des(); EigenVector7d CT_future_des = m_respModel.getT_BBfixed_CTtraj_future_des(); EigenVector7d BB_des = m_respModel.getT_BBfixed_BB_des(); Eigen::AngleAxis<double> rotCTdes(CT_des(6), Eigen::Vector3d(CT_des(3),CT_des(4),CT_des(5))); Eigen::Translation3d transCTdes(CT_des(0),CT_des(1),CT_des(2)); EigenAffineTransform3d T_BBfixed_CT_des = transCTdes * rotCTdes; //printf("transCTdes: x %.3f y %.3f z %.3f\n",CT_des(0),CT_des(1),CT_des(2)); Eigen::AngleAxis<double> rotCTtraj(CT_future_des(6), Eigen::Vector3d(CT_future_des(3),CT_future_des(4),CT_future_des(5))); Eigen::Translation3d transCTtraj(CT_future_des(0),CT_future_des(1),CT_future_des(2)); EigenAffineTransform3d T_BBfixed_CTtraj_future_des = transCTtraj * rotCTtraj; Eigen::AngleAxis<double> rotBBdes(BB_des(6), Eigen::Vector3d(BB_des(3),BB_des(4),BB_des(5))); Eigen::Translation3d transBBdes(BB_des(0),BB_des(1),BB_des(2)); EigenAffineTransform3d T_BBfixed_BB_des = transBBdes * rotBBdes; //% Rotation about the z-axis of the catheter tip. // % Here we calculate the angle between the current x-axis and the // % pure-breathing x-axis. // T_CTtraj_CT=inv(T_BBfixed_CTtraj)*T_BBfixed_CT; EigenAffineTransform3d T_CTtraj_CT = T_BBfixed_CT_des.inverse() * m_BB_CT_curTipPos; // % This is the total amount of psy that has occurred at the tip compared // % with pure breathing // total_psy=atan2(T_CTtraj_CT(2,1),T_CTtraj_CT(1,1)); double total_psy = atan2(T_CTtraj_CT(1,0), T_CTtraj_CT(0,0)); //% Existing roll in the catheter handle, from Base_Roll which was a separate // % function but is now incorporated into here // T_BBtraj_BBmob = inv(T_BBfixed_BBtraj) * T_BBfixed_BBmob; // % Assuming the BB point has rotated about its Z axis, the amount of roll in // % the handle is calculated as the angle of rotation about the base z-axis. // % Here we calculate the angle between the new x-axis and the trajectory // % x-axis. // gamma=atan2(T_BBtraj_BBmob(2,1),T_BBtraj_BBmob(1,1)); EigenAffineTransform3d T_BBtraj_BBmob = T_BBfixed_BB_des.inverse() * m_BBfixed_BBmobile; m_currGamma = atan2(T_BBtraj_BBmob(1,0), T_BBtraj_BBmob(0,0)); //printf("Psy : %.3f Gamma : %.3f\n", total_psy * deg180overPi, m_currGamma * deg180overPi); std::vector<double> psyGamma = {total_psy*deg180overPi, m_currGamma*deg180overPi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_PSY_GAMMA, psyGamma); //% Get BT w.r.t. mobile BB, rather than fixed BB // T_BBmob_BT = inv(T_BBfixed_BBmob)*T_BBfixed_CT*inv(T_BT_CT); EigenAffineTransform3d T_BBmob_BT = m_BBfixed_BBmobile.inverse() * m_BBfixed_CTorig * m_BT_CT.inverse(); //% Initialize even if EKF is off // T_BBfixed_CT_future = zeros(1,16); EigenAffineTransform3d T_BBfixed_CT_future = EigenAffineTransform3d::Identity(); switch(m_modeFlags.instTrackState) { case INST_TRACK_OFF: switch(m_modeFlags.tethered) { case MODE_TETHETERED: // TODO : % **** this is not implemented correctly right now // % If the cath is tethered to a point... fix this later // % Right now I'm just copying the relative case over here in case I // % hit the wrong button by accident m_dXYZPsi(0) = m_input_AbsXYZ(0) + T_BBfixed_CT_des(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_input_AbsXYZ(1) + T_BBfixed_CT_des(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_input_AbsXYZ(2) + T_BBfixed_CT_des(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = m_input_delPsi - total_psy; break; case MODE_RELATIVE: //% If the cath is being told to do relative adjustments then that's // % like adding the relative adjustments to the Traj point. Then I // % just take the difference between where I am now and the relative // % change from the Traj point. // dx = inputbox_delt_x + T_BBfixed_CTtraj(1,4) - T_BBfixed_CT(1,4); // dy = inputbox_delt_y + T_BBfixed_CTtraj(2,4) - T_BBfixed_CT(2,4); // dz = inputbox_delt_z + T_BBfixed_CTtraj(3,4) - T_BBfixed_CT(3,4); // dpsi = inputbox_delt_psi - total_psy; m_dXYZPsi(0) = m_input_AbsXYZ(0) + T_BBfixed_CT_des(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_input_AbsXYZ(1) + T_BBfixed_CT_des(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_input_AbsXYZ(2) + T_BBfixed_CT_des(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = m_input_delPsi - total_psy; break; default: qCritical() << "Unknown Mode! MOBILE - INST_TRACK_OFF."; break; } break; case INST_TRACK_ON: // Mobile, IT then switch(m_modeFlags.instTrackMode) { case INST_TRACK_POSITION: // Mobile, IT, Position switch(m_modeFlags.EKFstate) { case EKF_OFF: // Mobile, IT, Position m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = 0.0; break; case EKF_ON: // Mobile, IT, Position, EKF T_BBfixed_CT_future = T_BBfixed_CTtraj_future_des * T_CTtraj_CT; // dx = T_BBfixed_Instr_EKF_x - T_BBfixed_CT_future(1,4); // dy = T_BBfixed_Instr_EKF_y - T_BBfixed_CT_future(2,4); // dz = T_BBfixed_Instr_EKF_z - T_BBfixed_CT_future(3,4); // dpsi = 0; // TODO : add EKF info here // this is doing inst track with predicted CT m_dXYZPsi(0) = m_BB_targetPos(0,3) - T_BBfixed_CT_future(0,3); m_dXYZPsi(1) = m_BB_targetPos(1,3) - T_BBfixed_CT_future(1,3); m_dXYZPsi(2) = m_BB_targetPos(2,3) - T_BBfixed_CT_future(2,3); m_dXYZPsi(3) = 0; break; default: m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3); m_dXYZPsi(3) = 0.0; qCritical() << "Unknown EKFstate! Mobile, IT, Position."; break; } break; // Mobile, IT, Position ends case INST_TRACK_IMAGER: // Mobile, IT, Imager { Eigen::Vector3d objectXYZ; switch(m_modeFlags.EKFstate) { case EKF_OFF: // Mobile, IT, Imager objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3); m_dXYZPsi(3) = computeSweep(m_BB_CT_curTipPos, objectXYZ); break; case EKF_ON: // Mobile, IT, Imager, EKF // % Take future CT traj point and transform by the same // % matrix that transforms from current CT traj to current // % CT. This is the best estimate that we can get of where // % the CT will be in the future. T_BBfixed_CT_future = T_BBfixed_CTtraj_future_des * T_CTtraj_CT; // object_loc = [T_BBfixed_Instr_EKF_x; // T_BBfixed_Instr_EKF_y; // T_BBfixed_Instr_EKF_z]; // TODO: add Kalman here objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3); m_dXYZPsi(3) = computeSweep(T_BBfixed_CT_future, objectXYZ); break; default: objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3); m_dXYZPsi(3) = computeSweep(m_BB_CT_curTipPos, objectXYZ); qCritical() << "Unknown EKFstate! Defaulting to EKF Off."; break; } m_dXYZPsi(0) = T_BBfixed_CT_des(0,3) - m_BB_CT_curTipPos(0,3); m_dXYZPsi(1) = T_BBfixed_CT_des(1,3) - m_BB_CT_curTipPos(1,3); m_dXYZPsi(2) = T_BBfixed_CT_des(2,3) - m_BB_CT_curTipPos(2,3); } break; // Mobile, IT, Imager ends default: qCritical() << "Unknown! Mobile, IT."; break; } break; default: break; } //printf("m_dXYZPsi - x %.3f y %.3f z %.3f psi %.3f\n", m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)*deg180overPi); std::vector<double> dxyzpsi = {m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)*deg180overPi}; emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_DXYZPSI, dxyzpsi); } double ControllerThread::computeSweep(const Eigen::Transform<double,3,Eigen::Affine> &currT, const Eigen::Vector3d &objXYZ) { Eigen::Vector3d currLoc = currT.matrix().col(3).segment(0,3); // current location catheter xyz Eigen::Vector3d y_1 = currT.matrix().col(1).segment(0,3); // normal to the catheter's XZ plane // distance from the current point to the obj double d_obj_cur = (objXYZ - currLoc).norm(); // distance from object to the catheter's XZ plane double d_obj_plane = y_1.dot(objXYZ - currLoc) / y_1.norm(); double ratio = d_obj_plane / d_obj_cur; if(abs(ratio) > 1.0) ratio = ratio / abs(ratio); // otherwise, asin will be invalid double psy = 0.0; if(d_obj_cur > 0.0001) psy = asin(ratio); // angle between object and the catheter's XZ plane return psy; } void ControllerThread::updateGains() { // Calculate distance from target double distError = m_dXYZPsi.segment(0,3).norm(); double angleError = m_dXYZPsi(3); // Update gains double kPitch = 0.0, kYaw = 0.0, kRoll = 0.0, kTrans = 0.0; if(distError < m_convLimits.posMin) { kPitch = m_gains.kPitchMin; kYaw = m_gains.kYawMin; kTrans = m_gains.kTransMin; } else if(distError > m_convLimits.posMax) { kPitch = m_gains.kPitchMax; kYaw = m_gains.kYawMax; kTrans = m_gains.kTransMax; } else { double tPos = (distError - m_convLimits.posMin)/(m_convLimits.posMax - m_convLimits.posMin); kPitch = lerp(m_gains.kPitchMin, m_gains.kPitchMax, tPos); kYaw = lerp(m_gains.kYawMin, m_gains.kYawMax, tPos); kTrans = lerp(m_gains.kTransMin, m_gains.kTransMax, tPos); } if(angleError < m_convLimits.angleMin) { kRoll = m_gains.kRollMin; } else if(angleError > m_convLimits.angleMax) { kRoll = m_gains.kRollMax; } else { double tAng = (angleError - m_convLimits.angleMin)/(m_convLimits.angleMax - m_convLimits.angleMin); kRoll = lerp(m_gains.kRollMin, m_gains.kRollMax, tAng); } m_gains.kRoll = kRoll; m_gains.kPitch = kPitch; m_gains.kYaw = kYaw; m_gains.kTrans = kTrans; std::cout << "Gains - kR: " << kRoll << " kP: " << kPitch << " kY: " << kYaw << " kT: " << kTrans << std::endl; } // ---------------- // ACCESSORS // ---------------- // ---------------- // HELPER FUNCTIONS // ---------------- static void Transform_From_EMreading(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &input, Eigen::Transform<double,3,Eigen::Affine> &output) { // QElapsedTimer elTimer; // elTimer.start(); Eigen::Translation3d trans(input.x, input.y, input.z); Eigen::Matrix3d rot; rot << input.s[0][0], input.s[0][1], input.s[0][2], input.s[1][0], input.s[1][1], input.s[1][2], input.s[2][0], input.s[2][1], input.s[2][2]; // Eigen::Matrix3d rot; // rot << input.s[0][0], input.s[1][0], input.s[2][0], // input.s[0][1], input.s[1][1], input.s[2][1], // input.s[0][2], input.s[1][2], input.s[2][2]; output = trans * rot; // std::cout << output.matrix() << std::endl; // qint64 elNsec = elTimer.nsecsElapsed(); // qDebug() << "Nsec elapsed:" << elNsec; } Eigen::Transform<double,3,Eigen::Affine> ControllerThread::readTransformFromTxtFile(const QString &path) { Eigen::Transform<double,3,Eigen::Affine> tform; QFile file(path); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "File doesn't exist:" << path << " !!!"; return tform; } QTextStream in(&file); for(size_t i = 0; i < 3; i++) { for(size_t j = 0; j < 4; j++) { if(!in.atEnd()) { in >> tform(i,j); } else { qDebug() << "File ended prematurely at element (" << i << "," << j << "):" << path << " !!!"; return tform; } } } // convert from meters to mm tform.translation() *= 1000.0; std::cout << "Loaded:" << path.toStdString().c_str() << std::endl; std::cout << tform.matrix() << std::endl; return tform; } void ControllerThread::loadConstants() { m_BB_Box = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_BB_Box.txt")); m_STm_BT = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_STm_BT.txt")); m_BT_CT = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_BT_CT.txt")); m_BB_SBm = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_BB_SBm.txt")); m_ISm_INSTR = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_ISm_INSTR.txt")); } inline const QString getCurrTimeStr() { return QTime::currentTime().toString("HH.mm.ss.zzz"); } inline const QString getCurrDateTimeStr() { return QDateTime::currentDateTime().toString("dd/MM/yyyy - hh:mm:ss.zzz"); }
52,543
C++
38.358801
149
0.586377
adegirmenci/HBL-ICEbot/ControllerWidget/sweep.h
#ifndef SWEEP_H #define SWEEP_H #include <QObject> #include <QElapsedTimer> #include "kinematics_4dof.h" #include "../icebot_definitions.h" class Sweep { public: explicit Sweep(unsigned int nSteps_ = 30, double stepAngle_ = 2.0*piOverDeg180, double convLimit_ = 1.0*piOverDeg180, qint64 imgDuration_ = 3000); void activate(); void abort() {reset();} void reset(); int update(const double currPsy); double getStepAngle() { return stepAngle; } unsigned int getRemainingSteps() { return remSteps; } bool getIsConverged() { return isConverged; } bool getIsActive() { return isActive; } unsigned int getNumControlCycles() { return nControlCycles; } qint64 getOverallTimeElapsed() { return overallTimer.elapsed(); } private: bool isActive; // are we currently sweeping? unsigned int nControlCycles; // how many control cycles have elapsed since the beginning of this sweep unsigned int nSteps; // number of desired steps (angle increments) unsigned int remSteps; // remaining number of steps (angle increments) double stepAngle; // angle increment between sweps double convergenceLimit; // convergence criterion (CURR_PSY angle from 0) bool isConverged; // did we converge? qint64 imagingDuration; // how many ms to image for at current angle once converged QElapsedTimer timer; // keep track of ms spent at current angle after convergence QElapsedTimer overallTimer; }; #endif // SWEEP_H
1,539
C
33.999999
106
0.692008
adegirmenci/HBL-ICEbot/ControllerWidget/controllerthread.h
#ifndef CONTROLLERTHREAD_H #define CONTROLLERTHREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> #include <QString> #include <QTime> #include <QTimer> #include <QElapsedTimer> #include <QFile> #include <QDebug> #include <QSharedPointer> #include <QAtomicInt> #include <atomic> #include <vector> #include <memory> // included in kinematics_4dof.h //#include <Eigen/Dense> //#include <Eigen/SVD> //#include <Eigen/StdVector> //#include <Eigen/Geometry> #include <iostream> //#include <fstream> //#include <iterator> #include "kinematics_4dof.h" #include "filtfilt.h" #include "cyclicmodel.h" #include "../icebot_definitions.h" #include "../AscensionWidget/3DGAPI/ATC3DG.h" #include "gainswidget.h" #include "sweep.h" // MATLAB SVM Include Files //#define SVM_ON #ifdef SVM_ON #include <cmath> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "SVMregression_types.h" #include "SVMregression.h" #include "SVMregression_initialize.h" #include "SVMregression_terminate.h" static SVMregressionStackData SVMregressionStackDataGlobal; #endif struct ModeFlags { int coordFrame; int tethered; int instTrackState; int instTrackMode; int EKFstate; int inVivoMode; explicit ModeFlags(int cF = COORD_FRAME_WORLD, int tth = MODE_TETHETERED, int iTS = INST_TRACK_OFF, int iTM = INST_TRACK_POSITION, int EKFs = EKF_OFF, int iVM = IN_VIVO_OFF) : coordFrame(cF), tethered(tth), instTrackState(iTS), instTrackMode(iTM), EKFstate(EKFs), inVivoMode(iVM) { } }; struct XYZPSI { double x; double y; double z; double psi; explicit XYZPSI(double x_ = 0.0, double y_ = 0.0, double z_ = 0.0, double psi_ = 0.0): x(x_), y(y_), z(z_), psi(psi_) { } }; Q_DECLARE_METATYPE(ModeFlags) Q_DECLARE_METATYPE(EigenVectorFiltered) Q_DECLARE_METATYPE(XYZPSI) class ControllerThread : public QObject { Q_OBJECT public: explicit ControllerThread(QObject *parent = 0); ~ControllerThread(); signals: void statusChanged(int event); void logData(QTime timeStamp, int loopIdx, int dataType, std::vector<double> data); void logEvent(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID); // FRMGRAB_EVENT_IDS void logEventWithMessage(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID, // FRMGRAB_EVENT_IDS QString &message); void sendMsgToWidget(QString msg, int destination); void logError(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int errCode, // FRMGRAB_ERROR_CODES QString message); void finished(); // emit upon termination void setEPOSservoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel); void send_CT_toFrameClient(std::vector<double> T_BB_CT_curTipPos, double time); void sendDataToRespModelWidget(int numSamples, bool isTrained, bool inVivoMode, double omega0); void reportCurrentXYZPSI(XYZPSI currXYZPSI); void toggleFrameClientContinuousStreaming(bool turnOn); public slots: void setEpoch(const QDateTime &epoch); void printThreadID(); void receiveEMdata(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data); void receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings); void updateJointSpaceCommand(double pitch, double yaw, double roll, double trans); void updateConfigSpaceCommand(double alpha, double theta, double gamma, double d); void updateTaskSpaceCommand(double x, double y, double z, double delPsi, bool isAbsolute); void resetBB(); void startControlCycle(); // start timer void stopControlCycle(); // stop timer const bool isControlling() { return m_keepControlling; } void setGains(GainsPYRT gains); void setLimits(ConvergenceLimits limits); void setModeFlags(ModeFlags flags); void setUSangle(double usAngle); void initializeRespModel(); void re_initializeRespModel(); void stopRespModel(); void updateFutureSamples(int n); void startSweep(unsigned int nSteps_, double stepAngle_, double convLimit_, qint64 imgDuration_); void abortSweep(); private slots: void controlCycle(); // on a timer private: // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Timer for calling controlLoop every xxx msecs QTimer *m_timer; // Epoch for time stamps // During InitializeController(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if Controller is ready // True if InitializeController was successful bool m_isReady; // Flag to tell that we are still controlling bool m_keepControlling; // Flag to abort actions bool m_abort; const int m_prec = 4; // precision for print operations // latest reading std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> m_prevReading; std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> m_latestReading; // transforms Eigen::Transform<double,3,Eigen::Affine> m_BB_Box, m_Box_SBm, m_STm_BT, m_BT_CT, m_BB_CT_curTipPos, m_BBfixed_CTorig, m_BB_SBm, m_BBfixed_BBmobile, m_BBmobile_BT, m_BBmobile_CT, m_curTipPos, m_ISm_INSTR, m_basTipPos_fixed, m_basTipPos_mobile, m_Box_BBfixed, m_Box_BBmobile, m_targetPos, m_BB_targetPos, m_currChest; // delta x,y,z,psi to target Eigen::Vector3d m_input_AbsXYZ, m_input_RelXYZ; double m_input_delPsi; Eigen::Vector4d m_dXYZPsi, m_deltaXYZPsiToTarget; double m_currGamma; public: // Respiration Model -- this is public for now, change later CyclicModel m_respModel; private: bool m_respModelInitializing; // gains GainsPYRT m_gains; // convergence limits ConvergenceLimits m_convLimits; // Mode Flags ModeFlags m_modeFlags; // US angle double m_USangle; // keep track of number of control cycles // an atomic variable alleviates the need to use mutexes during mutation std::atomic<unsigned int> m_numCycles; // Kinematics oject Kinematics_4DOF m_cathKin; // Sweep object Sweep m_sweep; // --- Private methods --- void computeCoordFrameWorld(); // Coord Frame: world void computeCoordFrameMobile(); // Coord Frame: mobile double computeSweep(const Eigen::Transform<double,3,Eigen::Affine> &currT, const Eigen::Vector3d &objXYZ); void updateGains(); // Update gains Eigen::Transform<double,3,Eigen::Affine> readTransformFromTxtFile(const QString &path); void loadConstants(); public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; // ---------------- // HELPER FUNCTIONS // ---------------- inline const QString getCurrTimeStr(); inline const QString getCurrDateTimeStr(); static void Transform_From_EMreading(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &input, Eigen::Transform<double,3,Eigen::Affine> &output); #endif // CONTROLLERTHREAD_H
8,500
C
29.912727
132
0.594471
adegirmenci/HBL-ICEbot/ControllerWidget/cyclicmodel.cpp
#include "cyclicmodel.h" CyclicModel::CyclicModel(QObject *parent) : QObject(parent) { resetModel(); std::cout << "--- Initialized CyclicModel. ---" << std::endl; } CyclicModel::~CyclicModel() { } void CyclicModel::resetModel() { // ------------------ EMPTY BUFFERS ------------------ // // UNFILTERED DATA m_BBfixed_CT .clear(); m_BBfixed_Instr.clear(); m_BBfixed_BB .clear(); m_Bird4 .clear(); m_Bird4_new.clear(); // TIME DATA m_timeData_init.clear(); m_timeData_new .clear(); // ------------------ INIT BUFFERS ------------------ // // UNFILTERED DATA m_BBfixed_CT .reserve(N_SAMPLES); // this stores all of the incoming CT points m_BBfixed_Instr.reserve(N_SAMPLES); // this stores all of the incoming instr_x points m_BBfixed_BB .reserve(N_SAMPLES); // this stores all of the incoming BB points m_Bird4 .reserve(N_SAMPLES); // this remains constant after initialization m_Bird4_new.resize(N_SAMPLES, 0.0); // most recent chest tracker data // FILTERED DATA m_BBfixed_CT_filtered = EigenMatrixFiltered::Zero(N_FILTERED,7); // this remains constant after initialization m_BBfixed_BB_filtered = EigenMatrixFiltered::Zero(N_FILTERED,7); // this remains constant after initialization m_Bird4_filtered = EigenVectorFiltered::Zero(N_FILTERED); // this remains constant after initialization m_Bird4_filtered_new = EigenVectorFiltered::Zero(N_FILTERED); // most recent filtered chest tracker data m_breathSignalFromModel = EigenVectorFiltered::Zero(N_FILTERED); // ***CURRENT*** RECTANGULAR COMPONENTS m_BBfixed_CT_rectangular = EigenMatrixRectangular::Zero(N_RECT,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle m_BBfixed_BB_rectangular = EigenMatrixRectangular::Zero(N_RECT,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle m_Bird4_rectangular = EigenVectorRectangular::Zero(N_RECT); // 1 component : x (benchtop) or -z (in vivo) // ***CURRENT*** POLAR COMPONENTS m_BBfixed_CT_polar = EigenMatrixPolar::Zero(N_POLAR,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle m_BBfixed_BB_polar = EigenMatrixPolar::Zero(N_POLAR,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle m_Bird4_polar = EigenVectorPolar::Zero(N_POLAR); // 1 component : x (benchtop) or -z (in vivo) // TIME DATA m_timeData_init.reserve(N_SAMPLES); // stores the time vector for the model initialization observations m_timeData_new .resize(N_SAMPLES, 0.0); // stores time for the most recent observations m_nFutureSamples = 2*EDGE_EFFECT; m_omega0 = 2.*pi/BREATH_RATE; // frequency [rad/sec] m_omega0_init = 2.*pi/BREATH_RATE; m_periods.clear(); // averaging filter for period m_numSamples = 0; // number of observations added IN TOTAL m_isTrained = false; // is the model trained m_lastTrainingTimestamp = 0; // when last training was performed m_isInVivo = true; // are we in IN VIVO mode } void CyclicModel::addTrainingObservation(const EigenAffineTransform3d &T_BB_CT_curTipPos, const EigenAffineTransform3d &T_BB_targetPos, const EigenAffineTransform3d &T_Box_BBmobile, const EigenAffineTransform3d &T_BB_Box, const EigenAffineTransform3d &T_Bird4, const double sampleTime) { // em_tip = m_BB_CT_curTipPos // m_BB_CT_curTipPos is the current CT point w.r.t. BBfixed // em_instr = m_BB_targetPos // m_BB_targetPos is the current INST point w.r.t. BBfixed // local_Box_BBmobile = m_Box_BBmobile // m_Box_BBmobile is the current BB point w.r.t. Box // local_BB_Box = m_BB_Box // m_BB_Box is the current Box point w.r.t. BBfixed // local_Bird4 = m_Bird4 // 4th EM tracker // local_BB_Box * local_Box_BBmobile = em_base; // T_BB_Box * T_Box_BBmobile = T_BBfixed_BBmobile // BBfixed_CT.insert(BBfixed_CT.end(), em_tip, em_tip+16); // BBfixed_Instr.insert(BBfixed_Instr.end(), em_instr, em_instr+16); // BBfixed_BB.insert(BBfixed_BB.end(), em_base, em_base+16); // Bird4.insert(Bird4.end(), local_Bird4, local_Bird4+16); if( m_numSamples < N_SAMPLES) { EigenAffineTransform3d T_BB_BBm = T_BB_Box * T_Box_BBmobile; // axis angle Eigen::AngleAxisd tempEA_CT (T_BB_CT_curTipPos.rotation()), tempEA_Inst(T_BB_targetPos.rotation()), tempEA_BB (T_BB_BBm.rotation()); //, tempEA_Bird(T_Bird4.rotation()); // Create 7d Eigen::Vectors to hold the x,y,z,xaxis,yaxis,zaxis,angle EigenVector7d tempCT, tempInst, tempBB; tempCT << T_BB_CT_curTipPos(0,3), T_BB_CT_curTipPos(1,3), T_BB_CT_curTipPos(2,3), tempEA_CT.axis()(0), tempEA_CT.axis()(1), tempEA_CT.axis()(2), tempEA_CT.angle(); tempInst << T_BB_targetPos(0,3), T_BB_targetPos(1,3), T_BB_targetPos(2,3), tempEA_Inst.axis()(0), tempEA_Inst.axis()(1), tempEA_Inst.axis()(2), tempEA_Inst.angle(); tempBB << T_BB_BBm(0,3), T_BB_BBm(1,3), T_BB_BBm(2,3), tempEA_BB.axis()(0), tempEA_BB.axis()(1), tempEA_BB.axis()(2), tempEA_BB.angle(); double tempBird4; if(m_isInVivo) tempBird4 = -T_Bird4(2,3); // -z axis of the EM tracker (in vivo) else tempBird4 = T_Bird4(0,3); // x axis of the EM tracker (benchtop) // push newest readings m_BBfixed_CT.push_back(tempCT); m_BBfixed_Instr.push_back(tempInst); m_BBfixed_BB.push_back(tempBB); m_Bird4.push_back(tempBird4); m_timeData_init.push_back(sampleTime); // send to plotter switch (m_plotFocus) { case RESP_MODEL_PLOT_BIRD4: emit sendToPlotBird4(0, sampleTime, tempBird4); break; case RESP_MODEL_PLOT_CT: emit sendToPlotBird4(0, sampleTime, tempCT.segment(0,3).norm()); break; default: emit sendToPlotBird4(0, sampleTime, tempBird4); break; } m_numSamples++; printf("x: %.3f\n",m_BBfixed_CT.back()(0)); } else { printf("Already have enough training points!\n"); printf("I'll forgive you and fix this.\n"); printf("Train model and call addObservation.\n"); trainModel(); addObservation(T_Bird4, sampleTime); } } void CyclicModel::addObservation(const EigenAffineTransform3d &T_Bird4, const double sampleTime) { printf("Entering addObservation\n"); if(m_isTrained) { QElapsedTimer elTimer; elTimer.start(); // erase oldest observation m_Bird4_new .erase(m_Bird4_new.begin()); m_timeData_new.erase(m_timeData_new.begin()); double tempBird4; if(m_isInVivo) tempBird4 = -T_Bird4(2,3); // -z axis of the EM tracker (in vivo) else tempBird4 = T_Bird4(0,3); // x axis of the EM tracker (benchtop) // add new observation m_Bird4_new.push_back(tempBird4); m_timeData_new.push_back(sampleTime); // send to plotter switch (m_plotFocus) { case RESP_MODEL_PLOT_BIRD4: emit sendToPlotBird4(0, sampleTime, tempBird4); break; case RESP_MODEL_PLOT_CT: emit sendToPlotBird4(0, sampleTime, tempBird4 - 130.); break; default: emit sendToPlotBird4(0, sampleTime, tempBird4); break; } m_numSamples++; qint64 elNsec = elTimer.nsecsElapsed(); printf("Insert new obs: %d ns\n", elNsec); // up to here take about 3 microseconds // Retrain model std::cout << "Retrain model..."; retrainModel(); std::cout << "...done." << std::endl; // send to plotter switch (m_plotFocus) { case RESP_MODEL_PLOT_BIRD4: emit sendToPlotBird4(1, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_Bird4_filtered_new.tail(1)[0]); emit sendToPlotBird4(2, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_breathSignalFromModel.tail(1)[0]); break; case RESP_MODEL_PLOT_CT: //emit sendToPlotBird4(1, m_timeData_new.back(), m_BBfixed_CTtraj_future_des(1)); //emit sendToPlotBird4(2, m_timeData_new.back(), m_BBfixed_CT_des(1)); emit sendToPlotBird4(1, m_timeData_new.back(), m_BBfixed_CTtraj_future_des.segment(0, 3).norm()); emit sendToPlotBird4(2, m_timeData_new.back(), m_BBfixed_CT_des.segment(0, 3).norm()); break; default: emit sendToPlotBird4(1, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_Bird4_filtered_new.tail(1)[0]); emit sendToPlotBird4(2, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_breathSignalFromModel.tail(1)[0]); break; } } else { std::cout << "Not trained yet!\n" << std::endl; std::cout << "FATAL ERROR!!!\n" << std::endl; // becuase we lost this data } } void CyclicModel::trainModel() { if(m_numSamples < N_SAMPLES) // not enough samples { std::cout << "m_numSamples is less than N_SAMPLES!" << std::endl; m_isTrained = false; } else if(m_isTrained) // already trained { std::cout << "Already trained!" << std::endl; } else // train { // size_t m = N_HARMONICS; // m = number of sinusoid components // double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point size_t N_initpts = m_BBfixed_CT.size(); // number of initialization points std::cout << "Training model.\n" << std::endl; if(N_initpts <= 2*EDGE_EFFECT) { std::cout << "Error: N_initpts < 2*edge_effect.\n" << std::endl; return; } if(N_initpts != N_SAMPLES) { std::cout << "Error: N_initpts != N_SAMPLES\n" << std::endl; } // calculate things from inputs // size_t num_states = N_STATES; // size_t N_filtered = N_initpts - 2*EDGE_EFFECT; // low pass filter the data filterTrainingData(); std::cout << "Filtered training data.\n" << std::endl; // // save filtered data // QString outputFile1("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\LoggedData\\m_BBfixed_CT_filtered.txt"); // QString outputFile2("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\LoggedData\\m_BBfixed_BB_filtered.txt"); // QString outputFile3("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\LoggedData\\m_Bird4_filtered.txt"); // save4x4FilteredData(outputFile1, m_BBfixed_CT_filtered); // save4x4FilteredData(outputFile2, m_BBfixed_BB_filtered); // saveFilteredData(outputFile3, m_Bird4_filtered); // Use peak detection to look at the filtered data and find the period updatePeriod( peakDetector(true) ); // run for init std::cout << "Updated period.\n" << std::endl; // Get Fourier decomposition // TODO : should compare if the column by column computation is slower than the whole matrix approach // Eigen::VectorXd z_init_x = m_BBfixed_CT_filtered.col(0); // Eigen::VectorXd z_init_y = m_BBfixed_CT_filtered.col(1); // Eigen::VectorXd z_init_z = m_BBfixed_CT_filtered.col(2); // Eigen::VectorXd z_init_xaxis = m_BBfixed_CT_filtered.col(3); // Eigen::VectorXd z_init_yaxis = m_BBfixed_CT_filtered.col(4); // Eigen::VectorXd z_init_zaxis = m_BBfixed_CT_filtered.col(5); // Eigen::VectorXd z_init_angle = m_BBfixed_CT_filtered.col(6); // cycle_recalculate(m_BBfixed_CT_filtered, m_BBfixed_CT_rectangular, m_BBfixed_CT_polar); // cycle_recalculate(m_BBfixed_BB_filtered, m_BBfixed_BB_rectangular, m_BBfixed_BB_polar); // cycle_recalculate(m_Bird4_filtered, m_Bird4_rectangular, m_Bird4_polar); // TODO : is this faster? // m_BBfixed_CT_polarRect = cycle_recalculate_concurrentM(m_BBfixed_CT_filtered, m_omega0); // m_BBfixed_BB_polarRect = cycle_recalculate_concurrentM(m_BBfixed_BB_filtered, m_omega0); // m_Bird4_polarRect = cycle_recalculate_concurrentV(m_Bird4_filtered, m_omega0); mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0, m_timeData_init); mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0, m_timeData_init); mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered, m_omega0, m_timeData_init); // 3 should finish first, process that while the others are running mConcurrent3.waitForFinished(); m_Bird4_polarRect = mConcurrent3.result(); m_Bird4_polar = m_Bird4_polarRect.segment(0, N_POLAR); m_Bird4_rectangular = m_Bird4_polarRect.segment(N_POLAR, N_RECT); std::cout << "m_Bird4_polarRect\n" << m_Bird4_polarRect << std::endl; std::cout << "m_Bird4_polar\n" << m_Bird4_polar << std::endl; std::cout << "m_Bird4_rectangular\n" << m_Bird4_rectangular << std::endl; // 1 should be done sooner since it was launched first mConcurrent1.waitForFinished(); m_BBfixed_CT_polarRect = mConcurrent1.result(); m_BBfixed_CT_polar = m_BBfixed_CT_polarRect.block(0,0, N_POLAR, 7); m_BBfixed_CT_rectangular = m_BBfixed_CT_polarRect.block(N_POLAR,0, N_RECT, 7); // 2 should be done mConcurrent2.waitForFinished(); m_BBfixed_BB_polarRect = mConcurrent2.result(); m_BBfixed_BB_polar = m_BBfixed_BB_polarRect.block(0,0, N_POLAR, 7); m_BBfixed_BB_rectangular = m_BBfixed_BB_polarRect.block(N_POLAR,0, N_RECT, 7); std::cout << "Model created.\n" << std::endl; m_lastTrainingTimestamp = QDateTime::currentMSecsSinceEpoch(); // ************************************************************* // // // // copy all of the init data over to the containers for new data // // // // ************************************************************* // m_Bird4_new = m_Bird4; // deep copy m_timeData_new = m_timeData_init; // deep copy // training is done! m_isTrained = true; } } void CyclicModel::retrainModel() { if(!m_isTrained) { std::cerr << "Not trained yet!" << std::endl; } else { QElapsedTimer elTimer; elTimer.start(); // low pass filter the data filterNewObservations(); qint64 elNsec = elTimer.nsecsElapsed(); printf("filterNewObservations: %d ns\n", elNsec); elTimer.restart(); // update Fourier components // TODO : run these concurrently // Eigen::MatrixXd m_BBfixed_CT_polarRect = cycle_recalculate_concurrent(m_BBfixed_CT_filtered, m_omega0); // Eigen::MatrixXd m_BBfixed_BB_polarRect = cycle_recalculate_concurrent(m_BBfixed_BB_filtered, m_omega0); // Eigen::VectorXd m_Bird4_polarRect = cycle_recalculate_concurrent(m_Bird4_filtered, m_omega0); // std::cout << "mConcurrent1.resultCount() " << mConcurrent1.resultCount() << mConcurrent1.isRunning() << mConcurrent1.isFinished() << std::endl; // std::cout << "mConcurrent2.resultCount() " << mConcurrent2.resultCount() << mConcurrent2.isRunning() << mConcurrent2.isFinished()<< std::endl; // std::cout << "mConcurrent3.resultCount() " << mConcurrent3.resultCount() << mConcurrent3.isRunning() << mConcurrent3.isFinished()<< std::endl; // if( (mConcurrent1.resultCount() > 0) && (mConcurrent2.resultCount() > 0) && (mConcurrent3.resultCount() > 0) ) if( mConcurrent3.resultCount() > 0 ) { // m_BBfixed_CT_polarRect = mConcurrent1.result(); // // mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0); // m_BBfixed_CT_polar = m_BBfixed_CT_polarRect.block(0,0, N_POLAR, 7); // m_BBfixed_CT_rectangular = m_BBfixed_CT_polarRect.block(N_POLAR,0, N_RECT, 7); // m_BBfixed_BB_polarRect = mConcurrent2.result(); // // mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0); // m_BBfixed_BB_polar = m_BBfixed_BB_polarRect.block(0,0, N_POLAR, 7); // m_BBfixed_BB_rectangular = m_BBfixed_BB_polarRect.block(N_POLAR,0, N_RECT, 7); m_Bird4_polarRect = mConcurrent3.result(); // mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered_new, m_omega0); // m_Bird4_filtered m_Bird4_polar = m_Bird4_polarRect.segment(0, N_POLAR); // segment(i,n) : i = start idx, n = num elements m_Bird4_rectangular = m_Bird4_polarRect.segment(N_POLAR, N_RECT); // std::cout << "m_Bird4_polar\n" << m_Bird4_polar << std::endl; // std::cout << "m_Bird4_rectangular\n" << m_Bird4_rectangular << std::endl; // elNsec = elTimer.nsecsElapsed(); // std::cout << "Cycle recalc x2+x1 Nsec elapsed: " << elNsec << std::endl; // elTimer.restart(); // update the prediction of m_breathSignalFromModel double t_minus_t_begin; // m_breathSignalFromModel = EigenVectorFiltered::Zero(N_FILTERED); for(size_t i = 0; i < N_FILTERED; i++) { t_minus_t_begin = m_timeData_new[i+EDGE_EFFECT] - m_timeData_new[EDGE_EFFECT];//- m_timeData_init[N_FILTERED + EDGE_EFFECT - 1]; // t_minus_t_begin = (m_numSamples - N_SAMPLES + i)*SAMPLE_DELTA_TIME; if(m_isInVivo) { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // FIXME : do we need to differentiate b/w in vivo and benchtop? // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular); // WE'RE NOT SURE IF THIS -1.0 IS SUPPOSED TO BE HERE !!!!!!!!!! } else { m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular); } } // update period / freq updatePeriod( peakDetector(false) ); elNsec = elTimer.nsecsElapsed(); printf("Update period: %d ns\n", elNsec); elTimer.restart(); // update Fourier components // mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0, m_timeData_new); // mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0, m_timeData_new); mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered_new, m_omega0, m_timeData_new); } else { // if( (!mConcurrent1.isRunning()) && (!mConcurrent2.isRunning()) && (!mConcurrent3.isRunning()) ) if( !mConcurrent3.isRunning() ) { // std::cout << "Start concurrent." << std::endl; // mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0, m_timeData_new); // mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0, m_timeData_new); mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered_new, m_omega0, m_timeData_new); } // TODO : is this the best way to test this? what if one of them finishes during these checks? // update the prediction of m_breathSignalFromModel double t_minus_t_begin; // m_breathSignalFromModel = EigenVectorFiltered::Zero(N_FILTERED); for(size_t i = 0; i < N_FILTERED; i++) { t_minus_t_begin = m_timeData_new[i+EDGE_EFFECT] - m_timeData_new[EDGE_EFFECT];//- m_timeData_init[N_FILTERED + EDGE_EFFECT - 1]; // t_minus_t_begin = (m_numSamples - N_SAMPLES + i)*SAMPLE_DELTA_TIME; if(m_isInVivo) { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // FIXME : do we need to differentiate b/w in vivo and benchtop? // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular); // WE'RE NOT SURE IF THIS -1.0 IS SUPPOSED TO BE HERE !!!!!!!!!! } else { m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular); } } } m_lastTrainingTimestamp = QDateTime::currentMSecsSinceEpoch(); std::cout << "m_Bird4_polar: " << m_Bird4_polar(6); // get predictions based on the models //double t0 = m_timeData_new.back() - m_timeData_init[EDGE_EFFECT]; // double t0 = m_timeData_init.back() - m_timeData_init[EDGE_EFFECT]; // double t1 = t0; // + 0.0; fudge factor may be needed? // double t2 = t1 + (m_nFutureSamples - EDGE_EFFECT)*SAMPLE_DELTA_TIME; double t0 = m_timeData_init.back() - m_timeData_init[N_FILTERED + EDGE_EFFECT - 1]; double t1 = t0; // + 0.0; fudge factor may be needed? double t2 = t1 + (m_nFutureSamples - EDGE_EFFECT)*SAMPLE_DELTA_TIME; getPrediction7Axis(t1, m_BBfixed_CT_polar, m_BBfixed_CT_rectangular, m_BBfixed_CT_des, m_Bird4_polar(6)); getPrediction7Axis(t2, m_BBfixed_CT_polar, m_BBfixed_CT_rectangular, m_BBfixed_CTtraj_future_des, m_Bird4_polar(6)); getPrediction7Axis(t1, m_BBfixed_BB_polar, m_BBfixed_BB_rectangular, m_BBfixed_BB_des, m_Bird4_polar(6)); printf("CT_des_x %.3f CTtraj_future_des %.3f BB_des %.3f\n", m_BBfixed_CT_des(0), m_BBfixed_CTtraj_future_des(0), m_BBfixed_BB_des(0)); elNsec = elTimer.nsecsElapsed(); std::cout << "getPrediction Nsec elapsed: " << elNsec << std::endl; elTimer.restart(); } } void CyclicModel::updatePeriod(const double period) { // omega_0 = 2*pi*1/period; % 2*pi*breathing frequency (rad/sec) if(period > 20.) m_omega0 = 2.0*pi/BREATH_RATE; else m_omega0 = 2.0*pi/period; } void CyclicModel::setPlotFocus(int idx) { m_plotFocus = idx; } void CyclicModel::setInVivo(const bool isInVivo) { if( (!m_isTrained) && (m_numSamples == 0) ) m_isInVivo = isInVivo; else printf("Can't modify mode now!\n"); } void CyclicModel::filterTrainingData() { // TODO: run concurrent? m_LowPassFilter.run(m_BBfixed_CT, m_BBfixed_CT_filtered); //m_LowPassFilter.run(m_BBfixed_Instr, m_BBfixed_Instr_filtered); m_LowPassFilter.run(m_BBfixed_BB, m_BBfixed_BB_filtered); m_LowPassFilter.run(m_Bird4, m_Bird4_filtered); } void CyclicModel::filterNewObservations() { // TODO : only filter for the last added point m_LowPassFilter.run(m_Bird4_new, m_Bird4_filtered_new); } double CyclicModel::peakDetector(const bool runForInit) { std::vector<size_t> peakIdx; // container for indices double thresh; if(runForInit){ // look at Bird4 // EigenVectorFiltered::Index maxRow, maxCol, minRow, minCol; auto maxBird = m_Bird4_filtered.maxCoeff();//(&maxRow, &maxCol); auto minBird = m_Bird4_filtered.minCoeff(); double diffBird = maxBird - minBird; thresh = minBird + diffBird * PEAK_THRESHOLD; // find indices that are greater than thresh auto it = std::find_if(m_Bird4_filtered.data(), m_Bird4_filtered.data() + m_Bird4_filtered.size(), [thresh](double i){return i > thresh;}); while (it != (m_Bird4_filtered.data() + m_Bird4_filtered.size()) ) { peakIdx.emplace_back(std::distance(m_Bird4_filtered.data(), it)); it = std::find_if(std::next(it), m_Bird4_filtered.data() + m_Bird4_filtered.size(), [thresh](double i){return i > thresh;}); } } else { // look at Bird4 // EigenVectorFiltered::Index maxRow, maxCol, minRow, minCol; auto maxBird = m_Bird4_filtered_new.maxCoeff();//(&maxRow, &maxCol); auto minBird = m_Bird4_filtered_new.minCoeff(); double diffBird = maxBird - minBird; thresh = minBird + diffBird * PEAK_THRESHOLD; // find indices that are greater than thresh auto it = std::find_if(m_Bird4_filtered_new.data(), m_Bird4_filtered_new.data() + m_Bird4_filtered_new.size(), [thresh](double i){return i > thresh;}); while (it != (m_Bird4_filtered_new.data() + m_Bird4_filtered_new.size()) ) { peakIdx.emplace_back(std::distance(m_Bird4_filtered_new.data(), it)); it = std::find_if(std::next(it), m_Bird4_filtered_new.data() + m_Bird4_filtered_new.size(), [thresh](double i){return i > thresh;}); } } // get the timestamp at peaks std::vector<double> peaksTime; peaksTime.reserve(peakIdx.size()); // if initializing, then use "m_timeData_init", otherwise use "m_timeData_new" if(runForInit){ for(auto it = peakIdx.begin(); it != peakIdx.end(); ++it){ peaksTime.emplace_back(m_timeData_init[(*it) + EDGE_EFFECT]); } std::cout << "///runForInit///" << std::endl; } else{ for(auto it = peakIdx.begin(); it != peakIdx.end(); ++it){ peaksTime.emplace_back(m_timeData_new[(*it) + EDGE_EFFECT]); } std::cout << "///m_timeData_new///" << std::endl; } std::cout << std::endl; // take the difference of time stamps std::vector<double> peaksTdiff; peaksTdiff.reserve(peaksTime.size() - 1); std::transform(peaksTime.begin()+1,peaksTime.end(), peaksTime.begin(),std::back_inserter(peaksTdiff),std::minus<double>()); // find time differences larger than 1 seconds std::cout << "peakDetector peakGapsIdx: " << std::endl; double largeTimeGap = 1.0; // seconds std::vector<size_t> peakGapsIdx; // container for indices std::vector<double>::iterator it2 = std::find_if(peaksTdiff.begin(), peaksTdiff.end(), [largeTimeGap](double i){return i > largeTimeGap;}); while (it2 != peaksTdiff.end()) { peakGapsIdx.emplace_back(std::distance(peaksTdiff.begin(), it2)); it2 = std::find_if(std::next(it2), peaksTdiff.end(), [largeTimeGap](double i){return i > largeTimeGap;}); std::cout << peakGapsIdx.back() << " "; } std::cout << std::endl; // we better have peaks if(peakGapsIdx.size() < 1) { std::cout << "PeakDetector is in trouble! n=" << peakGapsIdx.size() << std::endl; return BREATH_RATE; } std::vector<double> peakTimesRight, peakTimesLeft; peakTimesLeft.emplace_back(peaksTime.front()); for(auto it3 = peakGapsIdx.begin(); it3 != peakGapsIdx.end(); ++it3){ peakTimesRight.emplace_back(peaksTime[*it3]); peakTimesLeft.emplace_back(peaksTime[1 + *it3]); } peakTimesRight.emplace_back(peaksTime.back()); // if peak_detect_me(1) > tops_thresh // tops_peak_times_right(1)=[]; // tops_peak_times_left(1)=[]; // end // if peak_detect_me(end) > tops_thresh // tops_peak_times_right(end)=[]; // tops_peak_times_left(end)=[]; // end if(runForInit) { if( m_Bird4_filtered.head(1)[0] > thresh ) { peakTimesRight.erase(peakTimesRight.begin()); peakTimesLeft.erase(peakTimesLeft.begin()); } if( m_Bird4_filtered.tail(1)[0] > thresh ) { peakTimesRight.pop_back(); peakTimesLeft.pop_back(); } } else{ if( m_Bird4_filtered_new.head(1)[0] > thresh ) { peakTimesRight.erase(peakTimesRight.begin()); peakTimesLeft.erase(peakTimesLeft.begin()); } if( m_Bird4_filtered_new.tail(1)[0] > thresh ) { peakTimesRight.pop_back(); peakTimesLeft.pop_back(); } } // better not be empty if(peakTimesLeft.size() < 1) { std::cout << "PeakDetector is in trouble 2!\n" << std::endl << std::flush; return BREATH_RATE; } // tops_peak_times_means = mean([tops_peak_times_right tops_peak_times_left],2); std::vector<double> mean; mean.reserve(peakTimesRight.size()); std::transform(peakTimesRight.begin(), peakTimesRight.end(), peakTimesLeft.begin(), std::back_inserter(mean), [](double r, double l){ return (l+r)/2.0; }); // if length(tops_peak_times_means)>1 // tops_peak_times_diffs = tops_peak_times_means(2:end)-tops_peak_times_means(1:(end-1)); // period=mean(tops_peak_times_diffs); // else // period=breath_expected; // end double period = 0.0; if(mean.size() > 1) { // take the difference of the means std::vector<double> meanDiffs; meanDiffs.reserve(mean.size()); std::transform(mean.begin()+1, mean.end(), mean.begin(), std::back_inserter(meanDiffs), std::minus<double>()); period = std::accumulate(meanDiffs.begin(),meanDiffs.end(),0.0) / (double)meanDiffs.size(); } else { period = BREATH_RATE; printf("Not enough means\n"); } if(runForInit) { // save the original peaks //m_respPeakMean = mean; // In vivo version has an error checker to make sure the breathing period is // between 4 - 5.5 seconds if(m_isInVivo) { // clamp if( (period < (BREATH_RATE*0.8)) || (period > (BREATH_RATE*1.2)) ) period = BREATH_RATE; } m_periods.clear(); m_periods.resize(PERIOD_FILTER_SIZE, period); m_periods.push_back(0); // index for circular buffer m_omega0_init = 2.0*pi/period;; } else { // double period_old = 2.0*pi/m_omega0; // // Get the time difference between peaks //// % All of these steps account for the fact that there could be multiple //// % peaks detected for the model or for the measured values. We need to find //// % the smallest absolute value peak time difference, but then preserve the //// % sign on that time difference to know whether the period should be faster //// % or slower. //// for j=1:size(tops_peak_times_means_model,1) //// for i=1:size(tops_peak_times_means_meas,1) //// peak_time_diff(i,j) = tops_peak_times_means_model(j)-tops_peak_times_means_meas(i); //// end //// [~, idx(j)]=min(abs(peak_time_diff(:,j))); //// time_diff(j)=peak_time_diff(idx(j),j); //// end //// [~,idx2]=min(abs(time_diff)); //// min_time_diff=time_diff(idx2); // peakDetectorForBreathModel(); // filter the breathing signal // m_respPeakMean = m_breathSignalPeakMean; // if(m_respPeakMean.size() < 1) // { // std::cout << "PeakDetector is in trouble 3!\n" << std::endl; // return period_old; // } // if (mean.size() == 0) // { // printf("mean.size() == 0"); // return period_old; // } // Eigen::MatrixXd peakTimeDiff = Eigen::MatrixXd::Zero(m_respPeakMean.size(), mean.size()); // Eigen::VectorXd timeDiff = Eigen::VectorXd::Zero(m_respPeakMean.size()); // double minTimeDiff; // Eigen::VectorXd::Index minIdx; // for(size_t iMeanModel = 0; iMeanModel < m_respPeakMean.size(); iMeanModel++) // { // for(size_t jMeanMeas = 0; jMeanMeas < mean.size(); jMeanMeas++) // { // peakTimeDiff(iMeanModel,jMeanMeas) = m_respPeakMean[iMeanModel] - mean[jMeanMeas]; // } // peakTimeDiff.row(iMeanModel).cwiseAbs().minCoeff(&minIdx); // timeDiff[iMeanModel] = peakTimeDiff(iMeanModel,minIdx); // } // timeDiff.cwiseAbs().minCoeff(&minIdx); // minTimeDiff = timeDiff(minIdx); //// minTimeDiff = timeDiff.cwiseAbs().minCoeff(); // double period_new; // if(mean.size() > 0) // { // printf("period_old: %.3f | minTimeDiff: %.3f | mean[0]: %.3f | m_timeData_new[EDGE_EFFECT]: %.3f\n", // period_old, minTimeDiff, mean[0], m_timeData_new[EDGE_EFFECT]); // period_new = period_old*(1.0 - minTimeDiff/(mean[0] - m_timeData_new[EDGE_EFFECT])); // mean[minIdx], m_timeData_init[EDGE_EFFECT] // //period_new = period_old*(1.0 - minTimeDiff/(mean[0] - m_timeData_init[EDGE_EFFECT])); // mean[minIdx], m_timeData_init[EDGE_EFFECT] // if(m_isInVivo) // in vivo mode // { // if( (period_new < (BREATH_RATE*0.9)) || (period_new > (BREATH_RATE*1.1)) ) // period_new = period_old; // } // else // benchtop mode // { // if( (period_new < (period_old*0.9)) || (period_new > (period_old*1.1)) ) // { // printf("New period %.3f is oob, setting to old.\n", period_new); // period_new = period_old; // } // } // // period = period_new; // } // else // printf("Mean is empty.\n"); m_periods[m_periods[PERIOD_FILTER_SIZE]] = period; // add new period to filter m_periods[PERIOD_FILTER_SIZE] = (double)(((int)(m_periods[PERIOD_FILTER_SIZE] + 1)) % (PERIOD_FILTER_SIZE)); // increment and mod counter period = std::accumulate(m_periods.begin(),m_periods.end()-1,0.0) / (double)(PERIOD_FILTER_SIZE); // mean } std::cout << "Period: " << period << std::endl << std::flush; return period; } void CyclicModel::peakDetectorForBreathModel() { // look at m_breathSignalFromModel auto maxBird = m_breathSignalFromModel.maxCoeff(); auto minBird = m_breathSignalFromModel.minCoeff(); double diffBird = maxBird - minBird; double thresh = minBird + diffBird * PEAK_THRESHOLD; // find indices that are greater than thresh std::vector<size_t> peakIdx; // container for indices auto it = std::find_if(m_breathSignalFromModel.data(), m_breathSignalFromModel.data() + m_breathSignalFromModel.size(), [thresh](double i){return i > thresh;}); while (it != (m_breathSignalFromModel.data() + m_breathSignalFromModel.size()) ) { peakIdx.emplace_back(std::distance(m_breathSignalFromModel.data(), it)); it = std::find_if(std::next(it), m_breathSignalFromModel.data() + m_breathSignalFromModel.size(), [thresh](double i){return i > thresh;}); } // get the timestamp at peaks std::vector<double> peaksTime; peaksTime.reserve(peakIdx.size()); // read m_timeData_new for(auto it = peakIdx.begin(); it != peakIdx.end(); ++it){ peaksTime.emplace_back(m_timeData_new[(*it) + EDGE_EFFECT]); } if (peaksTime.size() == 0) { std::cout << "PeakDetector is in trouble! peaksTime.size is 0" << std::endl; return; } // take the difference of time stamps std::vector<double> peaksTdiff; peaksTdiff.reserve(peaksTime.size() - 1); std::transform(peaksTime.begin()+1,peaksTime.end(), peaksTime.begin(),std::back_inserter(peaksTdiff),std::minus<double>()); // find time differences larger than 1 seconds std::cout << "peakDetectorForBreathModel : peakGapsIdx: " << std::endl; double largeTimeGap = 1.0; // seconds std::vector<size_t> peakGapsIdx; // container for indices auto it2 = std::find_if(std::begin(peaksTdiff), std::end(peaksTdiff), [largeTimeGap](double i){return i > largeTimeGap;}); while (it2 != std::end(peaksTdiff)) { peakGapsIdx.emplace_back(std::distance(std::begin(peaksTdiff), it2)); it2 = std::find_if(std::next(it2), std::end(peaksTdiff), [largeTimeGap](double i){return i > largeTimeGap;}); std::cout << peakGapsIdx.back() << " "; } std::cout << std::endl; // we better have peaks if(peakGapsIdx.size() < 1) { std::cout << "PeakDetector is in trouble! n=" << peakGapsIdx.size() << std::endl; return; } std::vector<double> peakTimesRight, peakTimesLeft; peakTimesLeft.emplace_back(peaksTime.front()); for(auto it3 = peakGapsIdx.begin(); it3 != peakGapsIdx.end(); ++it3){ peakTimesRight.emplace_back(peaksTime[*it3]); peakTimesLeft.emplace_back(peaksTime[1 + *it3]); } peakTimesRight.emplace_back(peaksTime.back()); if( m_breathSignalFromModel.head(1)[0] > thresh ) { peakTimesRight.erase(peakTimesRight.begin()); peakTimesLeft.erase(peakTimesLeft.begin()); } if( m_breathSignalFromModel.tail(1)[0] > thresh ) { peakTimesRight.pop_back(); peakTimesLeft.pop_back(); } // better not be empty if(peakTimesLeft.size() < 1) { std::cout << "PeakDetector is in trouble 2! n=" << peakTimesLeft.size() << std::endl; return; } // tops_peak_times_means = mean([tops_peak_times_right tops_peak_times_left],2); std::vector<double> mean; mean.reserve(peakTimesRight.size()); std::transform(peakTimesRight.begin(), peakTimesRight.end(), peakTimesLeft.begin(), std::back_inserter(mean), [](double r, double l){ return (l+r)/2.0; }); m_breathSignalPeakMean = mean; } void CyclicModel::cycle_recalculate(const EigenMatrixFiltered &z_init, EigenMatrixRectangular &x_rect, EigenMatrixPolar &x_polar, const double omega0) { // TODO: add error checking to ensure that the vector size is correct if( z_init.cols() != 7 ) printf("cycle_recalculate: Wrong column size!\n"); if( z_init.rows() != N_FILTERED ) printf("cycle_recalculate: Wrong row size!\n"); // get all of the constants size_t m = N_HARMONICS; // m = number of sinusoid components double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point size_t N_initpts = N_SAMPLES; // number of initialization points size_t edge_effect = EDGE_EFFECT; double omega_0 = omega0; // calculate things from inputs size_t num_states = m * 2 + 2; //size_t N_filtered = N_initpts - 2 * edge_effect; // parse the already low pass filtered data Eigen::VectorXd z_init_x = z_init.col(0); Eigen::VectorXd z_init_y = z_init.col(1); Eigen::VectorXd z_init_z = z_init.col(2); Eigen::VectorXd z_init_xaxis = z_init.col(3); Eigen::VectorXd z_init_yaxis = z_init.col(4); Eigen::VectorXd z_init_zaxis = z_init.col(5); Eigen::VectorXd z_init_angle = z_init.col(6); // allocate zero matrices Eigen::MatrixXd A_init_x(N_FILTERED, num_states - 1); A_init_x.setZero(); A_init_x.col(0).setOnes(); Eigen::MatrixXd A_init_y(N_FILTERED, num_states - 1); A_init_y.setZero(); A_init_y.col(0).setOnes(); Eigen::MatrixXd A_init_z(N_FILTERED, num_states - 1); A_init_z.setZero(); A_init_z.col(0).setOnes(); Eigen::MatrixXd A_init_xaxis(N_FILTERED, num_states - 1); A_init_xaxis.setZero(); A_init_xaxis.col(0).setOnes(); Eigen::MatrixXd A_init_yaxis(N_FILTERED, num_states - 1); A_init_yaxis.setZero(); A_init_yaxis.col(0).setOnes(); Eigen::MatrixXd A_init_zaxis(N_FILTERED, num_states - 1); A_init_zaxis.setZero(); A_init_zaxis.col(0).setOnes(); Eigen::MatrixXd A_init_angle(N_FILTERED, num_states - 1); A_init_angle.setZero(); A_init_angle.col(0).setOnes(); for (int i = 0; i < N_FILTERED; i++) { for (int j = 1; j <= m; j++) { A_init_x(i, j) = sin(j*omega_0*i*delta_t); A_init_y(i, j) = sin(j*omega_0*i*delta_t); A_init_z(i, j) = sin(j*omega_0*i*delta_t); A_init_xaxis(i, j) = sin(j*omega_0*i*delta_t); A_init_yaxis(i, j) = sin(j*omega_0*i*delta_t); A_init_zaxis(i, j) = sin(j*omega_0*i*delta_t); A_init_angle(i, j) = sin(j*omega_0*i*delta_t); A_init_x(i, j + m) = cos(j*omega_0*i*delta_t); A_init_y(i, j + m) = cos(j*omega_0*i*delta_t); A_init_z(i, j + m) = cos(j*omega_0*i*delta_t); A_init_xaxis(i, j + m) = cos(j*omega_0*i*delta_t); A_init_yaxis(i, j + m) = cos(j*omega_0*i*delta_t); A_init_zaxis(i, j + m) = cos(j*omega_0*i*delta_t); A_init_angle(i, j + m) = cos(j*omega_0*i*delta_t); } } // Step 2. Use least squares estimate to solve for x. //VectorXd x_init_x = pseudoInverse(A_init_x) * z_init_x; Eigen::VectorXd x_init_x = A_init_x.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_x); Eigen::VectorXd x_init_y = A_init_y.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_y); Eigen::VectorXd x_init_z = A_init_z.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_z); Eigen::VectorXd x_init_xaxis = A_init_xaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_xaxis); Eigen::VectorXd x_init_yaxis = A_init_yaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_yaxis); Eigen::VectorXd x_init_zaxis = A_init_zaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_zaxis); Eigen::VectorXd x_init_angle = A_init_angle.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_angle); x_rect.col(0) = x_init_x; x_rect.col(1) = x_init_y; x_rect.col(2) = x_init_z; x_rect.col(3) = x_init_xaxis; x_rect.col(4) = x_init_yaxis; x_rect.col(5) = x_init_zaxis; x_rect.col(6) = x_init_angle; //VectorXd x_rect_x = x_init_x; //VectorXd x_rect_y = x_init_y; //VectorXd x_rect_z = x_init_z; //VectorXd x_rect_xaxis = x_init_xaxis; //VectorXd x_rect_yaxis = x_init_yaxis; //VectorXd x_rect_zaxis = x_init_zaxis; //VectorXd x_rect_angle = x_init_angle; // Step 3. Convert from rectangular into polar and assemble the state // vector, x, at k = 430 (which is the last trustworthy state we can know) // State vector, x // x = [c; r(1:4); omega; theta(1:4)]; Eigen::VectorXd x_polar_x(num_states); x_polar_x.setZero(); Eigen::VectorXd x_polar_y(num_states); x_polar_y.setZero(); Eigen::VectorXd x_polar_z(num_states); x_polar_z.setZero(); Eigen::VectorXd x_polar_xaxis(num_states); x_polar_xaxis.setZero(); Eigen::VectorXd x_polar_yaxis(num_states); x_polar_yaxis.setZero(); Eigen::VectorXd x_polar_zaxis(num_states); x_polar_zaxis.setZero(); Eigen::VectorXd x_polar_angle(num_states); x_polar_angle.setZero(); x_polar_x(0) = x_init_x(0); // c(dc offset) x_polar_y(0) = x_init_y(0); // c(dc offset) x_polar_z(0) = x_init_z(0); // c(dc offset) x_polar_xaxis(0) = x_init_xaxis(0); // c(dc offset) x_polar_yaxis(0) = x_init_yaxis(0); // c(dc offset) x_polar_zaxis(0) = x_init_zaxis(0); // c(dc offset) x_polar_angle(0) = x_init_angle(0); // c(dc offset) for (size_t i = 1; i <= m; i++) { x_polar_x(i) = std::sqrt(std::pow(x_init_x(i), 2) + std::pow(x_init_x(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_y(i) = std::sqrt(std::pow(x_init_y(i), 2) + std::pow(x_init_y(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_z(i) = std::sqrt(std::pow(x_init_z(i), 2) + std::pow(x_init_z(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_xaxis(i) = std::sqrt(std::pow(x_init_xaxis(i), 2) + std::pow(x_init_xaxis(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_yaxis(i) = std::sqrt(std::pow(x_init_yaxis(i), 2) + std::pow(x_init_yaxis(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_zaxis(i) = std::sqrt(std::pow(x_init_zaxis(i), 2) + std::pow(x_init_zaxis(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_angle(i) = std::sqrt(std::pow(x_init_angle(i), 2) + std::pow(x_init_angle(i + m), 2)); // r_i, convert rectangular coords back to polar } x_polar_x(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_y(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_z(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_xaxis(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_yaxis(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_zaxis(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_angle(m + 1) = omega_0; // omega_0, (rad / sec) for (int i = 0; i < m; i++) { x_polar_x(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_x(i + m + 1), x_init_x(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_y(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_y(i + m + 1), x_init_y(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_z(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_z(i + m + 1), x_init_z(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_xaxis(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_xaxis(i + m + 1), x_init_xaxis(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_yaxis(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_yaxis(i + m + 1), x_init_yaxis(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_zaxis(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_zaxis(i + m + 1), x_init_zaxis(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_angle(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_angle(i + m + 1), x_init_angle(i + 1)); // theta = i*omega*T + phi, (rad) } x_polar.col(0) = x_polar_x; x_polar.col(1) = x_polar_y; x_polar.col(2) = x_polar_z; x_polar.col(3) = x_polar_xaxis; x_polar.col(4) = x_polar_yaxis; x_polar.col(5) = x_polar_zaxis; x_polar.col(6) = x_polar_angle; } void CyclicModel::cycle_recalculate(const EigenVectorFiltered &z_init, EigenVectorRectangular &x_rect, EigenVectorPolar &x_polar, const double omega0) { // TODO: add error checking to ensure that the vector size is correct if( z_init.rows() != N_FILTERED ) printf("cycle_recalculate: Wrong row size!\n"); // get all of the constants size_t m = N_HARMONICS; // m = number of sinusoid components double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point size_t N_initpts = N_SAMPLES; // number of initialization points size_t edge_effect = EDGE_EFFECT; double omega_0 = omega0; // calculate things from inputs size_t num_states = m * 2 + 2; //size_t N_filtered = N_initpts - 2 * edge_effect; // parse the already low pass filtered data // Eigen::VectorXd z_init_x = z_init; // allocate zero matrices Eigen::MatrixXd A_init(N_FILTERED, num_states - 1); A_init.setZero(); A_init.col(0).setOnes(); for (int i = 0; i < N_FILTERED; i++) { for (int j = 1; j <= m; j++) { A_init(i, j) = sin(j*omega_0*i*delta_t); A_init(i, j + m) = cos(j*omega_0*i*delta_t); } } // Step 2. Use least squares estimate to solve for x. //VectorXd x_init_x = pseudoInverse(A_init) * z_init; Eigen::VectorXd x_init = A_init.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init); // Eigen::VectorXd x_init = A_init.colPivHouseholderQr().solve(z_init); // maybe faster? x_rect = x_init; // Step 3. Convert from rectangular into polar and assemble the state // vector, x, at k = 430 (which is the last trustworthy state we can know) // State vector, x // x = [c; r(1:4); omega; theta(1:4)]; x_polar.setZero(num_states); x_polar(0) = x_init(0); // c(dc offset) for (size_t i = 1; i <= m; i++) { x_polar(i) = std::sqrt(std::pow(x_init(i), 2) + std::pow(x_init(i + m), 2)); // r_i, convert rectangular coords back to polar } x_polar(m + 1) = omega_0; // omega_0, (rad / sec) for (int i = 0; i < m; i++) { x_polar(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init(i + m + 1), x_init(i + 1)); // theta = i*omega*T + phi, (rad) } //x_polar = x_polar; } Eigen::MatrixXd CyclicModel::cycle_recalculate_concurrentM(const EigenMatrixFiltered &z_init, const double omega0, const std::vector<double> &timeData) { if( z_init.cols() != 7 ) printf("cycle_recalculate: Wrong column size!\n"); if( z_init.rows() != N_FILTERED ) printf("cycle_recalculate: Wrong row size!\n"); // get all of the constants size_t m = N_HARMONICS; // m = number of sinusoid components double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point size_t N_initpts = N_SAMPLES; // number of initialization points //size_t edge_effect = EDGE_EFFECT; double omega_0 = omega0; // calculate things from inputs size_t num_states = m * 2 + 2; //size_t N_filtered = N_initpts - 2 * edge_effect; // parse the already low pass filtered data Eigen::VectorXd z_init_x = z_init.col(0); Eigen::VectorXd z_init_y = z_init.col(1); Eigen::VectorXd z_init_z = z_init.col(2); Eigen::VectorXd z_init_xaxis = z_init.col(3); Eigen::VectorXd z_init_yaxis = z_init.col(4); Eigen::VectorXd z_init_zaxis = z_init.col(5); Eigen::VectorXd z_init_angle = z_init.col(6); // allocate zero matrices Eigen::MatrixXd A_init_x(N_FILTERED, num_states - 1); A_init_x.setZero(); A_init_x.col(0).setOnes(); Eigen::MatrixXd A_init_y(N_FILTERED, num_states - 1); A_init_y.setZero(); A_init_y.col(0).setOnes(); Eigen::MatrixXd A_init_z(N_FILTERED, num_states - 1); A_init_z.setZero(); A_init_z.col(0).setOnes(); Eigen::MatrixXd A_init_xaxis(N_FILTERED, num_states - 1); A_init_xaxis.setZero(); A_init_xaxis.col(0).setOnes(); Eigen::MatrixXd A_init_yaxis(N_FILTERED, num_states - 1); A_init_yaxis.setZero(); A_init_yaxis.col(0).setOnes(); Eigen::MatrixXd A_init_zaxis(N_FILTERED, num_states - 1); A_init_zaxis.setZero(); A_init_zaxis.col(0).setOnes(); Eigen::MatrixXd A_init_angle(N_FILTERED, num_states - 1); A_init_angle.setZero(); A_init_angle.col(0).setOnes(); double t, s, c; for (int i = 0; i < N_FILTERED; i++) { t = timeData[i+EDGE_EFFECT] - timeData[EDGE_EFFECT]; for (int j = 1; j <= m; j++) { s = sin(j*omega_0*t); c = cos(j*omega_0*t); A_init_x(i, j) = s; A_init_y(i, j) = s; A_init_z(i, j) = s; A_init_xaxis(i, j) = s; A_init_yaxis(i, j) = s; A_init_zaxis(i, j) = s; A_init_angle(i, j) = s; A_init_x(i, j + m) = c; A_init_y(i, j + m) = c; A_init_z(i, j + m) = c; A_init_xaxis(i, j + m) = c; A_init_yaxis(i, j + m) = c; A_init_zaxis(i, j + m) = c; A_init_angle(i, j + m) = c; } } // Step 2. Use least squares estimate to solve for x. //VectorXd x_init_x = pseudoInverse(A_init_x) * z_init_x; Eigen::VectorXd x_init_x = A_init_x.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_x); Eigen::VectorXd x_init_y = A_init_y.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_y); Eigen::VectorXd x_init_z = A_init_z.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_z); Eigen::VectorXd x_init_xaxis = A_init_xaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_xaxis); Eigen::VectorXd x_init_yaxis = A_init_yaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_yaxis); Eigen::VectorXd x_init_zaxis = A_init_zaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_zaxis); Eigen::VectorXd x_init_angle = A_init_angle.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_angle); // Eigen::VectorXd x_init_x = A_init_x.colPivHouseholderQr().solve(z_init_x); // Eigen::VectorXd x_init_y = A_init_y.colPivHouseholderQr().solve(z_init_y); // Eigen::VectorXd x_init_z = A_init_z.colPivHouseholderQr().solve(z_init_z); // Eigen::VectorXd x_init_xaxis = A_init_xaxis.colPivHouseholderQr().solve(z_init_xaxis); // Eigen::VectorXd x_init_yaxis = A_init_yaxis.colPivHouseholderQr().solve(z_init_yaxis); // Eigen::VectorXd x_init_zaxis = A_init_zaxis.colPivHouseholderQr().solve(z_init_zaxis); // Eigen::VectorXd x_init_angle = A_init_angle.colPivHouseholderQr().solve(z_init_angle); EigenMatrixRectangular x_rect; x_rect.col(0) = x_init_x; x_rect.col(1) = x_init_y; x_rect.col(2) = x_init_z; x_rect.col(3) = x_init_xaxis; x_rect.col(4) = x_init_yaxis; x_rect.col(5) = x_init_zaxis; x_rect.col(6) = x_init_angle; //VectorXd x_rect_x = x_init_x; //VectorXd x_rect_y = x_init_y; //VectorXd x_rect_z = x_init_z; //VectorXd x_rect_xaxis = x_init_xaxis; //VectorXd x_rect_yaxis = x_init_yaxis; //VectorXd x_rect_zaxis = x_init_zaxis; //VectorXd x_rect_angle = x_init_angle; // Step 3. Convert from rectangular into polar and assemble the state // vector, x, at k = 430 (which is the last trustworthy state we can know) // State vector, x // x = [c; r(1:4); omega; theta(1:4)]; Eigen::VectorXd x_polar_x(num_states); x_polar_x.setZero(); Eigen::VectorXd x_polar_y(num_states); x_polar_y.setZero(); Eigen::VectorXd x_polar_z(num_states); x_polar_z.setZero(); Eigen::VectorXd x_polar_xaxis(num_states); x_polar_xaxis.setZero(); Eigen::VectorXd x_polar_yaxis(num_states); x_polar_yaxis.setZero(); Eigen::VectorXd x_polar_zaxis(num_states); x_polar_zaxis.setZero(); Eigen::VectorXd x_polar_angle(num_states); x_polar_angle.setZero(); x_polar_x(0) = x_init_x(0); // c(dc offset) x_polar_y(0) = x_init_y(0); // c(dc offset) x_polar_z(0) = x_init_z(0); // c(dc offset) x_polar_xaxis(0) = x_init_xaxis(0); // c(dc offset) x_polar_yaxis(0) = x_init_yaxis(0); // c(dc offset) x_polar_zaxis(0) = x_init_zaxis(0); // c(dc offset) x_polar_angle(0) = x_init_angle(0); // c(dc offset) for (size_t i = 1; i <= m; i++) { x_polar_x(i) = std::sqrt(std::pow(x_init_x(i), 2) + std::pow(x_init_x(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_y(i) = std::sqrt(std::pow(x_init_y(i), 2) + std::pow(x_init_y(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_z(i) = std::sqrt(std::pow(x_init_z(i), 2) + std::pow(x_init_z(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_xaxis(i) = std::sqrt(std::pow(x_init_xaxis(i), 2) + std::pow(x_init_xaxis(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_yaxis(i) = std::sqrt(std::pow(x_init_yaxis(i), 2) + std::pow(x_init_yaxis(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_zaxis(i) = std::sqrt(std::pow(x_init_zaxis(i), 2) + std::pow(x_init_zaxis(i + m), 2)); // r_i, convert rectangular coords back to polar x_polar_angle(i) = std::sqrt(std::pow(x_init_angle(i), 2) + std::pow(x_init_angle(i + m), 2)); // r_i, convert rectangular coords back to polar } x_polar_x(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_y(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_z(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_xaxis(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_yaxis(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_zaxis(m + 1) = omega_0; // omega_0, (rad / sec) x_polar_angle(m + 1) = omega_0; // omega_0, (rad / sec) t = timeData[N_FILTERED + EDGE_EFFECT - 1] - timeData[EDGE_EFFECT]; for (int i = 0; i < m; i++) { x_polar_x(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_x(i + m + 1), x_init_x(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_y(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_y(i + m + 1), x_init_y(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_z(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_z(i + m + 1), x_init_z(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_xaxis(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_xaxis(i + m + 1), x_init_xaxis(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_yaxis(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_yaxis(i + m + 1), x_init_yaxis(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_zaxis(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_zaxis(i + m + 1), x_init_zaxis(i + 1)); // theta = i*omega*T + phi, (rad) x_polar_angle(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_angle(i + m + 1), x_init_angle(i + 1)); // theta = i*omega*T + phi, (rad) } EigenMatrixPolar x_polar; x_polar.col(0) = x_polar_x; x_polar.col(1) = x_polar_y; x_polar.col(2) = x_polar_z; x_polar.col(3) = x_polar_xaxis; x_polar.col(4) = x_polar_yaxis; x_polar.col(5) = x_polar_zaxis; x_polar.col(6) = x_polar_angle; Eigen::MatrixXd result(N_POLAR + N_RECT, 7); result << x_polar, x_rect; return result; } Eigen::VectorXd CyclicModel::cycle_recalculate_concurrentV(const EigenVectorFiltered &z_init, const double omega0, const std::vector<double> &timeData) { // TODO: add error checking to ensure that the vector size is correct if( z_init.rows() != N_FILTERED ) printf("cycle_recalculate: Wrong row size!\n"); EigenVectorPolar x_polar; EigenVectorRectangular x_rect; // get all of the constants size_t m = N_HARMONICS; // m = number of sinusoid components double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point size_t N_initpts = N_SAMPLES; // number of initialization points -> should this be N_FILTERED? //size_t edge_effect = EDGE_EFFECT; double omega_0 = omega0; // calculate things from inputs size_t num_states = m * 2 + 2; //size_t N_filtered = N_initpts - 2 * edge_effect; // parse the already low pass filtered data // Eigen::VectorXd z_init_x = z_init; // allocate zero matrices Eigen::MatrixXd A_init(N_FILTERED, num_states - 1); A_init.setZero(); A_init.col(0).setOnes(); double t; for (int i = 0; i < N_FILTERED; i++) { t = timeData[i+EDGE_EFFECT] - timeData[EDGE_EFFECT]; for (int j = 1; j <= m; j++) { // A_init(i, j) = sin(j*omega_0*i*delta_t); // A_init(i, j + m) = cos(j*omega_0*i*delta_t); A_init(i, j) = std::sin(j*omega_0*t); A_init(i, j + m) = std::cos(j*omega_0*t); } } // Step 2. Use least squares estimate to solve for x. //VectorXd x_init_x = pseudoInverse(A_init) * z_init; Eigen::VectorXd x_init = A_init.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init); //Eigen::VectorXd x_init = A_init.colPivHouseholderQr().solve(z_init); // maybe faster? x_rect = x_init; // Step 3. Convert from rectangular into polar and assemble the state // vector, x, at k = 430 (which is the last trustworthy state we can know) // State vector, x // x = [c; r(1:4); omega; theta(1:4)]; x_polar.setZero(num_states); x_polar(0) = x_init(0); // c(dc offset) for (size_t i = 1; i <= m; i++) { x_polar(i) = std::sqrt(std::pow(x_init(i), 2) + std::pow(x_init(i + m), 2)); // r_i, convert rectangular coords back to polar } x_polar(m + 1) = omega_0; // (rad / sec) t = timeData[N_FILTERED + EDGE_EFFECT - 1] - timeData[EDGE_EFFECT]; for (int i = 0; i < m; i++) { x_polar(i + m + 2) = std::fmod(((double)i + 1.0)*omega_0*t + std::atan2(x_init(i + m + 1), x_init(i + 1)), 2*pi); // theta = i*omega*T + phi, (rad) } Eigen::VectorXd result(N_POLAR + N_RECT); result << x_polar, x_rect; return result; } double CyclicModel::getPrediction(const double timeShift, const EigenVectorPolar &x_polar, const EigenVectorRectangular &x_rect) { // Make sure the time coming in is already (t1[j] - t_begin) double x_des; using namespace std; if(m_isTrained) { x_des = 0.0; for (size_t i = 0; i < N_HARMONICS; i++) { x_des += x_polar(i+1) * std::sin( (i+1.0)*x_polar(N_HARMONICS+1)*timeShift + std::atan2( x_rect(i+N_HARMONICS+1), x_rect(i+1) ) ); //x_des += x_polar(i+1) * std::sin( ( (i+1.0)*x_polar(N_HARMONICS+1)*timeShift + std::atan2( x_rect(i+N_HARMONICS+1), x_rect(i+1) ) )/2.0 ); //x_des += x_polar(i+1) * std::sin( (i+1.0)*(x_polar(N_HARMONICS+1)*timeShift) + x_polar(i+N_HARMONICS+1) ); } x_des += x_polar(0); } else { x_des = std::numeric_limits<double>::quiet_NaN(); printf("quiet_NaN!!!\n"); } return x_des ; } void CyclicModel::getPrediction7Axis(const double timeShift, const EigenMatrixPolar &x_polar, const EigenMatrixRectangular &x_rect, EigenVector7d &X_des, const double phase) { // Make sure the time coming in is already (t1[j] - t_begin) // double period_orig = 2*pi/m_omega0_init; // double period_new = 2*pi/m_omega0; // double dif = (period_orig - period_new)/period_orig; double phDif = m_omega0_init * timeShift; if(m_isTrained) { X_des = EigenVector7d::Zero(); // if(X_des.size() != 7) // printf("X_des.size() != 7\n"); for(size_t j = 0; j < X_des.size(); j++) { for (size_t i = 0; i < N_HARMONICS; i++) { //X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*x_polar(N_HARMONICS+1,j)*timeShift + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) ); //X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*m_omega0*(phase/2.0/pi * period_orig) + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) ); //X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*m_omega0*((phase/2.0/pi-dif) * period_orig) + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) ); //X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*phase + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) ); //X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*(phase + m_omega0_init*(m_timeData_init.back() - m_timeData_init.front())) ); //X_des(j) = X_des(j) + x_polar(i+1,j) * sin( phase + (i+1.0)*( m_omega0_init*(m_timeData_init.back() - m_timeData_init[EDGE_EFFECT]))); X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*(phase + phDif - atan2( x_rect(N_HARMONICS+1,j), x_rect(1,j) )) + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) ); } X_des(j) = X_des(j) + x_polar(0,j); } } else { //X_des = EigenVector7d::Zero(); X_des = EigenVector7d::Constant(std::numeric_limits<double>::quiet_NaN()); printf("quiet_NaN7!!!\n"); } } void CyclicModel::loadData(QString filename, std::vector<double> &X) { // check if the directory exists QFile inFile(filename); if( inFile.open(QIODevice::ReadOnly) ) qDebug() << "Opened inFile" << filename; QTextStream in(&inFile); double dummy; while(!in.atEnd()) { in >> dummy; X.push_back(dummy); } qDebug() << "Read" << X.size() << "points."; } void CyclicModel::load4x4Data(QString filename, EigenStdVecVector7d &X) { // check if the directory exists QFile inFile(filename); if( inFile.open(QIODevice::ReadOnly) ) qDebug() << "Opened inFile" << filename; QTextStream in(&inFile); double dummy; EigenAffineTransform3d tempT; while(!in.atEnd()) { for(size_t i = 0; i < 4; i++) { for(size_t j = 0; j < 4; j++) { if(in.atEnd()) { qDebug() << "Early termination!" << filename; return; } in >> dummy; if(i < 3) tempT(i,j) = dummy; } } // axis angle EigenVector7d temp7d; Eigen::AngleAxisd tempEA(tempT.rotation()); temp7d << tempT(0,3), tempT(1,3), tempT(2,3), tempEA.axis()(0), tempEA.axis()(1), tempEA.axis()(2), tempEA.angle(); // push newest readings X.push_back(temp7d); } qDebug() << "Read" << X.size() << "points."; } void CyclicModel::load4x4Data(QString filename, std::vector<std::vector<double> > &X) { // check if the directory exists QFile inFile(filename); if( inFile.open(QIODevice::ReadOnly) ) qDebug() << "Opened inFile" << filename; QTextStream in(&inFile); double dummy; EigenAffineTransform3d tempT; X.clear(); X.resize(7,std::vector<double>()); while(!in.atEnd()) { for(size_t i = 0; i < 4; i++) { for(size_t j = 0; j < 4; j++) { if(in.atEnd()) { qDebug() << "Early termination!" << filename; return; } in >> dummy; if(i < 3) tempT(i,j) = dummy; } } // axis angle EigenVector7d temp7d; Eigen::AngleAxisd tempEA(tempT.rotation()); // push newest readings X[0].push_back(tempT(0,3)); X[1].push_back(tempT(1,3)); X[2].push_back(tempT(2,3)); X[3].push_back(tempEA.axis()(0)); X[4].push_back(tempEA.axis()(1)); X[5].push_back(tempEA.axis()(2)); X[6].push_back(tempEA.angle()); } qDebug() << "Read" << X.size() << "points."; } void CyclicModel::saveFilteredData(QString filename, const std::vector<double> &Y) { QFile outFile(filename); if( outFile.open(QIODevice::WriteOnly) ) qDebug() << "Opened outFile" << filename; QTextStream out(&outFile); for(size_t i = 0; i < Y.size(); i++) out << QString::number(Y[i], 'f', 4) << "\n"; qDebug() << "Wrote" << Y.size() << "points."; } void CyclicModel::saveFilteredData(QString filename, const EigenVectorFiltered &Y) { QFile outFile(filename); if( outFile.open(QIODevice::WriteOnly) ) qDebug() << "Opened outFile" << filename; QTextStream out(&outFile); for(size_t i = 0; i < Y.size(); i++) out << QString::number(Y[i], 'f', 4) << "\n"; qDebug() << "Wrote" << Y.size() << "points."; } void CyclicModel::save4x4FilteredData(QString filename, const EigenStdVecVector7d &Y) { QFile outFile(filename); if( outFile.open(QIODevice::WriteOnly) ) qDebug() << "Opened outFile" << filename; QTextStream out(&outFile); for(size_t i = 0; i < Y.size(); i++) { out << QString::number(Y[i](0), 'f', 4) << " " << QString::number(Y[i](1), 'f', 4) << " " << QString::number(Y[i](2), 'f', 4) << " " << QString::number(Y[i](3), 'f', 4) << " " << QString::number(Y[i](4), 'f', 4) << " " << QString::number(Y[i](5), 'f', 4) << " " << QString::number(Y[i](6), 'f', 4) << "\n"; } qDebug() << "Wrote" << Y.size() << "points."; } void CyclicModel::save4x4FilteredData(QString filename, const EigenMatrixFiltered &Y) { QFile outFile(filename); if( outFile.open(QIODevice::WriteOnly) ) qDebug() << "Opened outFile" << filename; QTextStream out(&outFile); for(size_t i = 0; i < Y.rows(); i++) { out << QString::number(Y(i,0), 'f', 4) << " " << QString::number(Y(i,1), 'f', 4) << " " << QString::number(Y(i,2), 'f', 4) << " " << QString::number(Y(i,3), 'f', 4) << " " << QString::number(Y(i,4), 'f', 4) << " " << QString::number(Y(i,5), 'f', 4) << " " << QString::number(Y(i,6), 'f', 4) << "\n"; } qDebug() << "Wrote" << Y.rows() << "points."; } void CyclicModel::testLPF() { //FIR lpf (Low_pass (60, 150, FILTER_ORDER)); QString inputFile("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\data_to_filter_x.txt"); QString outputFile("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\filtered_data_x_Cpp.txt"); filtfilt lpf; std::vector<double> X,Y; loadData(inputFile, X); X.pop_back(); // delete the last 0 // for(auto x : X) // std::cout << x << std::endl; QElapsedTimer elTimer; elTimer.start(); lpf.run(X, Y); lpf.run(X, Y); lpf.run(X, Y); lpf.run(X, Y); lpf.run(X, Y); qint64 elNsec = elTimer.nsecsElapsed(); qDebug() << "\nNsec elapsed:" << elNsec/5; saveFilteredData(outputFile, Y); // test run(const std::vector<double> &X, EigenVectorFiltered &Y); EigenVectorFiltered Y2; elTimer.restart(); lpf.run(X, Y2); lpf.run(X, Y2); lpf.run(X, Y2); lpf.run(X, Y2); lpf.run(X, Y2); elNsec = elTimer.nsecsElapsed(); qDebug() << "\n>>> EigenVectorFiltered Nsec elapsed:" << elNsec/5; //saveFilteredData(outputFile, Y2); // Test 7 axis filtering QString inputFile7d("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\data_to_filter.txt"); QString outputFile7d("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\filtered_data_Cpp.txt"); EigenStdVecVector7d X_7dv, Y_7dv; load4x4Data(inputFile7d, X_7dv); elTimer.restart(); lpf.run(X_7dv, Y_7dv); elNsec = elTimer.nsecsElapsed(); qDebug() << "\n>>> 7d Nsec elapsed:" << elNsec; //save4x4FilteredData(outputFile7d, Y_7dv); // test run(const std::vector<double> &X, EigenVectorFiltered &Y); EigenMatrixFiltered Y3; elTimer.restart(); lpf.run(X_7dv, Y3); elNsec = elTimer.nsecsElapsed(); qDebug() << "\n>>> EigenMatrixFiltered Nsec elapsed:" << elNsec; save4x4FilteredData(outputFile7d, Y3); // std::vector<std::vector<double>> Xvv; load4x4Data(inputFile7d, Xvv); elTimer.restart(); EigenVectorFiltered temp; for(size_t i = 0; i<7; i++) { lpf.run(Xvv[i], temp); Y3.col(i) = temp; } elNsec = elTimer.nsecsElapsed(); qDebug() << "\n>>> std::vector<std::vector<double>> Nsec elapsed:" << elNsec; //save4x4FilteredData(outputFile7d, Y3); }
71,550
C++
41.18809
186
0.578756
adegirmenci/HBL-ICEbot/ControllerWidget/sweep.cpp
#include "sweep.h" Sweep::Sweep(unsigned int nSteps_, double stepAngle_, double convLimit_, qint64 imgDuration_): isActive(false), nControlCycles(0), remSteps(nSteps_), nSteps(nSteps_), stepAngle(stepAngle_), convergenceLimit(convLimit_), isConverged(false), imagingDuration(imgDuration_) { } void Sweep::activate() { overallTimer.start(); reset(); isActive = true; } void Sweep::reset() { isActive = false; nControlCycles = 0; remSteps = nSteps; isConverged = false; } // reports required psy increment in radians int Sweep::update(const double currPsy) { if(isActive) // sweeping { nControlCycles++; // increment counter if(isConverged) // converged to target { if(timer.hasExpired(imagingDuration)) // done with this step { remSteps--; if(remSteps < 1) // done with sweep { reset(); // reset counters return SWEEP_DONE; } else { isConverged = false; return SWEEP_NEXT; } } else // still taking images return SWEEP_CONVERGED_ACQUIRING; // stay in place } else // not converged { if(abs(currPsy) < convergenceLimit) // converged! { isConverged = true; timer.start(); // start counting down return SWEEP_CONVERGED; } else // twiddle thumbs { return SWEEP_WAIT_TO_CONVERGE; } } } else // not even active return SWEEP_INACTIVE; }
1,803
C++
23.378378
72
0.497504
adegirmenci/HBL-ICEbot/ControllerWidget/kinematics_4dof.cpp
#include "kinematics_4dof.h" Kinematics_4DOF::Kinematics_4DOF(double L, double Rc, double Dknob) : m_L(L), m_Rc(Rc), m_dknob(Dknob) { } Kinematics_4DOF::~Kinematics_4DOF() { } void Kinematics_4DOF::operator =(const Kinematics_4DOF &Other) { m_L = Other.m_L; m_Rc = Other.m_Rc; m_dknob = Other.m_dknob; } Eigen::Transform<double, 3, Eigen::Affine> Kinematics_4DOF::forwardKinematics(double gamma, double theta, double alpha, double d) { if(alpha < 0) { alpha = std::abs(alpha); // flip sign theta = wrapToPi(theta + pi); } Eigen::Matrix4d t_; if(alpha > 0.000001) { t_ << sin(gamma + theta)*sin(theta) + cos(gamma + theta)*cos(theta)*cos(alpha), -sin(gamma + theta)*cos(theta) + cos(gamma + theta)*sin(theta)*cos(alpha), cos(theta + gamma)*sin(alpha), (m_L*cos(theta + gamma)*(1. - cos(alpha)))/alpha, -cos(gamma + theta)*sin(theta) + sin(gamma + theta)*cos(theta)*cos(alpha), cos(gamma + theta)*cos(theta) + sin(gamma + theta)*sin(theta)*cos(alpha), sin(theta + gamma)*sin(alpha), (m_L*sin(gamma + theta)*(1. - cos(alpha)))/alpha, -cos(theta)*sin(alpha), -sin(theta)*sin(alpha), cos(alpha), d + (m_L*sin(alpha))/alpha, 0, 0, 0, 1; } else { t_ << cos(gamma), -sin(gamma), 0, 0, sin(gamma), cos(gamma), 0, 0, 0, 0, 1, d + m_L, 0, 0, 0, 1; } Eigen::Transform<double, 3, Eigen::Affine> T(t_); return T; } Eigen::Transform<double, 3, Eigen::Affine> Kinematics_4DOF::forwardKinematics(const Eigen::Vector4d &config) { return forwardKinematics(config(0),config(1),config(2),config(3)); } Eigen::Vector4d Kinematics_4DOF::inverseKinematics3D(const double xt, const double yt, const double zt, const double gamma) { double theta, alpha, d; // If gamma is not provided, this problem is underdefined. 1 DoF is free since we didn't specify // an orientation for the US crystal. We deal with this by setting default gamma to zero. if( (std::abs(xt) < 0.000001) && (std::abs(yt) < 0.000001) ) { theta = 0.0; // bending axis 0 alpha = 0.0; // bending angle 0 d = zt - m_L; // translation } else { double gamma_plus_theta = atan2(yt, xt); // roll plus bending axis angle //std::cout << "atan2(1.0,0.0) = " << atan2(1.0,0.0) << std::endl; // Checking for this is not necessary, since atan2 returns pi/2 if x = 0 //if(xt == 0) // gamma_plus_theta = boost::math::copysign(pi/2., yt); theta = gamma_plus_theta - gamma; double df = sqrt(pow(xt,2) + pow(yt,2)); double c = df/m_L; // constant //bool fZeroSuccess = fZeroAlpha(c, alpha); fZeroAlpha(c, alpha); d = zt - (m_L*sin(alpha))/alpha; // translation } // gamma = wrapToPi(gamma); // theta = wrapToPi(theta); // Calculate tip and final position vectors Eigen::Transform<double, 3, Eigen::Affine> Tcalc = forwardKinematics(gamma,theta,alpha,d); // Check if there is any error between given and calculated final position double tip_given = sqrt(pow(xt,2) + pow(yt,2) + pow(zt,2)); //double tip_calc = sqrt( pow(Tcalc(0,3),2) + pow(Tcalc(1,3),2) + pow(Tcalc(2,3),2) ); double tip_calc = Tcalc.matrix().col(3).segment(0,3).norm(); double err = (tip_given - tip_calc)/tip_given; if(std::abs(err) > 0.000001) printf("BIG ERROR (%f) CHECK PARAMETERS\n", err); // if(true) // { // // Report to user // printf("Distance d is:\n\t %f mm\n", d); // printf("Angle gamma is:\n\t %f radians\n\t = %f degrees\n", gamma, gamma*180.0/pi); // printf("Angle theta is:\n\t %f radians\n\t = %f degrees\n", theta, theta*180.0/pi); // printf("Angle alpha is:\n\t %f radians\n\t = %f degrees\n", alpha, alpha*180.0/pi); // } return Eigen::Vector4d(gamma,theta,alpha,d); } Eigen::Vector4d Kinematics_4DOF::inverseKinematics(const Eigen::Transform<double, 3, Eigen::Affine> &T, const double gamma) { // get position from matrix double xt = T(0,3); double yt = T(1,3); double zt = T(2,3); double theta, alpha, d; if( (std::abs(xt) < 0.000001) && (std::abs(yt) < 0.000001) ) { theta = 0; // bending axis 0 alpha = 0; // bending angle 0 d = zt - m_L; // translation } else { double gamma_plus_theta = atan2(yt, xt); // roll plus bending axis angle theta = gamma_plus_theta - gamma; bool fZeroSuccess; if (fmod(gamma_plus_theta,pi) == 0) { double c = xt/m_L/cos(gamma_plus_theta); // constant fZeroSuccess = fZeroAlpha(c, alpha); } else { double c = yt/m_L/sin(gamma_plus_theta); // constant fZeroSuccess = fZeroAlpha(c, alpha); } d = zt - (m_L*sin(alpha))/alpha; // translation } //gamma = wrapToPi(gamma); theta = wrapToPi(theta); // Calculate tip and final position vectors //Eigen::Transform<double, 3, Eigen::Affine> T_curr_calc = forwardKinematics(gamma,theta,alpha,d); return Eigen::Vector4d(gamma,theta,alpha,d); } Eigen::Matrix<double, 4, 2> Kinematics_4DOF::control_icra2016(const Eigen::Transform<double, 3, Eigen::Affine> &T, const Eigen::Vector4d &dX, double gamma) { // Run inverse kinematics to get configuration space parameters Eigen::Vector4d configCurr = inverseKinematics(T, gamma); Eigen::Transform<double, 3, Eigen::Affine> T_Curr = forwardKinematics(configCurr); Eigen::Vector4d jointsCurr = configToJointSpace(configCurr); double xt = T_Curr(0,3) + dX(0); double yt = T_Curr(1,3) + dX(1); double zt = T_Curr(2,3) + dX(2); // Figure out angular deltas based on desired tip position // Keep the same amount of catheter base roll Eigen::Vector4d configTgt = inverseKinematics3D(xt, yt, zt, configCurr(0)); // gammaCurr Eigen::Transform<double, 3, Eigen::Affine> T_Tgt = forwardKinematics(configTgt); //std::cout << "Target Tform\n" << T_Tgt.matrix() << std::endl; // Figure out how much to unroll // Project initial x axis to the final x-y plane Eigen::Vector3d x_init = T_Curr.rotation().block<3,1>(0,0); Eigen::Vector3d x_final = T_Tgt.rotation().block<3,1>(0,0); Eigen::Vector3d z_final = T_Tgt.rotation().block<3,1>(0,2); Eigen::Vector3d x_init_proj = x_init - x_init.dot(z_final)*z_final; x_init_proj.normalize(); //std::cout << "x_init_proj\n" << x_init_proj << std::endl; // Find the angle between the projected and final x axes Eigen::Vector3d cross_xinit_xfinal = x_final.cross(x_init_proj); cross_xinit_xfinal.normalize(); //std::cout << "cross_xinit_xfinal\n" << cross_xinit_xfinal << std::endl; double dot_xinitproj_xfinal = x_init_proj.dot(x_final); //std::cout << "dot_xinitproj_xfinal\n" << dot_xinitproj_xfinal << std::endl; // The dot product can be slightly larger than 1 or -1, causing acos to return NAN if( (-1.0 > dot_xinitproj_xfinal) && (dot_xinitproj_xfinal > -1.01)) dot_xinitproj_xfinal = -1.0; if( (1.0 < dot_xinitproj_xfinal) && (dot_xinitproj_xfinal < 1.01) ) dot_xinitproj_xfinal = 1.0; double delta_angle = acos(dot_xinitproj_xfinal); //std::cout << "delta_angle\n" << delta_angle << std::endl; if( z_final.dot(cross_xinit_xfinal) < 0.0) delta_angle = -delta_angle; // account for directionality //std::cout << "delta_angle\n" << delta_angle << std::endl; // Add the unroll and user's desired roll angles to handle roll double angle_diff = delta_angle + dX(3); // dX(3) =>> dpsi in MATLAB configTgt(0) = configTgt(0) + angle_diff; // (gamma) update handle roll angle configTgt(1) = configTgt(1) - angle_diff; // (theta) update bending axis angle // Get the target configuration space paramters and joint angles T_Tgt = forwardKinematics(configTgt); // update transform Eigen::Vector4d jointsTgt = configToJointSpace(configTgt); Eigen::Matrix<double, 4, 2> jointsCurrAndTgt; //std::cout << "Joints Curr\n" << jointsCurr << std::endl; //std::cout << "Joints Target\n" << jointsTgt << std::endl; jointsCurrAndTgt << jointsCurr, jointsTgt; return jointsCurrAndTgt; } Eigen::Matrix<double, 6, 4> Kinematics_4DOF::JacobianNumeric(double gamma, double theta, double alpha, double d) { double del_ = 0.0001; // small bump // vary d Eigen::Transform<double, 3, Eigen::Affine> T1plus = forwardKinematics(gamma,theta,alpha,d + del_); Eigen::Transform<double, 3, Eigen::Affine> T1minus = forwardKinematics(gamma,theta,alpha,d - del_); // vary gamma Eigen::Transform<double, 3, Eigen::Affine> T2plus = forwardKinematics(gamma + del_,theta,alpha,d); Eigen::Transform<double, 3, Eigen::Affine> T2minus = forwardKinematics(gamma - del_,theta,alpha,d); // vary theta Eigen::Transform<double, 3, Eigen::Affine> T3plus = forwardKinematics(gamma,theta + del_,alpha,d); Eigen::Transform<double, 3, Eigen::Affine> T3minus = forwardKinematics(gamma,theta - del_,alpha,d); // vary alpha Eigen::Transform<double, 3, Eigen::Affine> T4plus = forwardKinematics(gamma,theta,alpha + del_,d); Eigen::Transform<double, 3, Eigen::Affine> T4minus = forwardKinematics(gamma,theta,alpha - del_,d); // numerical x double delx1 = (T1plus(0,3) - T1minus(0,3))/(2*del_); double delx2 = (T2plus(0,3) - T2minus(0,3))/(2*del_); double delx3 = (T3plus(0,3) - T3minus(0,3))/(2*del_); double delx4 = (T4plus(0,3) - T4minus(0,3))/(2*del_); // numerical y double dely1 = (T1plus(1,3) - T1minus(1,3))/(2*del_); double dely2 = (T2plus(1,3) - T2minus(1,3))/(2*del_); double dely3 = (T3plus(1,3) - T3minus(1,3))/(2*del_); double dely4 = (T4plus(1,3) - T4minus(1,3))/(2*del_); // numerical z double delz1 = (T1plus(2,3) - T1minus(2,3))/(2*del_); double delz2 = (T2plus(2,3) - T2minus(2,3))/(2*del_); double delz3 = (T3plus(2,3) - T3minus(2,3))/(2*del_); double delz4 = (T4plus(2,3) - T4minus(2,3))/(2*del_); // numerical angle 1 Eigen::Vector3d angles1Plus = T1plus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles1Minus = T1minus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles1 = (angles1Plus - angles1Minus)/(2*del_); // numerical angle 2 Eigen::Vector3d angles2Plus = T2plus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles2Minus = T2minus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles2 = (angles2Plus - angles2Minus)/(2*del_); // numerical angle 3 Eigen::Vector3d angles3Plus = T3plus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles3Minus = T3minus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles3 = (angles3Plus - angles3Minus)/(2*del_); // numerical angle 4 Eigen::Vector3d angles4Plus = T4plus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles4Minus = T4minus.rotation().eulerAngles(2,1,0); Eigen::Vector3d angles4 = (angles4Plus - angles4Minus)/(2*del_); // numerical angles x double angx1 = angles1(2); double angx2 = angles2(2); double angx3 = angles3(2); double angx4 = angles4(2); // numerical angles y double angy1 = angles1(1); double angy2 = angles2(1); double angy3 = angles3(1); double angy4 = angles4(1); // numerical angles z double angz1 = angles1(0); double angz2 = angles2(0); double angz3 = angles3(0); double angz4 = angles4(0); Eigen::Matrix<double, 6, 4> J; J << delx1, delx2, delx3, delx4, dely1, dely2, dely3, dely4, delz1, delz2, delz3, delz4, angx1, angx2, angx3, angx4, angy1, angy2, angy3, angy4, angz1, angz2, angz3, angz4; return J; } Eigen::Vector4d Kinematics_4DOF::dampedLeastSquaresStep(const Eigen::Matrix<double, 6, 4> &J, const Eigen::Matrix<double, 6, 1> &C_error) { // calculate the condition number Eigen::Matrix<double, 4, 4> We4 = Eigen::Matrix<double, 4, 4>::Identity() * (1./4.); // weighting matrix Eigen::Matrix<double, 6, 6> We6 = Eigen::Matrix<double, 6, 6>::Identity() * (1./6.); // weighting matrix double kap = sqrt( (J*We4*J.transpose()).trace() * (J.transpose()*We6*J).trace() ); // Weighted Frobenius norm //double kap = sqrt( (J*J.transpose()).trace() * (J.transpose*J).trace() ); // Frobenius norm double condNum = 1./kap; // condition number printf("J cond = %.3f\n", condNum); // lambda = 0.2; double lambda = condNum; Eigen::Matrix<double, 6, 6> mtrx = (J * J.transpose() + Eigen::Matrix<double, 6, 6>::Identity() * lambda); // Eigen::JacobiSVD<MatrixXf> svd(J, ComputeThinU | ComputeThinV); // Eigen::Matrix<double, 6, 4> E; // E(0,0) = svd.singularValues()(0) / (svd.singularValues()(0)*svd.singularValues()(0) + kap*kap); // E(1,1) = svd.singularValues()(1) / (svd.singularValues()(1)*svd.singularValues()(1) + kap*kap); // E(2,2) = svd.singularValues()(2) / (svd.singularValues()(2)*svd.singularValues()(2) + kap*kap); // E(3,3) = svd.singularValues()(3) / (svd.singularValues()(3)*svd.singularValues()(3) + kap*kap); // Eigen::Matrix<double, 4, 6> VEUT = svd.matrixV() * E * svd.matrixU().transpose(); // Eigen::Vector4d delta_C = VEUT * C_error; //Eigen::Vector4d delta_C = J.transpose()* mtrx.inverse() * C_error; Eigen::Vector4d delta_C = J.transpose()* mtrx.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(C_error); return delta_C; } // taskSpace = {x,y,z,psi} // configSpace = {gamma,theta,alpha,d} Eigen::Vector4d Kinematics_4DOF::taskToConfigSpace(const Eigen::Vector4d &taskSpace) { double xt = taskSpace(0), yt = taskSpace(1), zt = taskSpace(2), psi = taskSpace(3); double gamma, theta, alpha, d; if( (std::abs(xt) < 0.000001) && (std::abs(yt) < 0.000001) ) { alpha = 0; theta = 0; gamma = psi; d = zt - m_L; } else { double gamma_plus_theta = atan2(yt, xt); // roll plus bending axis angle theta = psi; gamma = gamma_plus_theta - psi; bool fZeroSuccess; if (fmod(gamma_plus_theta,pi) == 0) { double c = xt/m_L/cos(gamma_plus_theta); // constant fZeroSuccess = fZeroAlpha(c, alpha); } else { double c = yt/m_L/sin(gamma_plus_theta); // constant fZeroSuccess = fZeroAlpha(c, alpha); } d = zt - (m_L*sin(alpha))/alpha; // translation } // gamma = wrapToPi(gamma); // theta = wrapToPi(theta); if(alpha < 0) printf("\n\n\n\n\n ALPHA LESS THAN ZERO!!! \n\n\n\n\n"); return Eigen::Vector4d(gamma,theta,alpha,d); } // {gamma,theta,alpha,d} Eigen::Vector4d Kinematics_4DOF::configToTaskSpace(const Eigen::Vector4d &configSpace) { double gamma = configSpace(0), theta = configSpace(1), alpha = configSpace(2), d = configSpace(3); double x,y,z,psi; if(std::abs(alpha) < 0.0001) { x = 0; y = 0; z = d + m_L; psi = gamma; } else { double r = m_L*(1.0-cos(alpha))/alpha; x = r*cos(gamma + theta); y = r*sin(gamma + theta); z = d + m_L*sin(alpha)/alpha; psi = theta; } return Eigen::Vector4d(x,y,z,psi); } Eigen::Matrix4d Kinematics_4DOF::JacobianNumericTaskSpace(const Eigen::Vector4d &configCurr) { double gamma = configCurr(0), theta = configCurr(1), alpha = configCurr(2), d = configCurr(3); double del_ = 0.0001; // small bump // vary d Eigen::Transform<double, 3, Eigen::Affine> T1plus = forwardKinematics(gamma,theta,alpha,d + del_); Eigen::Transform<double, 3, Eigen::Affine> T1minus = forwardKinematics(gamma,theta,alpha,d - del_); // psi1plus = theta; // psi1minus = theta; // vary gamma Eigen::Transform<double, 3, Eigen::Affine> T2plus = forwardKinematics(gamma + del_,theta,alpha,d); Eigen::Transform<double, 3, Eigen::Affine> T2minus = forwardKinematics(gamma - del_,theta,alpha,d); // psi2plus = theta; // psi2minus = theta; // vary theta Eigen::Transform<double, 3, Eigen::Affine> T3plus = forwardKinematics(gamma,theta + del_,alpha,d); Eigen::Transform<double, 3, Eigen::Affine> T3minus = forwardKinematics(gamma,theta - del_,alpha,d); double psi3plus = theta + del_; double psi3minus = theta - del_; // vary alpha Eigen::Transform<double, 3, Eigen::Affine> T4plus = forwardKinematics(gamma,theta,alpha + del_,d); Eigen::Transform<double, 3, Eigen::Affine> T4minus = forwardKinematics(gamma,theta,alpha - del_,d); // psi4plus = theta; // psi4minus = theta; // numerical x double delx1 = (T1plus(0,3) - T1minus(0,3))/(2*del_); double delx2 = (T2plus(0,3) - T2minus(0,3))/(2*del_); double delx3 = (T3plus(0,3) - T3minus(0,3))/(2*del_); double delx4 = (T4plus(0,3) - T4minus(0,3))/(2*del_); // numerical y double dely1 = (T1plus(1,3) - T1minus(1,3))/(2*del_); double dely2 = (T2plus(1,3) - T2minus(1,3))/(2*del_); double dely3 = (T3plus(1,3) - T3minus(1,3))/(2*del_); double dely4 = (T4plus(1,3) - T4minus(1,3))/(2*del_); // numerical z double delz1 = (T1plus(2,3) - T1minus(2,3))/(2*del_); double delz2 = (T2plus(2,3) - T2minus(2,3))/(2*del_); double delz3 = (T3plus(2,3) - T3minus(2,3))/(2*del_); double delz4 = (T4plus(2,3) - T4minus(2,3))/(2*del_); // numerical psi // psi1,2,4 = 0 double psi3 = (psi3plus - psi3minus)/(2*del_); Eigen::Matrix4d J; if(std::abs(alpha) < 0.0001){ J << 1e-12, delx3, delx4, delx1, dely2, 1e-12, dely4, dely1, delz2, delz3, delz4, delz1, psi3, 0.0, 0.0, 0.0; } else{ J << delx2, delx3, delx4, delx1, dely2, dely3, dely4, dely1, delz2, delz3, delz4, delz1, 0.0, psi3, 0.0, 0.0; } return J; } Eigen::Vector4d Kinematics_4DOF::JacobianStep(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig) { Eigen::Vector4d dxyzpsi = targetTask - currTask; dxyzpsi(3) = wrapToPi(dxyzpsi(3)); double normXYZ = dxyzpsi.segment<3>(0).norm(), errorRot = std::abs(dxyzpsi(3)); double euclThresh = 1.5; double rotThresh = pi/5; Eigen::Vector4d delta_C; delta_C = Eigen::Vector4d::Zero(); Eigen::Vector4d newConfig = currConfig; Eigen::Vector4d newTask = currTask; //Eigen::Vector4d oldTask = newTask, intm_task; unsigned int iter = 0; bool isNotConverged = (normXYZ > 0.01) || (errorRot > 0.01); while( isNotConverged && (iter < 30) ) { // clamp error // don't translate more than 1.5 at a time if(normXYZ > euclThresh) dxyzpsi.segment<3>(0) *= euclThresh/normXYZ; // don't rotate more than 36 degrees at a time if(std::abs(dxyzpsi(3)) > rotThresh) dxyzpsi(3) = boost::math::copysign(rotThresh, dxyzpsi(3)); // numerically compute Jacobian Eigen::Matrix4d J = JacobianNumericTaskSpace(newConfig); // J_pseudoinverseWithNullspace Eigen::Vector4d v_(0.5,0.5,0.5,0.5); v_ *= 2.0; Eigen::JacobiSVD<Eigen::Matrix4d> svd(J, Eigen::ComputeThinU | Eigen::ComputeThinV); //Eigen::Matrix4d pinvJ = svd.solve(Eigen::Matrix4d::Identity()); // J.inverse(); //delta_C = pinvJ * dxyzpsi + (Eigen::Matrix4d::Identity() - pinvJ*J)*v_; delta_C = svd.solve(dxyzpsi) + (Eigen::Matrix4d::Identity() - svd.solve(J))*v_; // oldTask = configToTaskSpace(newConfig); newConfig += delta_C; if(newConfig(2) < 0.0) // gamma, theta, alpha, d { newConfig(2) = std::abs(newConfig(2)); newConfig(1) = wrapToPi(newConfig(1) + pi); } // intm_task = configToTaskSpace(newConfig); // newTask += (intm_task - oldTask); newTask = configToTaskSpace(newConfig); dxyzpsi = targetTask - newTask; dxyzpsi(3) = wrapToPi(dxyzpsi(3)); normXYZ = dxyzpsi.segment<3>(0).norm(); errorRot = std::abs(dxyzpsi(3)); isNotConverged = (normXYZ > 0.01) || (errorRot > 0.01); iter++; } if(isNotConverged) { printf("Not converged, %.3f %.3f.\n", normXYZ, errorRot); //newConfig = currConfig; } else printf("Converged in %d steps.\n", iter); return newConfig; } Eigen::Vector4d Kinematics_4DOF::JacobianStepSingle(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig) { Eigen::Vector4d dxyzpsi = targetTask - currTask; dxyzpsi(3) = wrapToPi(dxyzpsi(3)); double normXYZ = dxyzpsi.segment<3>(0).norm(), errorRot = std::abs(dxyzpsi(3)); double euclThresh = 1.5; double rotThresh = pi/5; Eigen::Vector4d delta_C; delta_C = Eigen::Vector4d::Zero(); bool isNotConverged = (normXYZ > 0.01) || (errorRot > 0.01); if( isNotConverged ) { // clamp error // don't translate more than 1.5 at a time if(normXYZ > euclThresh) dxyzpsi.segment<3>(0) *= euclThresh/normXYZ; // don't rotate more than 36 degrees at a time if(std::abs(dxyzpsi(3)) > rotThresh) dxyzpsi(3) = boost::math::copysign(rotThresh, dxyzpsi(3)); // numerically compute Jacobian Eigen::Matrix4d J = JacobianNumericTaskSpace(currConfig); // J_pseudoinverseWithNullspace Eigen::Vector4d v_(0.5,0.5,0.5,0.5); v_ *= 2.0; Eigen::JacobiSVD<Eigen::Matrix4d> svd(J, Eigen::ComputeThinU | Eigen::ComputeThinV); //Eigen::Matrix4d pinvJ = svd.solve(Eigen::Matrix4d::Identity()); // J.inverse(); //delta_C = pinvJ * dxyzpsi + (Eigen::Matrix4d::Identity() - pinvJ*J)*v_; delta_C = svd.solve(dxyzpsi) + (Eigen::Matrix4d::Identity() - svd.solve(J))*v_; } return delta_C; } double Kinematics_4DOF::wrapToPi(double lambda) { double signedPI = boost::math::copysign(pi, lambda); return lambda = fmod(lambda + signedPI,(2*pi)) - signedPI; } bool Kinematics_4DOF::fZeroAlpha(const double c, double &alpha) { // Newton's Method - init double a0 = 2*c; // initial guess double a1 = 0.0, y, yprime; bool foundSoln = false; // Newton's Method - iterate for(size_t i = 0; i < 25; i++) { y = 1.0 - cos(a0) - a0*c; // function yprime = sin(a0) - c; // 1st derivative if(std::abs(yprime) < 1.0e-14) break; a1 = a0 - y/yprime; if(std::abs(a1 - a0) <= (1.0e-7 * std::abs(a1)) ) { //printf("Found solution in %d steps.\n", i+1); foundSoln = true; break; } a0 = a1 ; } // Newton's Method - end if(!foundSoln) printf("fzero failed!!!\n"); alpha = a1; return foundSoln; } /*! * @param[in] d Translation * @param[in] gamma Roll angle * @param[in] theta Bending axis angle * @param[in] alpha Bending angle * @param[in] Rc Catheter radius * @param[in] dknob Diameter of the knob * @param[out] outputs A vector that contains the following values: * phi_trans : Translation * phi_pitch : Roll angle * phi_yaw : Bending axis angle * phi_roll : Bending angle */ void Kinematics_4DOF::configToJointSpace(const double gamma, const double theta, const double alpha, const double d, Eigen::Vector4d &outputs) { // Paul added a negative in front of this to be consistent with the way yaw is defined // for the catheter absolute joint angles outputs(0) = d; outputs(1) = 2.0 * ( m_Rc * alpha * cos(theta)) / m_dknob; outputs(2) = 2.0 * (-m_Rc * alpha * sin(theta)) / m_dknob; outputs(3) = gamma; // compensate for pitch/yaw coupling and losses // double tempPitch, tempYaw; // tempPitch = outputs(1)*PITCH_WP + outputs(2)*PITCH_WY + PITCH_BIAS; // tempYaw = outputs(1)*YAW_WP + outputs(2)*YAW_WY + YAW_BIAS; // outputs(1) = tempPitch;// /PITCH_SUM; // outputs(2) = tempYaw;// /YAW_SUM; } void Kinematics_4DOF::configToJointSpace(const Eigen::Vector4d &inputs, Eigen::Vector4d &outputs) { configToJointSpace(inputs(0),inputs(1),inputs(2),inputs(3),outputs); } Eigen::Vector4d Kinematics_4DOF::configToJointSpace(const Eigen::Vector4d &inputs) { Eigen::Vector4d outputs; configToJointSpace(inputs, outputs); return outputs; } Eigen::Vector4d Kinematics_4DOF::configToLearnedJointSpace(const Eigen::Vector4d &currConfig, const Eigen::Matrix<double, 4, -1> &configHistory, const Eigen::Vector4d &deltaConfig) { // feed into ML model to get target joint angles Eigen::Vector4d joints;// = getJointPrediction(currConfig, configHistory, deltaConfig); return joints; }
26,681
C++
37.336207
154
0.568869
adegirmenci/HBL-ICEbot/ControllerWidget/gainswidget.cpp
#include "gainswidget.h" #include "ui_gainswidget.h" gainsWidget::gainsWidget(QWidget *parent) : QWidget(parent), ui(new Ui::gainsWidget) { ui->setupUi(this); this->setWindowTitle("Adjust Gains"); qRegisterMetaType<GainsPYRT>("GainsPYRT"); qRegisterMetaType<ConvergenceLimits>("ConvergenceLimits"); } gainsWidget::~gainsWidget() { delete ui; } void gainsWidget::on_closeButton_clicked() { emit closeGainsWindow(); } void gainsWidget::closeEvent(QCloseEvent *event) { emit closeGainsWindow(); event->accept(); } void gainsWidget::on_setGainsButton_clicked() { GainsPYRT gains; gains.kPitchMin = ui->gainPitchMinSpinbox->value(); gains.kPitch = gains.kPitchMin; gains.kPitchMax = ui->gainPitchMaxSpinbox->value(); gains.kYawMin = ui->gainYawMinSpinbox->value(); gains.kYaw = gains.kYawMin; gains.kYawMax = ui->gainYawMaxSpinbox->value(); gains.kRollMin = ui->gainRollMinSpinbox->value(); gains.kRoll = gains.kRollMin; gains.kRollMax = ui->gainRollMaxSpinbox->value(); gains.kTransMin = ui->gainTransMinSpinbox->value(); gains.kTrans = gains.kTransMin; gains.kTransMax = ui->gainTransMaxSpinbox->value(); emit setGains(gains); } void gainsWidget::on_setLimitsButton_clicked() { ConvergenceLimits limits; limits.posMin = ui->posConvMinSpinbox->value(); limits.posMax = ui->posConvMaxSpinbox->value(); limits.angleMin = ui->angConvMinSpinbox->value(); limits.angleMax = ui->angConvMaxSpinbox->value(); emit setLimits(limits); }
1,558
C++
22.621212
62
0.700257
adegirmenci/HBL-ICEbot/ControllerWidget/kinematics_4dof.h
#ifndef KINEMATICS_4DOF_H #define KINEMATICS_4DOF_H #include <math.h> //#include <chrono> //#include <thread> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/math/special_functions/sign.hpp> //#include <boost/math/tools/roots.hpp> #include <Eigen/Dense> #include <Eigen/SVD> #include <Eigen/StdVector> #include <Eigen/Geometry> #include "../icebot_definitions.h" /*! * \brief Four degree of freedom catheter kinematics class. * \author Alperen Degirmenci * \version 1.0alpha * \date 2015-2016 */ class Kinematics_4DOF { public: Kinematics_4DOF(double L = 1.0, double Rc = 1.0, double Dknob = 1.0); ~Kinematics_4DOF(); void operator = (const Kinematics_4DOF &Other); // assignment operator definition // Configuration space to joint space void configToJointSpace(const double gamma, const double theta, const double alpha, const double d, Eigen::Vector4d &outputs); void configToJointSpace(const Eigen::Vector4d &inputs, Eigen::Vector4d &outputs); Eigen::Vector4d configToJointSpace(const Eigen::Vector4d &inputs); // new mapping based on learning Eigen::Vector4d configToLearnedJointSpace(const Eigen::Vector4d &currConfig, const Eigen::Matrix<double, 4, -1> &configHistory, const Eigen::Vector4d &deltaConfig); // Forward Kinematics Eigen::Transform<double, 3, Eigen::Affine> forwardKinematics(double gamma, double theta, double alpha, double d); Eigen::Transform<double, 3, Eigen::Affine> forwardKinematics(const Eigen::Vector4d &config); // Inverse Kinematics Eigen::Vector4d inverseKinematics3D(const double xt, const double yt, const double zt, const double gamma = 0.0); Eigen::Vector4d inverseKinematics(const Eigen::Transform<double, 3, Eigen::Affine> &T, const double gamma); // 4 DOF Eigen::Matrix<double, 4, 2> control_icra2016(const Eigen::Transform<double, 3, Eigen::Affine> &T, const Eigen::Vector4d &dX, double gamma); Eigen::Matrix<double, 6, 4> JacobianNumeric(double gamma, double theta, double alpha, double d); Eigen::Vector4d dampedLeastSquaresStep(const Eigen::Matrix<double, 6, 4> &J, const Eigen::Matrix<double,6,1> &C_error); // new kinematics with global heading Eigen::Vector4d taskToConfigSpace(const Eigen::Vector4d &taskSpace); Eigen::Vector4d configToTaskSpace(const Eigen::Vector4d &configSpace); Eigen::Matrix4d JacobianNumericTaskSpace(const Eigen::Vector4d &configCurr); Eigen::Vector4d JacobianStep(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig); Eigen::Vector4d JacobianStepSingle(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig); private: // GEOMETRY CONSTANTS double m_L; // constant length of distal bending section, for all ICE double m_Rc; // radius of catheter double m_dknob; // diameter of pulley inside the handle knob // STATE Eigen::Vector4d m_state; // Helper functions double wrapToPi(double lambda); bool fZeroAlpha(const double c, double &alpha); // time since last loop // time between EM readings public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; static const double pi = boost::math::constants::pi<double>(); static const double deg180overPi = 180.0/pi; static const double piOverDeg180 = pi/180.0; template <typename T> inline T lerp(const T v0, const T v1, const T t) { return (1-t)*v0 + t*v1; } #endif // KINEMATICS_4DOF_H
4,361
C
35.35
142
0.583582
adegirmenci/HBL-ICEbot/ControllerWidget/controllerwidget.cpp
#include "controllerwidget.h" #include "ui_controllerwidget.h" ControllerWidget::ControllerWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ControllerWidget), gainWidget(new gainsWidget), m_respModelWidget(new respModelWidget) { ui->setupUi(this); m_worker = new ControllerThread(); m_worker->moveToThread(&m_thread); connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); m_thread.start(); connect(this, SIGNAL(tellWorkerToPrintThreadID()), m_worker, SLOT(printThreadID())); connect(m_worker, SIGNAL(sendMsgToWidget(QString,int)), this, SLOT(receiveMsgFromWorker(QString,int))); connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); // updates connect(this, SIGNAL(updateJointSpaceCommand(double,double,double,double)), m_worker, SLOT(updateJointSpaceCommand(double,double,double,double))); connect(this, SIGNAL(updateConfigSpaceCommand(double,double,double,double)), m_worker, SLOT(updateConfigSpaceCommand(double,double,double,double))); connect(this, SIGNAL(updateTaskSpaceCommand(double,double,double,double,bool)), m_worker, SLOT(updateTaskSpaceCommand(double,double,double,double,bool))); // control cycle signals connect(this, SIGNAL(startControlCycle()), m_worker, SLOT(startControlCycle())); connect(this, SIGNAL(stopControlCycle()), m_worker, SLOT(stopControlCycle())); // reset BB connect(this, SIGNAL(tellWorkerToResetBB()), m_worker, SLOT(resetBB())); // Gains Widget connect(gainWidget, SIGNAL(closeGainsWindow()), this, SLOT(on_adjustGainsButton_clicked())); connect(gainWidget, SIGNAL(setGains(GainsPYRT)), m_worker, SLOT(setGains(GainsPYRT))); connect(gainWidget, SIGNAL(setLimits(ConvergenceLimits)), m_worker, SLOT(setLimits(ConvergenceLimits))); // Resp Model Widget connect(m_respModelWidget, SIGNAL(closeRespModelWindow()), this, SLOT(on_respModelButton_clicked())); connect(m_respModelWidget, SIGNAL(initializeRespModel()), m_worker, SLOT(initializeRespModel())); connect(m_respModelWidget, SIGNAL(re_initializeRespModel()), m_worker, SLOT(re_initializeRespModel())); connect(m_respModelWidget, SIGNAL(stopRespModel()), m_worker, SLOT(stopRespModel())); connect(m_respModelWidget, SIGNAL(newFutureSamplesValue(int)), m_worker, SLOT(updateFutureSamples(int))); // connect(m_worker, SIGNAL(sendDataToRespModelWidget(int,bool,bool,double,EigenVectorFiltered,EigenVectorFiltered,EigenVectorFiltered)), // m_respModelWidget, SLOT(receiveDataFromRespModel(int,bool,bool,double,EigenVectorFiltered,EigenVectorFiltered,EigenVectorFiltered))); connect(m_worker, SIGNAL(sendDataToRespModelWidget(int,bool,bool,double)), m_respModelWidget, SLOT(receiveDataFromRespModel(int,bool,bool,double))); connect(&(m_worker->m_respModel), SIGNAL(sendToPlotBird4(unsigned int, double, double)), m_respModelWidget, SLOT(plotBird4(unsigned int,double,double))); connect(m_respModelWidget, SIGNAL(changePlotFocus(int)), &(m_worker->m_respModel), SLOT(setPlotFocus(int))); // Sweep connect(this, SIGNAL(workerStartSweep(uint,double,double,qint64)), m_worker, SLOT(startSweep(uint,double,double,qint64))); connect(this, SIGNAL(workerAbortSweep()), m_worker, SLOT(abortSweep())); // Initalize gains and limits to defaults gainWidget->on_setGainsButton_clicked(); gainWidget->on_setLimitsButton_clicked(); // Mode Flags connect(this, SIGNAL(updateModeFlags(ModeFlags)), m_worker, SLOT(setModeFlags(ModeFlags))); // US angle connect(this, SIGNAL(updateUSangle(double)), m_worker, SLOT(setUSangle(double))); ui->jointSpaceGroupBox->setChecked(false); ui->configSpaceGroupBox->setChecked(false); // trajectory m_keepDriving = false; m_currTrajIdx = 0; m_ctr = 0; connect(m_worker, SIGNAL(reportCurrentXYZPSI(XYZPSI)), this, SLOT(receiveCurrentXYZPSI(XYZPSI))); } ControllerWidget::~ControllerWidget() { m_thread.quit(); m_thread.wait(); qDebug() << "Controller thread quit."; gainWidget->close(); //m_respModelWidget->close(); emit m_respModelWidget->closeRespModelWindow(); delete gainWidget; delete m_respModelWidget; delete ui; } void ControllerWidget::workerStatusChanged(int status) { switch(status) { case CONTROLLER_INITIALIZED: ui->controllerToggleButton->setEnabled(true); ui->statusLineEdit->setText("Initialized."); break; case CONTROLLER_LOOP_STARTED: ui->controllerToggleButton->setText( QStringLiteral("Stop Controller") ); ui->controllerToggleButton->setEnabled(true); ui->statusLineEdit->setText("Running."); break; case CONTROLLER_LOOP_STOPPED: ui->controllerToggleButton->setText( QStringLiteral("Start Controller") ); ui->controllerToggleButton->setEnabled(true); ui->statusLineEdit->setText("Stopped."); break; case CONTROLLER_EPOCH_SET: ui->statusTextEdit->appendPlainText("Epoch set."); break; case CONTROLLER_EPOCH_SET_FAILED: ui->statusTextEdit->appendPlainText("Epoch set failed!"); break; case CONTROLLER_RESET: ui->statusTextEdit->appendPlainText("Controller reset."); break; case CONTROLLER_RESET_FAILED: ui->statusTextEdit->appendPlainText("Controller reset failed!"); break; default: ui->statusTextEdit->appendPlainText("Unknown state!"); break; } } void ControllerWidget::receiveMsgFromWorker(QString msg, int destination) { if(destination == 0) { ui->statusTextEdit->clear(); ui->statusTextEdit->appendPlainText(msg); } else { ui->statusLineEdit->setText(msg); } } void ControllerWidget::on_testButton_clicked() { qDebug() << QTime::currentTime() << "Widget Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId()); emit tellWorkerToPrintThreadID(); } void ControllerWidget::on_taskSpaceGroupBox_toggled(bool arg1) { if(arg1 && ui->configSpaceGroupBox->isChecked()) ui->configSpaceGroupBox->setChecked(false); if(arg1 && ui->jointSpaceGroupBox->isChecked()) ui->jointSpaceGroupBox->setChecked(false); } void ControllerWidget::on_configSpaceGroupBox_toggled(bool arg1) { if(arg1 && ui->taskSpaceGroupBox->isChecked()) ui->taskSpaceGroupBox->setChecked(false); if(arg1 && ui->jointSpaceGroupBox->isChecked()) ui->jointSpaceGroupBox->setChecked(false); } void ControllerWidget::on_jointSpaceGroupBox_toggled(bool arg1) { if(arg1 && ui->configSpaceGroupBox->isChecked()) ui->configSpaceGroupBox->setChecked(false); if(arg1 && ui->taskSpaceGroupBox->isChecked()) ui->taskSpaceGroupBox->setChecked(false); } void ControllerWidget::on_updateJointSpaceButton_clicked() { double pitch = ui->pitchSpinbox->value() * piOverDeg180; double yaw = ui->yawSpinbox->value() * piOverDeg180; double roll = ui->rollSpinbox->value() * piOverDeg180; double trans = ui->transSpinbox->value(); ui->statusTextEdit->appendPlainText(QString("[%5] Joint Space Command: %1 %2 %3 %4") .arg(pitch) .arg(yaw) .arg(roll) .arg(trans) .arg(QTime::currentTime().toString("HH:mm:ss"))); emit updateJointSpaceCommand(pitch, yaw, roll, trans); } void ControllerWidget::on_updateConfigSpaceButton_clicked() { double alpha = ui->alphaSpinbox->value() * piOverDeg180; double theta = ui->thetaSpinbox->value() * piOverDeg180; double gamma = ui->gammaSpinbox->value() * piOverDeg180; double d = ui->dSpinbox->value(); ui->statusTextEdit->appendPlainText(QString("[%5] Config Space Command: %1 %2 %3 %4") .arg(alpha) .arg(theta) .arg(gamma) .arg(d) .arg(QTime::currentTime().toString("HH:mm:ss"))); emit updateConfigSpaceCommand(alpha, theta, gamma, d); } void ControllerWidget::on_updateTaskSpaceButton_clicked() { double x = ui->xSpinbox->value(); double y = ui->ySpinbox->value(); double z = ui->zSpinbox->value(); double delPsi = ui->delPsiSpinbox->value() * piOverDeg180; bool isAbsolute = ui->absoluteRadiobutton->isChecked(); ui->statusTextEdit->appendPlainText(QString("[%6] Task Space Command: %1 %2 %3 %4 %5") .arg(x) .arg(y) .arg(z) .arg(delPsi) .arg(isAbsolute ? "Abs" : "Rel") // ? : ternary operator .arg(QTime::currentTime().toString("HH:mm:ss"))); emit updateTaskSpaceCommand(x, y, z, delPsi, isAbsolute); } void ControllerWidget::on_controllerToggleButton_clicked() { ui->controllerToggleButton->setEnabled(false); // disable button if(m_worker->isControlling()) { // TODO: this should stop LabJack collection emit stopControlCycle(); } else { // TODO: this should trigger LabJack collection emit startControlCycle(); } } void ControllerWidget::on_resetBB_Button_clicked() { emit tellWorkerToResetBB(); } void ControllerWidget::on_adjustGainsButton_clicked() { if(gainWidget->isHidden()) { ui->adjustGainsButton->setText("Hide Gains"); gainWidget->show(); gainWidget->raise(); } else { ui->adjustGainsButton->setText("Adjust Gains"); //gainWidget->hide(); gainWidget->close(); } } void ControllerWidget::on_relativeRadiobutton_clicked() { ui->xSpinbox->setValue(0.0); ui->ySpinbox->setValue(0.0); ui->zSpinbox->setValue(0.0); ui->delPsiSpinbox->setValue(0.0); } void ControllerWidget::on_absoluteRadiobutton_clicked() { ui->xSpinbox->setValue(0.0); ui->ySpinbox->setValue(0.0); ui->zSpinbox->setValue(70.0); ui->delPsiSpinbox->setValue(0.0); } void ControllerWidget::on_updateFlagsButton_clicked() { ModeFlags flags; // int coordFrame; // int tethered; // int instTrackState; // int instTrackMode; // int EKFstate; // int inVivoMode; if(ui->mobileRadioButton->isChecked()) flags.coordFrame = COORD_FRAME_MOBILE; else if(ui->worldRadioButton->isChecked()) flags.coordFrame = COORD_FRAME_WORLD; else{ qDebug() << "coordFrame: State not recognized!"; return; } if(ui->relativeModeRadioButton->isChecked()) flags.tethered = MODE_RELATIVE; else if(ui->tetheredModeRadioButton->isChecked()) flags.tethered = MODE_TETHETERED; else{ qDebug() << "tethered: State not recognized!"; return; } if(ui->ITonRadioButton->isChecked()) flags.instTrackState = INST_TRACK_ON; else if(ui->IToffRadioButton->isChecked()) flags.instTrackState = INST_TRACK_OFF; else{ qDebug() << "instTrackState: State not recognized!"; return; } if(ui->imagerRadioButton->isChecked()) flags.instTrackMode = INST_TRACK_IMAGER; else if(ui->positionRadioButton->isChecked()) flags.instTrackMode = INST_TRACK_POSITION; else{ qDebug() << "instTrackMode: State not recognized!"; return; } if(ui->EKFonRadioButton->isChecked()) flags.EKFstate = EKF_ON; else if(ui->EKFoffRadioButton->isChecked()) flags.EKFstate = EKF_OFF; else{ qDebug() << "EKFstate: State not recognized!"; return; } if(ui->InVivoOnRadioButton->isChecked()) flags.inVivoMode = IN_VIVO_ON; else if(ui->InVivoOffRadioButton->isChecked()) flags.inVivoMode = IN_VIVO_OFF; else{ qDebug() << "inVivoMode: State not recognized!"; return; } emit updateModeFlags(flags); } void ControllerWidget::on_setUSangleButton_clicked() { double usAngle = ui->usAngleSpinBox->value(); emit updateUSangle(usAngle); } void ControllerWidget::on_respModelButton_clicked() { if(m_respModelWidget->isHidden()) { ui->respModelButton->setText("Close RespModel Win"); m_respModelWidget->show(); m_respModelWidget->raise(); } else { ui->respModelButton->setText("Respiration Model"); m_respModelWidget->close(); } } void ControllerWidget::receiveCurrentXYZPSI(XYZPSI currXYZPSI) { m_currXYZPSI = currXYZPSI; if( (m_ctr % 5) == 0 ) { ui->currXspinbox->setValue(currXYZPSI.x); ui->currYspinbox->setValue(currXYZPSI.y); ui->currZspinbox->setValue(currXYZPSI.z); ui->currDelPsiSpinbox->setValue(currXYZPSI.psi); } m_ctr++; } void ControllerWidget::on_trajOpenFileButton_clicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open CSV File"), "../ICEbot_QT_v1/LoggedData", tr("CSV File (*.csv)")); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << file.errorString(); return; } QTextStream in(&file); m_XYZPSIs.clear(); while (!in.atEnd()) { QString line = in.readLine(); QStringList split = line.split(','); // files are generated using dlmwrite in MATLAB if(split.size() == 4) { XYZPSI xyzpsi; xyzpsi.x = split[0].toDouble(); xyzpsi.y = split[1].toDouble(); xyzpsi.z = split[2].toDouble(); xyzpsi.psi = split[3].toDouble() * piOverDeg180; // convert to radians double signedPI = boost::math::copysign(pi, xyzpsi.psi); xyzpsi.psi = fmod(xyzpsi.psi + signedPI,(2*pi)) - signedPI; m_XYZPSIs.push_back(xyzpsi); } else { qDebug() << "Error reading CSV - number of elements in line is not equal to 4!"; break; } } qDebug() << "Read" << m_XYZPSIs.size() << "setpoints from trajectory file."; if(m_XYZPSIs.size() > 0){ ui->trajDriveButton->setEnabled(true); ui->trajStepLineEdit->setText(QString("%1 points loaded.").arg(m_XYZPSIs.size())); } else{ ui->trajDriveButton->setEnabled(false); ui->trajStepLineEdit->setText("Error reading file."); } } void ControllerWidget::on_trajDriveButton_clicked() { if(m_keepDriving) { m_keepDriving = false; ui->trajDriveButton->setText("Drive"); // stop timer m_trajTimer->stop(); disconnect(m_trajTimer, SIGNAL(timeout()), 0, 0); delete m_trajTimer; } else { m_keepDriving = true; ui->trajDriveButton->setText("Stop"); m_currTrajIdx = 0; ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_XYZPSIs.size())); XYZPSI targetXYZPSI = m_XYZPSIs[m_currTrajIdx]; // send to worker emit updateTaskSpaceCommand(targetXYZPSI.x, targetXYZPSI.y, targetXYZPSI.z, targetXYZPSI.psi, true); // update spinbox in UI ui->xSpinbox->setValue(targetXYZPSI.x); ui->ySpinbox->setValue(targetXYZPSI.y); ui->zSpinbox->setValue(targetXYZPSI.z); ui->delPsiSpinbox->setValue(targetXYZPSI.psi * deg180overPi); // start timer m_trajTimer = new QTimer(this); connect(m_trajTimer, SIGNAL(timeout()), this, SLOT(driveTrajectory())); m_trajTimer->start(10); } } void ControllerWidget::driveTrajectory() { XYZPSI targetXYZPSI = m_XYZPSIs[m_currTrajIdx]; if( (abs(m_currXYZPSI.x - targetXYZPSI.x) < 0.75) && (abs(m_currXYZPSI.y - targetXYZPSI.y) < 0.75) && (abs(m_currXYZPSI.z - targetXYZPSI.z) < 0.75) && m_keepDriving) { m_currTrajIdx++; ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_XYZPSIs.size())); if(m_currTrajIdx < m_XYZPSIs.size()) { // get next traget targetXYZPSI = m_XYZPSIs[m_currTrajIdx]; // send to worker emit updateTaskSpaceCommand(targetXYZPSI.x, targetXYZPSI.y, targetXYZPSI.z, targetXYZPSI.psi, true); // update spinbox in UI ui->xSpinbox->setValue(targetXYZPSI.x); ui->ySpinbox->setValue(targetXYZPSI.y); ui->zSpinbox->setValue(targetXYZPSI.z); ui->delPsiSpinbox->setValue(targetXYZPSI.psi * deg180overPi); qDebug() << "Drive to" << targetXYZPSI.x << targetXYZPSI.y << targetXYZPSI.z << targetXYZPSI.psi; } else { m_keepDriving = false; ui->trajDriveButton->setText("Drive"); } } } void ControllerWidget::on_sweepButton_clicked() { unsigned int nSteps = ui->numSweepsSpinBox->value(); double stepAngle = ui->sweepStepDblSpinBox->value() * piOverDeg180; double convLimit = ui->sweepThreshDblSpinBox->value() * piOverDeg180; qint64 imgDuration = ui->acqTimeMsSpinBox->value(); emit workerStartSweep(nSteps, stepAngle, convLimit, imgDuration); } void ControllerWidget::on_abortSweepButton_clicked() { emit workerAbortSweep(); }
17,623
C++
32.762452
147
0.629915
adegirmenci/HBL-ICEbot/ControllerWidget/respmodelwidget.h
#ifndef RESPMODELWIDGET_H #define RESPMODELWIDGET_H #include <QWidget> #include <QCloseEvent> #include "filtfilt.h" #include "../icebot_definitions.h" namespace Ui { class respModelWidget; } class respModelWidget : public QWidget { Q_OBJECT public: explicit respModelWidget(QWidget *parent = 0); ~respModelWidget(); signals: void closeRespModelWindow(); void initializeRespModel(); void re_initializeRespModel(); void stopRespModel(); void newFutureSamplesValue(int n); void changePlotFocus(int idx); private slots: void on_closeButton_clicked(); void on_initializeButton_clicked(); void on_futureSamplesSpinBox_valueChanged(int arg1); void on_reInitButton_clicked(); void receiveDataFromRespModel(int numSamples, bool isTrained, bool inVivoMode, double omega0);//, //EigenVectorFiltered Bird4_filtered, //EigenVectorFiltered Bird4_filtered_new, //EigenVectorFiltered breathSignalFromModel); void plotBird4(unsigned int plotID, double time, double value); void on_stopButton_clicked(); void on_bird4RadioButton_clicked(); void on_CTradioButton_clicked(); private: Ui::respModelWidget *ui; void closeEvent(QCloseEvent *event); double m_lastPlotKey; // to limit update rate of plot }; #endif // RESPMODELWIDGET_H
1,530
C
20.871428
80
0.630719
adegirmenci/HBL-ICEbot/ControllerWidget/cyclicmodel.h
#ifndef CYCLICMODEL_H #define CYCLICMODEL_H #include <QObject> #include <vector> #include <algorithm> #include <iostream> #include <memory> #include <limits> #include <Eigen/Dense> #include <Eigen/SVD> #include <Eigen/Geometry> #include <QString> #include <QDir> #include <QFile> #include <QDataStream> #include <QTextStream> #include <QDebug> #include <QElapsedTimer> #include <QtConcurrent/QtConcurrentRun> #include <QFuture> #include <QDateTime> #include "filtfilt.h" #include "../icebot_definitions.h" class CyclicModel : public QObject { Q_OBJECT public: explicit CyclicModel(QObject *parent = 0); ~CyclicModel(); // void operator = (const CyclicModel &Other); // add training data void addTrainingObservation(const EigenAffineTransform3d &T_BB_CT_curTipPos, const EigenAffineTransform3d &T_BB_targetPos, const EigenAffineTransform3d &T_Box_BBmobile, const EigenAffineTransform3d &T_BB_Box, const EigenAffineTransform3d &T_Bird4, const double sampleTime); // reset model void resetModel(); // get initial model void trainModel(); // add respiration data void addObservation(const EigenAffineTransform3d &T_Bird4, const double sampleTime); // update the period void updatePeriod(const double period); void updateNfutureSamples(int n) { m_nFutureSamples = n; } // Accessors const size_t getNumSamples() { return m_numSamples; } const bool isTrained() { return m_isTrained; } const bool isInVivoMode() { return m_isInVivo; } const double getOmega() { return m_omega0; } void setInVivo(const bool isInVivo); EigenVectorFiltered get_Bird4_filtered() { return m_Bird4_filtered; } EigenVectorFiltered get_Bird4_filtered_new() { return m_Bird4_filtered_new; } EigenVectorFiltered get_breathSignalFromModel() { return m_breathSignalFromModel; } EigenVector7d getT_BBfixed_CT_des() { return m_BBfixed_CT_des; } EigenVector7d getT_BBfixed_CTtraj_future_des() { return m_BBfixed_CTtraj_future_des; } EigenVector7d getT_BBfixed_BB_des() { return m_BBfixed_BB_des; } // testing function - external data load and save void loadData(QString filename, std::vector<double> &X); void load4x4Data(QString filename, EigenStdVecVector7d &X); void load4x4Data(QString filename, std::vector<std::vector<double>> &X); void saveFilteredData(QString filename, const std::vector<double> &Y); void saveFilteredData(QString filename, const EigenVectorFiltered &Y); void save4x4FilteredData(QString filename, const EigenStdVecVector7d &Y); void save4x4FilteredData(QString filename, const EigenMatrixFiltered &Y); void testLPF(); public slots: void setPlotFocus(int idx); signals: void sendToPlotBird4(unsigned int plotID, double time, double val); private: void retrainModel(); void filterTrainingData(); void filterNewObservations(); double peakDetector(const bool runForInit); void peakDetectorForBreathModel(); double getPrediction(const double timeShift, const EigenVectorPolar &x_polar, const EigenVectorRectangular &x_rect); void getPrediction7Axis(const double timeShift, const EigenMatrixPolar &x_polar, const EigenMatrixRectangular &x_rect, EigenVector7d &X_des, const double phase); void cycle_recalculate(const EigenMatrixFiltered &z_init, EigenMatrixRectangular &x_rect, EigenMatrixPolar &x_polar, const double omega0); void cycle_recalculate(const EigenVectorFiltered &z_init, EigenVectorRectangular &x_rect, EigenVectorPolar &x_polar, const double omega0); Eigen::MatrixXd cycle_recalculate_concurrentM(const EigenMatrixFiltered &z_init, const double omega0, const std::vector<double> &timeData); Eigen::VectorXd cycle_recalculate_concurrentV(const EigenVectorFiltered &z_init, const double omega0, const std::vector<double> &timeData); // data members // Low Pass Filter filtfilt m_LowPassFilter; // UNFILTERED DATA // x,y,z,xaxis,yaxis,zaxis,angle - only needed for training // TODO : how does replacing EigenStdVecVector7d with EigenMatrixFiltered affect performance? EigenStdVecVector7d m_BBfixed_CT, // this stores all of the incoming CT points m_BBfixed_Instr, // this stores all of the incoming instr_x points m_BBfixed_BB; // this stores all of the incoming BB points // for the chest tracker, we only the need the x (benchtop) or -z (in vivo) axis of this std::vector<double> m_Bird4, // this remains constant after initialization m_Bird4_new; // most recent chest tracker data // FILTERED DATA // 7 components: x,y,z,xaxis,yaxis,zaxis,angle EigenMatrixFiltered m_BBfixed_CT_filtered, // this remains constant after initialization m_BBfixed_BB_filtered; // this remains constant after initialization // for the chest tracker, we only the need the x (benchtop) or -z (in vivo) axis of this EigenVectorFiltered m_Bird4_filtered, // this remains constant after initialization m_Bird4_filtered_new, // most recent filtered chest tracker data m_breathSignalFromModel; // ***CURRENT*** RECTANGULAR COMPONENTS EigenMatrixRectangular m_BBfixed_CT_rectangular, // 7 components: x,y,z,xaxis,yaxis,zaxis,angle m_BBfixed_BB_rectangular; // 7 components: x,y,z,xaxis,yaxis,zaxis,angle EigenVectorRectangular m_Bird4_rectangular; // 1 component : x (benchtop) or -z (in vivo) // ***CURRENT*** POLAR COMPONENTS EigenMatrixPolar m_BBfixed_CT_polar, // 7 components: x,y,z,xaxis,yaxis,zaxis,angle m_BBfixed_BB_polar; // 7 components: x,y,z,xaxis,yaxis,zaxis,angle EigenVectorPolar m_Bird4_polar; // 1 component : x (benchtop) or -z (in vivo) // MODEL-BASED ESTIMATES OF CURRENT AND FUTURE POSITIONS EigenVector7d m_BBfixed_CT_des, m_BBfixed_CTtraj_future_des, m_BBfixed_BB_des; // TIME DATA std::vector<double> m_timeData_init, // stores the time vector for the model initialization observations m_timeData_new; // stores time for the most recent observations // PEAK DATA - MEAN OF THE LEFT AND RIGHT std::vector<double> m_respPeakMean, m_breathSignalPeakMean; size_t m_nFutureSamples; // how much into the future should we look? double m_omega0; // frequency double m_omega0_init; std::vector<double> m_periods; size_t m_numSamples; // number of observations added IN TOTAL bool m_isTrained; // is the model trained qint64 m_lastTrainingTimestamp; // when last training was performed bool m_isInVivo; // are we in IN VIVO mode int m_plotFocus; // concurrent execution QFuture<Eigen::MatrixXd> mConcurrent1, mConcurrent2; QFuture<Eigen::VectorXd> mConcurrent3; Eigen::MatrixXd m_BBfixed_CT_polarRect; Eigen::MatrixXd m_BBfixed_BB_polarRect; Eigen::VectorXd m_Bird4_polarRect; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; #endif // CYCLICMODEL_H
7,516
C
38.563158
143
0.669505
adegirmenci/HBL-ICEbot/ControllerWidget/filtfilt.cpp
#include "filtfilt.h" filtfilt::filtfilt() { m_A = {1}; // From MATLAB : m_B = fir1(50,(100/60/2)/(150/2),'low'); // order 50, 100 bpm, 150 Hz sampling // m_B = {0.00264726249703924, 0.00279642405272151, 0.00319013679531822, 0.00382941384359819, // 0.00471069197708524, 0.00582582662708399, 0.00716217671948781, 0.00870277868575645, // 0.0104266071117473, 0.0123089176854006, 0.0143216663725929, 0.0164339971333124, // 0.0186127890229487, 0.0208232522381201, 0.0230295615915197, 0.0251955150597567, // 0.0272852044611377, 0.0292636850004373, 0.0310976303728649, 0.0327559603516814, // 0.0342104282892947, 0.0354361567303369, 0.0364121103516330, 0.0371214966872074, // 0.0375520865406890, 0.0376964476024575, 0.0375520865406890, 0.0371214966872074, // 0.0364121103516330, 0.0354361567303369, 0.0342104282892947, 0.0327559603516814, // 0.0310976303728649, 0.0292636850004373, 0.0272852044611377, 0.0251955150597567, // 0.0230295615915197, 0.0208232522381201, 0.0186127890229487, 0.0164339971333124, // 0.0143216663725929, 0.0123089176854006, 0.0104266071117473, 0.00870277868575645, // 0.00716217671948781, 0.00582582662708399, 0.00471069197708524, 0.00382941384359819, // 0.00319013679531822, 0.00279642405272151, 0.00264726249703924}; size_t filterOrder = FILTER_ORDER + 1; // must be odd! double deltaT = SAMPLE_DELTA_TIME; double samplingFreq = 1.0/deltaT; double band = (HEART_RATE/60./2.)/(samplingFreq/2.); m_zzi = std::allocate_shared< Eigen::MatrixXd >( Eigen::aligned_allocator<Eigen::MatrixXd>() ); m_B = FIR_LPF_LeastSquares(filterOrder, band); // for(auto x : m_B) // std::cout << x << std::endl; updateFilterParameters(); } filtfilt::~filtfilt() { } void filtfilt::run(const std::vector<double> &X, std::vector<double> &Y) { int len = X.size(); // length of input if (len <= m_nfact) { std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl; return; } std::vector<double> leftpad = subvector_reverse(X, m_nfact, 1); double _2x0 = 2 * X[0]; std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](double val) {return _2x0 - val; }); std::vector<double> rightpad = subvector_reverse(X, len - 2, len - m_nfact - 1); double _2xl = 2 * X[len-1]; std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](double val) {return _2xl - val; }); double y0; std::vector<double> signal1, signal2, zi; signal1.reserve(leftpad.size() + X.size() + rightpad.size()); append_vector(signal1, leftpad); append_vector(signal1, X); append_vector(signal1, rightpad); zi.resize(m_zzi->size()); // Do the forward and backward filtering y0 = signal1[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; }); filter(signal1, signal2, zi); std::reverse(signal2.begin(), signal2.end()); y0 = signal2[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; }); filter(signal2, signal1, zi); Y = subvector_reverse(signal1, signal1.size() - m_nfact - 1, m_nfact); } void filtfilt::run(const std::vector<double> &X, EigenVectorFiltered &Y) { int len = X.size(); // length of input if (len <= m_nfact) { std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl; return; } std::vector<double> leftpad = subvector_reverse(X, m_nfact, 1); double _2x0 = 2 * X[0]; std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](double val) {return _2x0 - val; }); std::vector<double> rightpad = subvector_reverse(X, len - 2, len - m_nfact - 1); double _2xl = 2 * X[len-1]; std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](double val) {return _2xl - val; }); double y0; std::vector<double> signal1, signal2, zi; signal1.reserve(leftpad.size() + X.size() + rightpad.size()); append_vector(signal1, leftpad); append_vector(signal1, X); append_vector(signal1, rightpad); zi.resize(m_zzi->size()); // Do the forward and backward filtering y0 = signal1[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; }); filter(signal1, signal2, zi); std::reverse(signal2.begin(), signal2.end()); y0 = signal2[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; }); filter(signal2, signal1, zi); subvector_reverseEig(signal1, signal1.size() - m_nfact - 1 - EDGE_EFFECT, m_nfact + EDGE_EFFECT, Y); } void filtfilt::run(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y) { int len = X.size(); // length of input if (len <= m_nfact) { std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl; return; } EigenStdVecVector7d leftpad = subvector_reverseEig(X, m_nfact, 1); EigenVector7d _2x0 = X[0] * 2.0; std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](EigenVector7d val) {return _2x0 - val; }); EigenStdVecVector7d rightpad = subvector_reverseEig(X, len - 2, len - m_nfact - 1); EigenVector7d _2xl = X[len-1] * 2.0; std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](EigenVector7d val) {return _2xl - val; }); EigenVector7d y0; EigenStdVecVector7d signal1, signal2, zi; // signal1.reserve(leftpad.size() + X.size() + rightpad.size()); append_vector(signal1, leftpad); append_vector(signal1, X); append_vector(signal1, rightpad); zi.resize(m_zzi->size()); // Do the forward and backward filtering y0 = signal1[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; }); filter(signal1, signal2, zi); std::reverse(signal2.begin(), signal2.end()); y0 = signal2[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; }); filter(signal2, signal1, zi); Y = subvector_reverseEig(signal1, signal1.size() - m_nfact - 1, m_nfact); } void filtfilt::run(const EigenStdVecVector7d &X, EigenMatrixFiltered &Y) { int len = X.size(); // length of input , should be equal to N_INPUTS if (len <= m_nfact) { std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl; return; } EigenStdVecVector7d leftpad = subvector_reverseEig(X, m_nfact, 1); EigenVector7d _2x0 = X[0] * 2.0; std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](EigenVector7d val) {return _2x0 - val; }); EigenStdVecVector7d rightpad = subvector_reverseEig(X, len - 2, len - m_nfact - 1); EigenVector7d _2xl = X[len-1] * 2.0; std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](EigenVector7d val) {return _2xl - val; }); EigenVector7d y0; EigenStdVecVector7d signal1, signal2, zi; // signal1.reserve(leftpad.size() + X.size() + rightpad.size()); append_vector(signal1, leftpad); append_vector(signal1, X); append_vector(signal1, rightpad); zi.resize(m_zzi->size()); // Do the forward and backward filtering y0 = signal1[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; }); filter(signal1, signal2, zi); std::reverse(signal2.begin(), signal2.end()); y0 = signal2[0]; std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; }); filter(signal2, signal1, zi); subvector_reverseEig(signal1, signal1.size() - m_nfact - EDGE_EFFECT - 1, m_nfact + EDGE_EFFECT, Y); } void filtfilt::filter(const std::vector<double> &X, std::vector<double> &Y, std::vector<double> &Zi) { size_t input_size = X.size(); //size_t filter_order = std::max(m_A.size(), m_B.size()); size_t filter_order = m_nfilt; // m_B.resize(filter_order, 0); // m_A.resize(filter_order, 0); Zi.resize(filter_order, 0); Y.resize(input_size); const double *x = &X[0]; const double *b = &m_B[0]; const double *a = &m_A[0]; double *z = &Zi[0]; double *y = &Y[0]; // QElapsedTimer elTimer; // elTimer.start(); for (size_t i = 0; i < input_size; ++i) { size_t order = filter_order - 1; while (order) { if (i >= order) { z[order - 1] = b[order] * x[i - order] - a[order] * y[i - order] + z[order]; } --order; } y[i] = b[0] * x[i] + z[0]; } Zi.resize(filter_order - 1); // qint64 elNsec = elTimer.nsecsElapsed(); // std::cout << "\nNsec elapsed:" << elNsec << std::endl; } void filtfilt::filter(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y, EigenStdVecVector7d &Zi) { size_t input_size = X.size(); //size_t filter_order = std::max(m_A.size(), m_B.size()); size_t filter_order = m_nfilt; // m_B.resize(filter_order, 0); // m_A.resize(filter_order, 0); Zi.resize(filter_order, EigenVector7d::Zero()); Y.resize(input_size); // const EigenVector7d *x = &X[0]; const double *b = &m_B[0]; const double *a = &m_A[0]; // EigenVector7d *z = &Zi[0]; // EigenVector7d *y = &Y[0]; // QElapsedTimer elTimer; // elTimer.start(); for (size_t i = 0; i < input_size; ++i) { size_t order = filter_order - 1; // if(i < order) // order = i; // may lead to tiny tiny speedup while (order) { if (i >= order) { Zi[order - 1] = (X[i - order] * b[order] - Y[i - order] * a[order] + Zi[order]).eval(); } --order; } Y[i] = X[i] * b[0] + Zi[0]; } Zi.resize(filter_order - 1); // qint64 elNsec = elTimer.nsecsElapsed(); // std::cout << "\nNsec elapsed:" << elNsec << std::endl; } void filtfilt::setFilterCoefficients(const std::vector<double> &B, const std::vector<double> &A) { m_A = A; m_B = B; updateFilterParameters(); } void filtfilt::updateFilterParameters() { m_na = m_A.size(); m_nb = m_B.size(); m_nfilt = (m_nb > m_na) ? m_nb : m_na; m_nfact = 3 * (m_nfilt - 1); // length of edge transients // set up filter's initial conditions to remove DC offset problems at the // beginning and end of the sequence m_B.resize(m_nfilt, 0); m_A.resize(m_nfilt, 0); m_rows.clear(); m_cols.clear(); //rows = [1:nfilt-1 2:nfilt-1 1:nfilt-2]; add_index_range(m_rows, 0, m_nfilt - 2); if (m_nfilt > 2) { add_index_range(m_rows, 1, m_nfilt - 2); add_index_range(m_rows, 0, m_nfilt - 3); } //cols = [ones(1,nfilt-1) 2:nfilt-1 2:nfilt-1]; add_index_const(m_cols, 0, m_nfilt - 1); if (m_nfilt > 2) { add_index_range(m_cols, 1, m_nfilt - 2); add_index_range(m_cols, 1, m_nfilt - 2); } // data = [1+a(2) a(3:nfilt) ones(1,nfilt-2) -ones(1,nfilt-2)]; auto klen = m_rows.size(); m_data.clear(); m_data.resize(klen); m_data[0] = 1 + m_A[1]; int j = 1; if (m_nfilt > 2) { for (int i = 2; i < m_nfilt; i++) m_data[j++] = m_A[i]; for (int i = 0; i < m_nfilt - 2; i++) m_data[j++] = 1.0; for (int i = 0; i < m_nfilt - 2; i++) m_data[j++] = -1.0; } // Calculate initial conditions Eigen::MatrixXd sp = Eigen::MatrixXd::Zero(max_val(m_rows) + 1, max_val(m_cols) + 1); for (size_t k = 0; k < klen; ++k) { sp(m_rows[k], m_cols[k]) = m_data[k]; } auto bb = Eigen::VectorXd::Map(m_B.data(), m_B.size()); auto aa = Eigen::VectorXd::Map(m_A.data(), m_A.size()); (*m_zzi) = (sp.inverse() * (bb.segment(1, m_nfilt - 1) - (bb(0) * aa.segment(1, m_nfilt - 1)))); if (m_A.empty()) { std::cerr << "The feedback filter coefficients are empty." << std::endl; } if (std::all_of(m_A.begin(), m_A.end(), [](double coef){ return coef == 0; })) { std::cerr << "At least one of the feedback filter coefficients has to be non-zero." << std::endl; } if (m_A[0] == 0) { std::cerr << "First feedback coefficient has to be non-zero." << std::endl; } // Normalize feedback coefficients if a[0] != 1; auto a0 = m_A[0]; if (a0 != 1.0) { std::transform(m_A.begin(), m_A.end(), m_A.begin(), [a0](double v) { return v / a0; }); std::transform(m_B.begin(), m_B.end(), m_B.begin(), [a0](double v) { return v / a0; }); } } void filtfilt::add_index_range(std::vector<int> &indices, int beg, int end, int inc) { for (int i = beg; i <= end; i += inc) { indices.push_back(i); } } void filtfilt::add_index_const(std::vector<int> &indices, int value, size_t numel) { while (numel--) { indices.push_back(value); } } void filtfilt::append_vector(std::vector<double> &vec, const std::vector<double> &tail) { vec.insert(vec.end(), tail.begin(), tail.end()); } void filtfilt::append_vector(EigenStdVecVector7d &vec, const EigenStdVecVector7d &tail) { vec.insert(vec.end(), tail.begin(), tail.end()); } std::vector<double> filtfilt::subvector_reverse(const std::vector<double> &vec, int idx_end, int idx_start) { std::vector<double> result(&vec[idx_start], &vec[idx_end+1]); std::reverse(result.begin(), result.end()); return result; } EigenStdVecVector7d filtfilt::subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start) { EigenStdVecVector7d result(&vec[idx_start], &vec[idx_end+1]); std::reverse(result.begin(), result.end()); return result; } void filtfilt::subvector_reverseEig(const std::vector<double> &vec, int idx_end, int idx_start, EigenVectorFiltered &Y) { Eigen::Map<const EigenVectorFiltered> temp(&vec[idx_start], idx_end - idx_start + 1); Y = temp.reverse(); } void filtfilt::subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start, EigenMatrixFiltered &Y) { Y = EigenMatrixFiltered::Zero(idx_end - idx_start + 1, 7); for(size_t i = 0; i < (idx_end - idx_start + 1); i++) { Y.row(i) = vec[idx_end - i]; } } // L should be odd std::vector<double> filtfilt::FIR_LPF_LeastSquares(size_t L, const double deltaT) { if(deltaT > 1.0) std::cerr << "deltaT is too large, sample faster!!!" << std::endl; std::vector<double> F = {0.0, deltaT/2.0, deltaT/2.0, 0.5}, dF = {deltaT/2.0, 0.0, 0.5 - deltaT/2.0}, M = {1,1,0,0}, W = {1,1}; // size_t fullBand = 1, constantWeights = 1; size_t N = L; L = (N-1)/2; // k=m=(0:L); // Type-I double b0 = 0.0; std::vector<double> b(L, 0.0); std::vector<size_t> m(L+1), k(L); for(size_t i = 0; i < m.size(); i++) m[i] = i; for(size_t i = 0; i < k.size(); i++) k[i] = m[i+1]; for(size_t s = 0; s < 3; s += 2) { // m=(M(s+1)-M(s))/(F(s+1)-F(s)); % slope // b1=M(s)-m*F(s); % y-intercept //double m_ = (M[s+1] - M[s])/(F[s+1] - F[s]); double b1 = M[s];// - m_*F[s]; //b0 = b0 + (b1*(F(s+1)-F(s)) + m/2*(F(s+1)*F(s+1)-F(s)*F(s)))* abs(W((s+1)/2)^2) ; //b0 += ( b1*(F[s+1]-F[s]) + m_/2.0*(F[s+1]*F[s+1]-F[s]*F[s]) );//* pow(W[(s+1)/2],2); W = 1 anyways b0 += b1*(F[s+1]-F[s]); //b = b+(m/(4*pi*pi)*(cos(2*pi*k*F(s+1))-cos(2*pi*k*F(s)))./(k.*k))... // * abs(W((s+1)/2)^2); //b = b + (F(s+1)*(m*F(s+1)+b1)*sinc(2*k*F(s+1)) ... // - F(s)*(m*F(s)+b1)*sinc(2*k*F(s))) ... // * abs(W((s+1)/2)^2); // sinc(x) = sin(pi*x)/(pi*x); ->> (sin(pi*2.0*k[i]*F[s+1])/(pi*2.0*k[i]*F[s+1])) for(size_t i = 0; i < b.size(); i++) { double sinc_ = boost::math::sinc_pi(pi*2.0*k[i]*F[s+1]); //b[i] += (m_/(4.0*pi*pi)*(cos(2.0*pi*k[i]*F[s+1])-cos(2.0*pi*k[i]*F[s]))/(1.0*k[i]*k[i]));//* pow(W[(s+1)/2],2); //b[i] += (F[s+1]*(m_*F[s+1]+b1)*sinc_ - F[s]*(m_*F[s]+b1)*sinc_);// * pow(W[(s+1)/2],2); b[i] += (F[s+1]*b1*sinc_ - F[s]*b1*sinc_); } } b.insert(b.begin(),b0); // a=(W(1)^2)*4*b; std::vector<double> a(b.size()); for(size_t i = 0; i < a.size(); i++) { //a[i] = 4.0*b[i]; a[i] = 2.0*b[i]; } //a[0] /= 2.0; // h=[a(L+1:-1:2)/2; a(1); a(2:L+1)/2].'; std::vector<double> h;// size N h.insert(h.end(), a.rbegin(), a.rend()); h.insert(h.end(), a.begin()+1, a.end()); // return h; // b = hh.*Wind(:)'; // a = 1; // generate the Hamming window coefficients std::vector<double> Wind = genHammingWindow(N); // reuse b b.clear(); b.resize(N); for(size_t i = 0; i < b.size(); i++) { b[i] = h[i] * Wind[i]; } // scale filter // b = b / sum(b); double sumb = std::accumulate(b.begin(),b.end(),0.0); for(size_t i = 0; i < b.size(); i++) { b[i] /= sumb; } return b; } std::vector<double> filtfilt::genHammingWindow(const size_t L) { std::vector<double> w; if(L % 2 > 0) { // Odd length window size_t half = (L+1)/2; w = calcWindow(half, L); } else { // Even length window size_t half = L/2; w = calcWindow(half, L); } return w; } std::vector<double> filtfilt::calcWindow(size_t m, size_t n) { // x = (0:m-1)'/(n-1); double x = 0.0; std::vector<double> w; w.resize(m); // compute coefficients of the Hamming windows for(size_t i = 0; i < m; i++) { x = i/(n-1.0); // between 0.00 and 0.50 w[i] = 0.54 - 0.46*cos(2*pi*x); } // w = [w; w(end-1:-1:1)]; // make symmetric w.insert(w.end(), w.rbegin()+1, w.rend()); return w; }
18,811
C++
32.592857
126
0.542714
adegirmenci/HBL-ICEbot/HeartRateWidget/heartratewidget.cpp
#include "heartratewidget.h" #include "ui_heartratewidget.h" HeartRateWidget::HeartRateWidget(QWidget *parent) : QWidget(parent), ui(new Ui::HeartRateWidget) { ui->setupUi(this); m_time.resize(VEC_SIZE, 0.0); m_voltage.resize(VEC_SIZE, 0.0); m_HR = 0.0, m_stdHR = 0.0, m_phaseHR = 0.0; minPeakDist = 60./120./2.; minPeakHei = 0.2; m_counter = 0; // Initialize MATLAB DLL ECGgating_initialize(); // qDebug() << "HR Widget Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; } HeartRateWidget::~HeartRateWidget() { // Terminate MATLAB DLL ECGgating_terminate(); delete ui; } void HeartRateWidget::receiveECG(qint64 timeStamp, std::vector<double> data) { // remove first element m_time.erase(m_time.begin()); m_voltage.erase(m_voltage.begin()); // add new reading m_time.push_back((double)timeStamp/1000.); m_voltage.push_back(data[0]); // peak detection ECGgating(&m_voltage[0], &m_time[0], minPeakDist, minPeakHei, ECGpeakVals_data, ECGpeakVals_size, ECGpeakTimes_data, ECGpeakTimes_size, &m_HR, &m_stdHR, &m_phaseHR); m_counter = (m_counter + 1) % 60; if(m_counter == 0) { ui->HRlineEdit->setText(QString::number(m_HR,'f',1)); ui->phaseLineEdit->setText(QString::number(m_phaseHR,'f',3)); } emit reportPhase(timeStamp, m_phaseHR); }
1,425
C++
23.586206
103
0.625263
adegirmenci/HBL-ICEbot/HeartRateWidget/heartratewidget.h
#ifndef HEARTRATEWIDGET_H #define HEARTRATEWIDGET_H #include <QWidget> #include <QTime> #include <QString> #include <QDebug> #include <QThread> #include <cmath> #include <math.h> #include <iostream> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "rt_nonfinite.h" #include "rtwtypes.h" #include "ECGgating_types.h" #include "ECGgating.h" #include "ECGgating_terminate.h" #include "ECGgating_initialize.h" #define VEC_SIZE 3000 // 3000 sample points namespace Ui { class HeartRateWidget; } class HeartRateWidget : public QWidget { Q_OBJECT public: explicit HeartRateWidget(QWidget *parent = 0); ~HeartRateWidget(); signals: void reportPhase(qint64 timeStamp, double phase); public slots: void receiveECG(qint64 timeStamp, std::vector<double> data); private: Ui::HeartRateWidget *ui; std::vector<double> m_time; std::vector<double> m_voltage; double m_HR, m_stdHR, m_phaseHR; double ECGpeakVals_data[6000]; int ECGpeakVals_size[1]; double ECGpeakTimes_data[6000]; int ECGpeakTimes_size[2]; unsigned __int8 m_counter; double minPeakDist; double minPeakHei; }; #endif // HEARTRATEWIDGET_H
1,205
C
17.84375
53
0.700415
adegirmenci/HBL-ICEbot/OmniWidget/omnithread.cpp
#include "omnithread.h" omniThread::omniThread(QObject *parent) : QThread(parent) { // moveToThread(this); m_hUpdateHandle = 0; HDErrorInfo error; /* Initialize the device, must be done before attempting to call any hd functions. */ m_hHD = hdInitDevice(HD_DEFAULT_DEVICE); if (HD_DEVICE_ERROR(error = hdGetError())) { hduPrintError(stderr, &error, "Failed to initialize the device"); //throw exception } m_sphereRadius = 40.0; /* Schedule the main scheduler callback that updates the device state. */ m_hUpdateHandle = hdScheduleAsynchronous(updateDeviceCallback, this, HD_MAX_SCHEDULER_PRIORITY); open(); init(); // updateTimer = new QTimer(); // updateTimer->setInterval(1); // connect(updateTimer, SIGNAL(timeout()), this, SLOT(run())); // updateTimer->start(); } void omniThread::getDevicePosRot(hduVector3Dd &pos, hduVector3Dd &rot) { pos = m_currentData.m_devicePosition; //rot = m_currentData.m_deviceRotation; rot = m_currentData.m_stylusHeading; } void omniThread::open() { HDErrorInfo error; /* Start the servo loop scheduler. */ hdEnable(HD_FORCE_OUTPUT); hdStartScheduler(); if (HD_DEVICE_ERROR(error = hdGetError())) { hduPrintError(stderr, &error, "Failed to start the scheduler"); //throw exception } if(fopen_s(&pFile, "omniPositionRec.txt","w") == 0) fprintf(stdout, "Opened log file.\n"); } void omniThread::init() { /* Perform a synchronous call to copy the most current device state. */ hdScheduleSynchronous(copyDeviceDataCallback, this, HD_MIN_SCHEDULER_PRIORITY); memcpy(&m_prevData, &m_currentData, sizeof(DeviceData)); } void omniThread::close() { /* For cleanup, unschedule callbacks and stop the servo loop. */ hdStopScheduler(); hdUnschedule(m_hUpdateHandle); hdDisableDevice(m_hHD); fclose(pFile); } void omniThread::setSphereRad(double radius) { if((1.0 < radius) && (radius < 80.0)) m_sphereRadius = radius; } void omniThread::run() { // QElapsedTimer elTimer; // elTimer.start(); // qint64 ctr = 0; // qint64 elapsedT = 0; // qint64 avgTime = 0; while(isRunning()) { /* Perform a synchronous call to copy the most current device state. This synchronous scheduler call ensures that the device state is obtained in a thread-safe manner. */ hdScheduleSynchronous(copyDeviceDataCallback, this, HD_MIN_SCHEDULER_PRIORITY); // // Filter noise // hduVector3Dd diffPos, diffRot; // for(int i = 0; i < 3; i++) // { // diffPos[i] = fabs(m_currentData.m_devicePosition[i] - m_prevData.m_devicePosition[i]); // diffRot[i] = fabs(m_currentData.m_deviceRotation[i] - m_prevData.m_deviceRotation[i]); // if(diffPos[i] < 0.001) // m_currentData.m_devicePosition[i] = m_prevData.m_devicePosition[i]; // if(diffRot[i] < 0.001) // m_currentData.m_deviceRotation[i] = m_prevData.m_deviceRotation[i]; // } /* If the user depresses the gimbal button, display the current location information. */ if (m_currentData.m_buttonState && !m_prevData.m_buttonState) { /*fprintf(stdout, "Current position: (%g, %g, %g)\n", m_currentData.m_devicePosition[0], m_currentData.m_devicePosition[1], m_currentData.m_devicePosition[2]);*/ //fprintf(stdout, "Roll, pitch, yaw: (%g, %g, %g)\n", roll_, pitch_, yaw_); //fprintf(stdout, "Send A3200 to: (%g, %g, %g)\n", axis01, axis02, axis00); //close gripper //*************** FIX THIS - need to use signals? //ui->outputText->append(QString("Current position: (%1, %2, %3)").arg(ui->xLCD->value()).arg(ui->yLCD->value()).arg(ui->zLCD->value())); emit button1pressed(true); } else if (m_currentData.m_buttonState && m_prevData.m_buttonState) { /* Button is held pressed down. */ // Gripper remains closed // write other code } else if (!m_currentData.m_buttonState && m_prevData.m_buttonState) { /* Button released. */ // Open gripper emit button1pressed(false); } /* Check if an error occurred. */ if (HD_DEVICE_ERROR(m_currentData.m_error)) { hduPrintError(stderr, &m_currentData.m_error, "Device error detected"); if (hduIsSchedulerError(&m_currentData.m_error)) { /* Quit, since communication with the device was disrupted. */ fprintf(stderr, "Communication with the device was disrupted..\n"); } } /* Store off the current data for the next loop. */ memcpy(&m_prevData, &m_currentData, sizeof(DeviceData)); // ctr++; // elapsedT += elTimer.restart(); // avgTime = elapsedT; // if( (ctr%1000) == 0) // printf("Elapsed Omni time: %d msec in %d counts.\n", int(avgTime), int(ctr)); fprintf(pFile,"%lf %lf %lf %lf %lf %lf\n", m_currentData.m_devicePosition[0],m_currentData.m_devicePosition[1],m_currentData.m_devicePosition[2], m_currentData.m_stylusHeading[0],m_currentData.m_stylusHeading[1],m_currentData.m_stylusHeading[2]); } exec(); } /******************************************************************************* Checks the state of the gimbal button and gets the position of the device. *******************************************************************************/ HDCallbackCode HDCALLBACK updateDeviceCallback(void *ptr) //pUserData { omniThread* omniPtr = (omniThread *) ptr; int nButtons = 0; hdBeginFrame(hdGetCurrentDevice()); /* Retrieve the current button(s). */ hdGetIntegerv(HD_CURRENT_BUTTONS, &nButtons); /* In order to get the specific button 1 state, we use a bitmask to test for the HD_DEVICE_BUTTON_1 bit. */ omniPtr->gServoDeviceData.m_buttonState = (nButtons & HD_DEVICE_BUTTON_2) ? HD_TRUE : HD_FALSE; /* Get the current location of the device (HD_GET_CURRENT_POSITION) We declare a vector of three doubles since hdGetDoublev returns the information in a vector of size 3. */ hdGetDoublev(HD_CURRENT_POSITION, omniPtr->gServoDeviceData.m_devicePosition); /* Get the transformation matrix (HD_CURRENT_TRANSFORM) We declare a vector of three doubles since hdGetDoublev returns the information in a vector of size 3. */ hdGetDoublev(HD_CURRENT_GIMBAL_ANGLES, omniPtr->gServoDeviceData.m_deviceRotation); hduVector3Dd temp = omniPtr->gServoDeviceData.m_deviceRotation; omniPtr->gServoDeviceData.m_deviceRotation[0] = temp[2]; omniPtr->gServoDeviceData.m_deviceRotation[2] = temp[0]; hdGetDoublev(HD_CURRENT_TRANSFORM, omniPtr->gServoDeviceData.m_transform); // // calculate Roll [=0], Pitch [=1], Yaw [=2] // omniPtr->gServoDeviceData.m_deviceRotation[0] = // atan2(omniPtr->gServoDeviceData.m_transform[4], omniPtr->gServoDeviceData.m_transform[0]); // omniPtr->gServoDeviceData.m_deviceRotation[2] = // atan2(-1.0*omniPtr->gServoDeviceData.m_transform[8], // sqrt(pow(omniPtr->gServoDeviceData.m_transform[9],2) + pow(omniPtr->gServoDeviceData.m_transform[10],2)) ); // omniPtr->gServoDeviceData.m_deviceRotation[1] = // atan2(omniPtr->gServoDeviceData.m_transform[9], omniPtr->gServoDeviceData.m_transform[10]); // calculate Roll [=0], Pitch [=1], Yaw [=2] // omni stores transformation matix in a column fashion (0,1,2,3 first column) omniPtr->gServoDeviceData.m_stylusHeading[0] = -omniPtr->gServoDeviceData.m_transform[8];//2 omniPtr->gServoDeviceData.m_stylusHeading[1] = -omniPtr->gServoDeviceData.m_transform[9];//6 omniPtr->gServoDeviceData.m_stylusHeading[2] = -omniPtr->gServoDeviceData.m_transform[10]; /* Also check the error state of HDAPI. */ omniPtr->gServoDeviceData.m_error = hdGetError(); const hduVector3Dd spherePosition(0,0,0); const double sphereStiffness = .25; // Find the distance between the device and the center of the // sphere. double distance = (omniPtr->gServoDeviceData.m_devicePosition - spherePosition).magnitude(); // If the user is outside the sphere -- i.e. if the distance from the user to // the center of the sphere is greater than the sphere radius -- then the user // is penetrating the sphere and a force should be commanded to repel him // towards the center. if (distance > omniPtr->getSphereRad()) { // Calculate the penetration distance. double penetrationDistance = distance - omniPtr->getSphereRad(); // Create a unit vector in the direction of the force, this will always // be inward to the center of the sphere through the user's // position. hduVector3Dd forceDirection = (spherePosition - omniPtr->gServoDeviceData.m_devicePosition)/distance; // Use F=kx to create a force vector that is towards the center of // the sphere and proportional to the penetration distance, and scaled // by the object stiffness. // Hooke's law explicitly: double k = sphereStiffness; hduVector3Dd x = penetrationDistance*forceDirection; hduVector3Dd f = k*x; hdSetDoublev(HD_CURRENT_FORCE, f); } /* Copy the position into our device_data tructure. */ hdEndFrame(hdGetCurrentDevice()); return HD_CALLBACK_CONTINUE; } /******************************************************************************* Checks the state of the gimbal button and gets the position of the device. *******************************************************************************/ HDCallbackCode HDCALLBACK copyDeviceDataCallback(void *ptr) //pUserData { omniThread* omniPtr = (omniThread *) ptr; DeviceData *pDeviceData = &(omniPtr->m_currentData); //(DeviceData *) pUserData; memcpy(pDeviceData, &(omniPtr->gServoDeviceData), sizeof(DeviceData)); return HD_CALLBACK_DONE; }
10,315
C++
36.787546
149
0.618905
adegirmenci/HBL-ICEbot/OmniWidget/omni.h
#ifndef OMNI_H #define OMNI_H #include <QWidget> #include <QTimer> //#include <QThread> #include <stdio.h> #include <assert.h> #include <windows.h> #include <conio.h> //#include <HDU/hduVector.h> #include "omnithread.h" namespace Ui { class Omni; } class Omni : public QWidget { Q_OBJECT public: explicit Omni(QWidget *parent = 0); omniThread *m_omnithread; ~Omni(); public slots: void updateLCD(); private slots: void on_sphSizeSpinBox_valueChanged(double arg1); private: Ui::Omni *ui; // QTimer *omniTimer; QTimer *updateTimer; //QThread momniThread; }; #endif // OMNI_H
631
C
13.363636
53
0.657686
adegirmenci/HBL-ICEbot/OmniWidget/omni.cpp
#include "omni.h" #include "ui_omni.h" /** Use to init the clock */ //#define TIMER_INIT LARGE_INTEGER frequency;LARGE_INTEGER t1,t2;double elapsedTime;QueryPerformanceFrequency(&frequency); /** Use to start the performance timer */ //#define TIMER_START QueryPerformanceCounter(&t1); /** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */ //#define TIMER_STOP QueryPerformanceCounter(&t2);elapsedTime=(float)(t2.QuadPart-t1.QuadPart)/frequency.QuadPart;printf("%g sec\n",elapsedTime); Omni::Omni(QWidget *parent) : QWidget(parent), ui(new Ui::Omni) { ui->setupUi(this); // omniTimer = new QTimer(); // omniTimer->setInterval(1); // connect(omniTimer, SIGNAL(timeout()), this, SLOT(mainLoop())); // //connect(omniTimer, SIGNAL(timeout()), ui->omniWidget, SLOT(mainLoop())); // omniTimer->start(); m_omnithread = new omniThread(); //m_omnithread->moveToThread(&momniThread); m_omnithread->start(); updateTimer = new QTimer(); updateTimer->setInterval(150); connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateLCD())); updateTimer->start(); } Omni::~Omni() { //omniTimer->stop(); updateTimer->stop(); if(m_omnithread->isRunning()) { m_omnithread->close(); m_omnithread->exit(); } delete ui; } void Omni::updateLCD() { hduVector3Dd pos; hduVector3Dd rot; m_omnithread->getDevicePosRot(pos, rot); ui->xLCD->display(pos[0]); ui->yLCD->display(pos[1]); ui->zLCD->display(pos[2]); ui->rollLCD->display(rot[0]); ui->pitchLCD->display(rot[1]); ui->yawLCD->display(rot[2]); } void Omni::on_sphSizeSpinBox_valueChanged(double arg1) { m_omnithread->setSphereRad(arg1); }
1,782
C++
26.430769
145
0.662177
adegirmenci/HBL-ICEbot/OmniWidget/omnithread.h
#ifndef OMNITHREAD_H #define OMNITHREAD_H #include <QThread> #include <QTimer> #include <QElapsedTimer> #include <stdio.h> #include <assert.h> #include <windows.h> #include <conio.h> #include <HD/hd.h> #include <HD/hdDefines.h> #include <HD/hdScheduler.h> #include <HDU/hduError.h> #include <HDU/hduVector.h> /* Holds data retrieved from HDAPI. */ typedef struct { HDboolean m_buttonState; /* Has the device button has been pressed. */ hduVector3Dd m_devicePosition; /* Current device coordinates. */ HDdouble m_transform[16]; // Transformation matrix HDErrorInfo m_error; hduVector3Dd m_deviceRotation; hduVector3Dd m_stylusHeading; } DeviceData; class omniThread : public QThread { Q_OBJECT public: explicit omniThread(QObject *parent = 0); DeviceData m_currentData; DeviceData m_prevData; DeviceData gServoDeviceData; void open(); void init(); void close(); void getDevicePosRot(hduVector3Dd &pos, hduVector3Dd &rot); double getSphereRad() {return m_sphereRadius;} void setSphereRad(double radius); signals: void button1pressed(bool pressed); public slots: void run(); private: HDSchedulerHandle m_hUpdateHandle; HHD m_hHD; double m_sphereRadius; FILE *pFile; //QTimer *updateTimer; }; HDCallbackCode HDCALLBACK updateDeviceCallback(void *ptr); HDCallbackCode HDCALLBACK copyDeviceDataCallback(void *ptr); #endif // OMNITHREAD_H
1,455
C
19.8
80
0.710653