def test_slice(): element_type = Type.f32 shape = Shape([6, 6]) A = Parameter(element_type, shape) parameter_list = [A] input_arr = np.arange(36, dtype=np.float32).reshape(6, 6) lower_bounds = [1, 1] upper_bounds = [5, 5] function = Function( NodeVector( [Slice(A, Coordinate(lower_bounds), Coordinate(upper_bounds))]), parameter_list, 'test') backend = Backend.create(test.BACKEND_NAME) a = backend.create_tensor(element_type, shape) result = backend.create_tensor(element_type, Shape([4, 4])) a.write(util.numpy_to_c(input_arr), 0, 36 * 4) result_arr = np.zeros(16, dtype=np.float32).reshape(4, 4) result.write(util.numpy_to_c(result_arr), 0, 16 * 4) handle = backend.compile(function) handle.call([result], [a]) result.read(util.numpy_to_c(result_arr), 0, 64) result_arr_ref = input_arr[lower_bounds[0]:upper_bounds[0], lower_bounds[1]:upper_bounds[1]] assert np.allclose(result_arr, result_arr_ref) #test with strides strides = [1, 2] function = Function( NodeVector([ Slice(A, Coordinate(lower_bounds), Coordinate(upper_bounds), Strides(strides)) ]), parameter_list, 'test') backend = Backend.create(test.BACKEND_NAME) result = backend.create_tensor(element_type, Shape([4, 2])) result_arr = np.zeros(8, dtype=np.float32).reshape(4, 2) result.write(util.numpy_to_c(result_arr), 0, 8 * 4) handle = backend.compile(function) handle.call([result], [a]) result.read(util.numpy_to_c(result_arr), 0, 32) result_arr_ref = result_arr_ref[::strides[0], ::strides[1]] assert np.allclose(result_arr, result_arr_ref)
def slice(node, lower_bounds, upper_bounds, strides=None, name=None): # type: (Node, List[int], List[int], List[int], str) -> Node """Take a slice of an input tensor, (sub-tensor) that resides within a bounding box. Optionally this function may be provided with stride along each axis. :param node: The tensor we want to slice. :param lower_bounds: The (inclusive) lower-bound coordinates for the tensor slice. :param upper_bounds: The (exclusive) upper-bound coordinates for the tensor slice. :param strides: The strides for the tensor slice. :param name: Optional name for the output node. :return: Return node that represents a slice of input nodes data. """ if strides is None: return Slice(node, Coordinate(lower_bounds), Coordinate(upper_bounds)) else: return Slice(node, Coordinate(lower_bounds), Coordinate(upper_bounds), Strides(strides))