def test_image_io_vector(resx, resy, comp, ext, dt): shape = (resx, resy) pixel = np.random.rand(*shape, comp).astype(to_numpy_type(dt)) pixel_t = ti.Vector.field(comp, dt, shape) pixel_t.from_numpy(pixel) fn = make_temp_file(suffix='.' + ext) ti.imwrite(pixel_t, fn) pixel_r = (ti.imread(fn).astype(to_numpy_type(dt)) + 0.5) / 256.0 assert np.allclose(pixel_r, pixel, atol=2e-2) os.remove(fn)
def to_numpy(self): import numpy as np from taichi.lang.meta import tensor_to_ext_arr arr = np.zeros(shape=self.shape, dtype=to_numpy_type(self.dtype)) tensor_to_ext_arr(self, arr) ti.sync() return arr
def make_constant_expr(val, dtype): if isinstance(val, (float, np.floating)): constant_dtype = impl.get_runtime( ).default_fp if dtype is None else dtype if constant_dtype not in real_types: raise TaichiTypeError( 'Floating-point literals must be annotated with a floating-point type. For type casting, use `ti.cast`.' ) return Expr(_ti_core.make_const_expr_fp(constant_dtype, val)) if isinstance(val, (int, np.integer)): constant_dtype = impl.get_runtime( ).default_ip if dtype is None else dtype if constant_dtype not in integer_types: raise TaichiTypeError( 'Integer literals must be annotated with a integer type. For type casting, use `ti.cast`.' ) if _check_in_range(to_numpy_type(constant_dtype), val): return Expr( _ti_core.make_const_expr_int( constant_dtype, _clamp_unsigned_to_range(np.int64, val))) if dtype is None: raise TaichiTypeError( f'Integer literal {val} exceeded the range of default_ip: {impl.get_runtime().default_ip}, please specify the dtype via e.g. `ti.u64({val})` or set a different `default_ip` in `ti.init()`' ) else: raise TaichiTypeError( f'Integer literal {val} exceeded the range of specified dtype: {dtype}' ) raise TaichiTypeError(f'Invalid constant scalar data type: {type(val)}')
def to_numpy(self, keep_dims=False, as_vector=None, dtype=None): """Converts `self` to a numpy array. Args: keep_dims (bool, optional): Whether to keep the dimension after conversion. When keep_dims=True, on an n-D matrix field, the numpy array always has n+2 dims, even for 1x1, 1xn, nx1 matrix fields. When keep_dims=False, the resulting numpy array should skip the matrix dims with size 1. For example, a 4x1 or 1x4 matrix field with 5x6x7 elements results in an array of shape 5x6x7x4. as_vector (bool, deprecated): Whether to make the returned numpy array as a vector, i.e., with shape (n,) rather than (n, 1). Note that this argument has been deprecated. More discussion about `as_vector`: https://github.com/taichi-dev/taichi/pull/1046#issuecomment-633548858. dtype (DataType, optional): The desired data type of returned numpy array. Returns: numpy.ndarray: The result numpy array. """ if as_vector is not None: warning( 'v.to_numpy(as_vector=True) is deprecated, ' 'please use v.to_numpy() directly instead', DeprecationWarning, stacklevel=3) if dtype is None: dtype = to_numpy_type(self.dtype) as_vector = self.m == 1 and not keep_dims shape_ext = (self.n, ) if as_vector else (self.n, self.m) import numpy as np arr = np.zeros(self.shape + shape_ext, dtype=dtype) from taichi.lang.meta import matrix_to_ext_arr matrix_to_ext_arr(self, arr, as_vector) ti.sync() return arr
def to_numpy(self, dtype=None): if dtype is None: dtype = to_numpy_type(self.dtype) import numpy as np # pylint: disable=C0415 arr = np.zeros(shape=self.shape, dtype=dtype) taichi.lang.meta.tensor_to_ext_arr(self, arr) ti.sync() return arr
def to_numpy(self, dtype=None): if dtype is None: dtype = to_numpy_type(self.dtype) import numpy as np arr = np.zeros(shape=self.shape, dtype=dtype) from taichi.lang.meta import tensor_to_ext_arr tensor_to_ext_arr(self, arr) ti.sync() return arr
def to_numpy(self, dtype=None): if dtype is None: dtype = to_numpy_type(self.dtype) import numpy as np # pylint: disable=C0415 arr = np.zeros(shape=self.shape, dtype=dtype) from taichi._kernels import tensor_to_ext_arr # pylint: disable=C0415 tensor_to_ext_arr(self, arr) taichi.lang.runtime_ops.sync() return arr
def make_constant_expr(val, dtype): if isinstance(val, (int, np.integer)): constant_dtype = pytaichi.default_ip if dtype is None else dtype _check_in_range(to_numpy_type(constant_dtype), val) return Expr( _ti_core.make_const_expr_int( constant_dtype, _clamp_unsigned_to_range(np.int64, val))) if isinstance(val, (float, np.floating)): constant_dtype = pytaichi.default_fp if dtype is None else dtype return Expr(_ti_core.make_const_expr_fp(constant_dtype, val)) raise TaichiTypeError(f'Invalid constant scalar data type: {type(val)}')
def _ndarray_to_numpy(self): """Converts ndarray to a numpy array. Returns: numpy.ndarray: The result numpy array. """ arr = np.zeros(shape=self.arr.shape, dtype=to_numpy_type(self.dtype)) from taichi._kernels import ndarray_to_ext_arr # pylint: disable=C0415 ndarray_to_ext_arr(self, arr) impl.get_runtime().sync() return arr
def ndarray_to_numpy(self): """Converts ndarray to a numpy array. Returns: numpy.ndarray: The result numpy array. """ if impl.current_cfg().ndarray_use_torch: return self.arr.cpu().numpy() arr = np.zeros(shape=self.arr.shape, dtype=to_numpy_type(self.dtype)) taichi.lang.meta.ndarray_to_ext_arr(self, arr) impl.get_runtime().sync() return arr
def _ndarray_matrix_to_numpy(self, layout, as_vector): """Converts matrix ndarray to a numpy array. Returns: numpy.ndarray: The result numpy array. """ arr = np.zeros(shape=self.arr.shape, dtype=to_numpy_type(self.dtype)) from taichi._kernels import \ ndarray_matrix_to_ext_arr # pylint: disable=C0415 layout_is_aos = 1 if layout == Layout.AOS else 0 ndarray_matrix_to_ext_arr(self, arr, layout_is_aos, as_vector) impl.get_runtime().sync() return arr
def to_numpy(self): """Create a numpy array containing the same elements when the class itself represents GlobalVariableExpression (field) or ExternalTensorExpression internally. This is an unified interface to match :func:`taichi.lang.Matrix.to_numpy`. Returns: The numpy array containing the same elements when the class itself represents GlobalVariableExpression (field) or ExternalTensorExpression internally. """ import numpy as np from taichi.lang.meta import tensor_to_ext_arr arr = np.zeros(shape=self.shape, dtype=to_numpy_type(self.dtype)) tensor_to_ext_arr(self, arr) ti.sync() return arr
def test_image_io_uint(resx, resy, comp, ext, dt): shape = (resx, resy) np_type = to_numpy_type(dt) # When saving to disk, pixel data will be truncated into 8 bits. # Be careful here if you want lossless saving. np_max = np.iinfo(np_type).max // 256 pixel = np.random.randint(256, size=(*shape, comp), dtype=np_type) * np_max pixel_t = ti.Vector.field(comp, dt, shape) pixel_t.from_numpy(pixel) fn = make_temp_file(suffix='.' + ext) ti.imwrite(pixel_t, fn) pixel_r = ti.imread(fn).astype(np_type) * np_max assert (pixel_r == pixel).all() os.remove(fn)
def ndarray_matrix_to_numpy(self, as_vector): """Converts matrix ndarray to a numpy array. Returns: numpy.ndarray: The result numpy array. """ if self.ndarray_use_torch: return self.arr.cpu().numpy() arr = np.zeros(shape=self.arr.shape, dtype=to_numpy_type(self.dtype)) from taichi._kernels import \ ndarray_matrix_to_ext_arr # pylint: disable=C0415 ndarray_matrix_to_ext_arr(self, arr, as_vector) impl.get_runtime().sync() return arr
def to_numpy(self): """Converts ndarray to a numpy array. Returns: numpy.ndarray: The result numpy array. """ if impl.current_cfg().ndarray_use_torch: return self.arr.cpu().numpy() else: import numpy as np # pylint: disable=C0415 arr = np.zeros(shape=self.arr.shape, dtype=to_numpy_type(self.dtype)) from taichi.lang.meta import \ ndarray_to_ext_arr # pylint: disable=C0415 ndarray_to_ext_arr(self, arr) impl.get_runtime().sync() return arr
def to_numpy(self, keep_dims=False, as_vector=None, dtype=None): # Discussion: https://github.com/taichi-dev/taichi/pull/1046#issuecomment-633548858 if as_vector is not None: warning( 'v.to_numpy(as_vector=True) is deprecated, ' 'please use v.to_numpy() directly instead', DeprecationWarning, stacklevel=3) as_vector = self.m == 1 and not keep_dims shape_ext = (self.n, ) if as_vector else (self.n, self.m) if not self.is_global(): return np.array(self.entries).reshape(shape_ext) if dtype is None: dtype = to_numpy_type(self.dtype) ret = np.zeros(self.shape + shape_ext, dtype=dtype) from taichi.lang.meta import matrix_to_ext_arr matrix_to_ext_arr(self, ret, as_vector) return ret
def make_constant_expr(val, dtype): if isinstance(val, (int, np.integer)): constant_dtype = impl.get_runtime( ).default_ip if dtype is None else dtype if constant_dtype not in integer_types: raise TaichiTypeError( 'Integer literals must be annotated with a integer type. For type casting, use `ti.cast`.' ) _check_in_range(to_numpy_type(constant_dtype), val) return Expr( _ti_core.make_const_expr_int( constant_dtype, _clamp_unsigned_to_range(np.int64, val))) if isinstance(val, (float, np.floating)): constant_dtype = impl.get_runtime( ).default_fp if dtype is None else dtype if constant_dtype not in real_types: raise TaichiTypeError( 'Floating-point literals must be annotated with a floating-point type. For type casting, use `ti.cast`.' ) return Expr(_ti_core.make_const_expr_fp(constant_dtype, val)) raise TaichiTypeError(f'Invalid constant scalar data type: {type(val)}')
def test_image_io(resx, resy, comp, ext, is_field, dt): if comp != 1: shape = (resx, resy, comp) else: shape = (resx, resy) if is_field: pixel_t = ti.field(dt, shape) pixel = np.random.randint(256, size=shape, dtype=to_numpy_type(dt)) if is_field: pixel_t.from_numpy(pixel) fn = make_temp_file(suffix='.' + ext) if is_field: ti.imwrite(pixel_t, fn) else: ti.imwrite(pixel, fn) pixel_r = ti.imread(fn) if comp == 1: # from (resx, resy, 1) to (resx, resy) pixel_r = pixel_r.reshape((resx, resy)) assert (pixel_r == pixel).all() os.remove(fn)
def to_numpy(self, keep_dims=False, as_vector=None, dtype=None): """Convert the taichi matrix to a numpy.ndarray. Args: keep_dims (bool, optional): Whether keep the dimension after conversion. When keep_dims=True, on an n-D matrix field, the numpy array always has n+2 dims, even for 1x1, 1xn, nx1 matrix fields. When keep_dims=False, the resulting numpy array should skip the dimensionality with only 1 element, on the matrix shape dimensionalities. For example, a 4x1 or 1x4 matrix field with 5x6x7 elements results in an array of shape 5x6x7x4. as_vector (bool, deprecated): Make the returned numpy array as a vector i.e., has a shape (n,) rather than (n, 1) Note that this argument has been deprecated. More discussion about `as_vector`: https://github.com/taichi-dev/taichi/pull/1046#issuecomment-633548858. dtype (DataType, optional): The desired data type of returned numpy array. Returns: numpy.ndarray: The numpy array that converted from the matrix field. """ # Discussion: https://github.com/taichi-dev/taichi/pull/1046#issuecomment-633548858 if as_vector is not None: warning( 'v.to_numpy(as_vector=True) is deprecated, ' 'please use v.to_numpy() directly instead', DeprecationWarning, stacklevel=3) as_vector = self.m == 1 and not keep_dims shape_ext = (self.n, ) if as_vector else (self.n, self.m) if not self.is_global(): return np.array(self.entries).reshape(shape_ext) if dtype is None: dtype = to_numpy_type(self.dtype) ret = np.zeros(self.shape + shape_ext, dtype=dtype) from taichi.lang.meta import matrix_to_ext_arr matrix_to_ext_arr(self, ret, as_vector) return ret