gstaichi 0.0.0__cp311-cp311-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. gstaichi/CHANGELOG.md +4 -0
  2. gstaichi/__init__.py +51 -0
  3. gstaichi/_funcs.py +706 -0
  4. gstaichi/_kernels.py +420 -0
  5. gstaichi/_lib/__init__.py +5 -0
  6. gstaichi/_lib/core/__init__.py +0 -0
  7. gstaichi/_lib/core/gstaichi_python.cp311-win_amd64.pyd +0 -0
  8. gstaichi/_lib/core/gstaichi_python.pyi +2917 -0
  9. gstaichi/_lib/core/py.typed +0 -0
  10. gstaichi/_lib/runtime/runtime_cuda.bc +0 -0
  11. gstaichi/_lib/runtime/runtime_x64.bc +0 -0
  12. gstaichi/_lib/runtime/slim_libdevice.10.bc +0 -0
  13. gstaichi/_lib/utils.py +243 -0
  14. gstaichi/_logging.py +131 -0
  15. gstaichi/_snode/__init__.py +5 -0
  16. gstaichi/_snode/fields_builder.py +187 -0
  17. gstaichi/_snode/snode_tree.py +34 -0
  18. gstaichi/_test_tools/__init__.py +18 -0
  19. gstaichi/_test_tools/dataclass_test_tools.py +36 -0
  20. gstaichi/_test_tools/load_kernel_string.py +30 -0
  21. gstaichi/_test_tools/textwrap2.py +6 -0
  22. gstaichi/_version_check.py +100 -0
  23. gstaichi/ad/__init__.py +3 -0
  24. gstaichi/ad/_ad.py +530 -0
  25. gstaichi/algorithms/__init__.py +3 -0
  26. gstaichi/algorithms/_algorithms.py +117 -0
  27. gstaichi/assets/.git +1 -0
  28. gstaichi/assets/Go-Regular.ttf +0 -0
  29. gstaichi/assets/static/imgs/ti_gallery.png +0 -0
  30. gstaichi/examples/lcg_python.py +26 -0
  31. gstaichi/examples/lcg_taichi.py +34 -0
  32. gstaichi/examples/minimal.py +28 -0
  33. gstaichi/experimental.py +16 -0
  34. gstaichi/lang/__init__.py +50 -0
  35. gstaichi/lang/_dataclass_util.py +31 -0
  36. gstaichi/lang/_fast_caching/__init__.py +3 -0
  37. gstaichi/lang/_fast_caching/args_hasher.py +122 -0
  38. gstaichi/lang/_fast_caching/config_hasher.py +30 -0
  39. gstaichi/lang/_fast_caching/fast_caching_types.py +21 -0
  40. gstaichi/lang/_fast_caching/function_hasher.py +57 -0
  41. gstaichi/lang/_fast_caching/hash_utils.py +11 -0
  42. gstaichi/lang/_fast_caching/python_side_cache.py +52 -0
  43. gstaichi/lang/_fast_caching/src_hasher.py +83 -0
  44. gstaichi/lang/_kernel_impl_dataclass.py +212 -0
  45. gstaichi/lang/_ndarray.py +366 -0
  46. gstaichi/lang/_ndrange.py +152 -0
  47. gstaichi/lang/_template_mapper.py +195 -0
  48. gstaichi/lang/_texture.py +172 -0
  49. gstaichi/lang/_wrap_inspect.py +215 -0
  50. gstaichi/lang/any_array.py +99 -0
  51. gstaichi/lang/ast/__init__.py +7 -0
  52. gstaichi/lang/ast/ast_transformer.py +1351 -0
  53. gstaichi/lang/ast/ast_transformer_utils.py +346 -0
  54. gstaichi/lang/ast/ast_transformers/__init__.py +0 -0
  55. gstaichi/lang/ast/ast_transformers/call_transformer.py +327 -0
  56. gstaichi/lang/ast/ast_transformers/function_def_transformer.py +304 -0
  57. gstaichi/lang/ast/checkers.py +106 -0
  58. gstaichi/lang/ast/symbol_resolver.py +57 -0
  59. gstaichi/lang/ast/transform.py +9 -0
  60. gstaichi/lang/common_ops.py +310 -0
  61. gstaichi/lang/exception.py +80 -0
  62. gstaichi/lang/expr.py +180 -0
  63. gstaichi/lang/field.py +428 -0
  64. gstaichi/lang/impl.py +1259 -0
  65. gstaichi/lang/kernel_arguments.py +155 -0
  66. gstaichi/lang/kernel_impl.py +1386 -0
  67. gstaichi/lang/matrix.py +1835 -0
  68. gstaichi/lang/matrix_ops.py +341 -0
  69. gstaichi/lang/matrix_ops_utils.py +190 -0
  70. gstaichi/lang/mesh.py +687 -0
  71. gstaichi/lang/misc.py +784 -0
  72. gstaichi/lang/ops.py +1494 -0
  73. gstaichi/lang/runtime_ops.py +13 -0
  74. gstaichi/lang/shell.py +35 -0
  75. gstaichi/lang/simt/__init__.py +5 -0
  76. gstaichi/lang/simt/block.py +94 -0
  77. gstaichi/lang/simt/grid.py +7 -0
  78. gstaichi/lang/simt/subgroup.py +191 -0
  79. gstaichi/lang/simt/warp.py +96 -0
  80. gstaichi/lang/snode.py +489 -0
  81. gstaichi/lang/source_builder.py +150 -0
  82. gstaichi/lang/struct.py +810 -0
  83. gstaichi/lang/util.py +312 -0
  84. gstaichi/linalg/__init__.py +10 -0
  85. gstaichi/linalg/matrixfree_cg.py +310 -0
  86. gstaichi/linalg/sparse_cg.py +59 -0
  87. gstaichi/linalg/sparse_matrix.py +303 -0
  88. gstaichi/linalg/sparse_solver.py +123 -0
  89. gstaichi/math/__init__.py +11 -0
  90. gstaichi/math/_complex.py +205 -0
  91. gstaichi/math/mathimpl.py +886 -0
  92. gstaichi/profiler/__init__.py +6 -0
  93. gstaichi/profiler/kernel_metrics.py +260 -0
  94. gstaichi/profiler/kernel_profiler.py +586 -0
  95. gstaichi/profiler/memory_profiler.py +15 -0
  96. gstaichi/profiler/scoped_profiler.py +36 -0
  97. gstaichi/sparse/__init__.py +3 -0
  98. gstaichi/sparse/_sparse_grid.py +77 -0
  99. gstaichi/tools/__init__.py +12 -0
  100. gstaichi/tools/diagnose.py +117 -0
  101. gstaichi/tools/np2ply.py +364 -0
  102. gstaichi/tools/vtk.py +38 -0
  103. gstaichi/types/__init__.py +21 -0
  104. gstaichi/types/annotations.py +52 -0
  105. gstaichi/types/compound_types.py +71 -0
  106. gstaichi/types/enums.py +49 -0
  107. gstaichi/types/ndarray_type.py +169 -0
  108. gstaichi/types/primitive_types.py +206 -0
  109. gstaichi/types/quant.py +88 -0
  110. gstaichi/types/texture_type.py +85 -0
  111. gstaichi/types/utils.py +11 -0
  112. gstaichi-0.0.0.data/data/SPIRV-Tools/cmake/SPIRV-ToolsConfig.cmake +5 -0
  113. gstaichi-0.0.0.data/data/SPIRV-Tools/cmake/SPIRV-ToolsTarget-release.cmake +29 -0
  114. gstaichi-0.0.0.data/data/SPIRV-Tools/cmake/SPIRV-ToolsTarget.cmake +113 -0
  115. gstaichi-0.0.0.data/data/SPIRV-Tools-diff/cmake/SPIRV-Tools-diffConfig.cmake +5 -0
  116. gstaichi-0.0.0.data/data/SPIRV-Tools-diff/cmake/SPIRV-Tools-diffTargets-release.cmake +19 -0
  117. gstaichi-0.0.0.data/data/SPIRV-Tools-diff/cmake/SPIRV-Tools-diffTargets.cmake +122 -0
  118. gstaichi-0.0.0.data/data/SPIRV-Tools-link/cmake/SPIRV-Tools-linkConfig.cmake +5 -0
  119. gstaichi-0.0.0.data/data/SPIRV-Tools-link/cmake/SPIRV-Tools-linkTargets-release.cmake +19 -0
  120. gstaichi-0.0.0.data/data/SPIRV-Tools-link/cmake/SPIRV-Tools-linkTargets.cmake +122 -0
  121. gstaichi-0.0.0.data/data/SPIRV-Tools-lint/cmake/SPIRV-Tools-lintConfig.cmake +5 -0
  122. gstaichi-0.0.0.data/data/SPIRV-Tools-lint/cmake/SPIRV-Tools-lintTargets-release.cmake +19 -0
  123. gstaichi-0.0.0.data/data/SPIRV-Tools-lint/cmake/SPIRV-Tools-lintTargets.cmake +122 -0
  124. gstaichi-0.0.0.data/data/SPIRV-Tools-opt/cmake/SPIRV-Tools-optConfig.cmake +5 -0
  125. gstaichi-0.0.0.data/data/SPIRV-Tools-opt/cmake/SPIRV-Tools-optTargets-release.cmake +19 -0
  126. gstaichi-0.0.0.data/data/SPIRV-Tools-opt/cmake/SPIRV-Tools-optTargets.cmake +122 -0
  127. gstaichi-0.0.0.data/data/SPIRV-Tools-reduce/cmake/SPIRV-Tools-reduceConfig.cmake +5 -0
  128. gstaichi-0.0.0.data/data/SPIRV-Tools-reduce/cmake/SPIRV-Tools-reduceTarget-release.cmake +19 -0
  129. gstaichi-0.0.0.data/data/SPIRV-Tools-reduce/cmake/SPIRV-Tools-reduceTarget.cmake +122 -0
  130. gstaichi-0.0.0.data/data/bin/SPIRV-Tools-shared.dll +0 -0
  131. gstaichi-0.0.0.data/data/include/GLFW/glfw3.h +6389 -0
  132. gstaichi-0.0.0.data/data/include/GLFW/glfw3native.h +594 -0
  133. gstaichi-0.0.0.data/data/include/spirv-tools/instrument.hpp +268 -0
  134. gstaichi-0.0.0.data/data/include/spirv-tools/libspirv.h +907 -0
  135. gstaichi-0.0.0.data/data/include/spirv-tools/libspirv.hpp +375 -0
  136. gstaichi-0.0.0.data/data/include/spirv-tools/linker.hpp +97 -0
  137. gstaichi-0.0.0.data/data/include/spirv-tools/optimizer.hpp +970 -0
  138. gstaichi-0.0.0.data/data/lib/SPIRV-Tools-diff.lib +0 -0
  139. gstaichi-0.0.0.data/data/lib/SPIRV-Tools-link.lib +0 -0
  140. gstaichi-0.0.0.data/data/lib/SPIRV-Tools-lint.lib +0 -0
  141. gstaichi-0.0.0.data/data/lib/SPIRV-Tools-opt.lib +0 -0
  142. gstaichi-0.0.0.data/data/lib/SPIRV-Tools-reduce.lib +0 -0
  143. gstaichi-0.0.0.data/data/lib/SPIRV-Tools-shared.lib +0 -0
  144. gstaichi-0.0.0.data/data/lib/SPIRV-Tools.lib +0 -0
  145. gstaichi-0.0.0.data/data/lib/cmake/glfw3/glfw3Config.cmake +3 -0
  146. gstaichi-0.0.0.data/data/lib/cmake/glfw3/glfw3ConfigVersion.cmake +65 -0
  147. gstaichi-0.0.0.data/data/lib/cmake/glfw3/glfw3Targets-release.cmake +19 -0
  148. gstaichi-0.0.0.data/data/lib/cmake/glfw3/glfw3Targets.cmake +107 -0
  149. gstaichi-0.0.0.data/data/lib/glfw3.lib +0 -0
  150. gstaichi-0.0.0.dist-info/METADATA +97 -0
  151. gstaichi-0.0.0.dist-info/RECORD +154 -0
  152. gstaichi-0.0.0.dist-info/WHEEL +5 -0
  153. gstaichi-0.0.0.dist-info/licenses/LICENSE +201 -0
  154. gstaichi-0.0.0.dist-info/top_level.txt +1 -0
gstaichi/lang/impl.py ADDED
@@ -0,0 +1,1259 @@
1
+ import numbers
2
+ import weakref
3
+ from types import FunctionType, MethodType
4
+ from typing import TYPE_CHECKING, Any, Iterable, Sequence
5
+
6
+ import numpy as np
7
+
8
+ from gstaichi._lib import core as _ti_core
9
+ from gstaichi._lib.core.gstaichi_python import (
10
+ DataTypeCxx,
11
+ Function,
12
+ KernelCxx,
13
+ Program,
14
+ )
15
+ from gstaichi._snode.fields_builder import FieldsBuilder
16
+ from gstaichi.lang._ndarray import ScalarNdarray
17
+ from gstaichi.lang._ndrange import GroupedNDRange, _Ndrange
18
+ from gstaichi.lang._texture import RWTextureAccessor
19
+ from gstaichi.lang.any_array import AnyArray
20
+ from gstaichi.lang.exception import (
21
+ GsTaichiCompilationError,
22
+ GsTaichiRuntimeError,
23
+ GsTaichiSyntaxError,
24
+ GsTaichiTypeError,
25
+ )
26
+ from gstaichi.lang.expr import Expr, make_expr_group
27
+ from gstaichi.lang.field import Field, ScalarField
28
+ from gstaichi.lang.kernel_arguments import SparseMatrixProxy
29
+ from gstaichi.lang.kernel_impl import BoundGsTaichiCallable, GsTaichiCallable, Kernel
30
+ from gstaichi.lang.matrix import (
31
+ Matrix,
32
+ MatrixField,
33
+ MatrixNdarray,
34
+ MatrixType,
35
+ Vector,
36
+ VectorNdarray,
37
+ make_matrix,
38
+ )
39
+ from gstaichi.lang.mesh import (
40
+ ConvType,
41
+ MeshElementFieldProxy,
42
+ MeshInstance,
43
+ MeshRelationAccessProxy,
44
+ MeshReorderedMatrixFieldProxy,
45
+ MeshReorderedScalarFieldProxy,
46
+ element_type_name,
47
+ )
48
+ from gstaichi.lang.simt.block import SharedArray
49
+ from gstaichi.lang.snode import SNode
50
+ from gstaichi.lang.struct import Struct, StructField, _IntermediateStruct
51
+ from gstaichi.lang.util import (
52
+ cook_dtype,
53
+ get_traceback,
54
+ gstaichi_scope,
55
+ is_gstaichi_class,
56
+ python_scope,
57
+ warning,
58
+ )
59
+ from gstaichi.types.enums import SNodeGradType
60
+ from gstaichi.types.ndarray_type import NdarrayType
61
+ from gstaichi.types.primitive_types import (
62
+ all_types,
63
+ f16,
64
+ f32,
65
+ f64,
66
+ i32,
67
+ i64,
68
+ u8,
69
+ u32,
70
+ u64,
71
+ )
72
+
73
+ if TYPE_CHECKING:
74
+ from gstaichi.lang._ndarray import Ndarray
75
+
76
+
77
+ @gstaichi_scope
78
+ def expr_init_shared_array(shape, element_type):
79
+ ast_builder = get_runtime().compiling_callable.ast_builder()
80
+ debug_info = _ti_core.DebugInfo(get_runtime().get_current_src_info())
81
+ return ast_builder.expr_alloca_shared_array(shape, element_type, debug_info)
82
+
83
+
84
+ @gstaichi_scope
85
+ def expr_init(rhs):
86
+ compiling_callable = get_runtime().compiling_callable
87
+ if rhs is None:
88
+ return Expr(
89
+ compiling_callable.ast_builder().expr_alloca(_ti_core.DebugInfo(get_runtime().get_current_src_info()))
90
+ )
91
+ if isinstance(rhs, Matrix) and (hasattr(rhs, "_DIM")):
92
+ return Matrix(*rhs.to_list(), ndim=rhs.ndim) # type: ignore
93
+ if isinstance(rhs, Matrix):
94
+ return make_matrix(rhs.to_list())
95
+ if isinstance(rhs, SharedArray):
96
+ return rhs
97
+ if isinstance(rhs, Struct):
98
+ return Struct(rhs.to_dict(include_methods=True, include_ndim=True))
99
+ if isinstance(rhs, list):
100
+ return [expr_init(e) for e in rhs]
101
+ if isinstance(rhs, tuple):
102
+ return tuple(expr_init(e) for e in rhs)
103
+ if isinstance(rhs, dict):
104
+ return dict((key, expr_init(val)) for key, val in rhs.items())
105
+ if isinstance(rhs, _ti_core.DataTypeCxx):
106
+ return rhs
107
+ if isinstance(rhs, _ti_core.Arch):
108
+ return rhs
109
+ if isinstance(rhs, _Ndrange):
110
+ return rhs
111
+ if isinstance(rhs, MeshElementFieldProxy):
112
+ return rhs
113
+ if isinstance(rhs, MeshRelationAccessProxy):
114
+ return rhs
115
+ if hasattr(rhs, "_data_oriented"):
116
+ return rhs
117
+ return Expr(
118
+ compiling_callable.ast_builder().expr_var(
119
+ Expr(rhs).ptr, _ti_core.DebugInfo(get_runtime().get_current_src_info())
120
+ )
121
+ )
122
+
123
+
124
+ @gstaichi_scope
125
+ def expr_init_func(rhs): # temporary solution to allow passing in fields as arguments
126
+ if isinstance(rhs, Field):
127
+ return rhs
128
+ return expr_init(rhs)
129
+
130
+
131
+ def begin_frontend_struct_for(ast_builder, group, loop_range):
132
+ if not isinstance(loop_range, (AnyArray, Field, SNode, RWTextureAccessor, _Root)):
133
+ raise TypeError(
134
+ f"Cannot loop over the object {type(loop_range)} in GsTaichi scope. Only GsTaichi fields (via template) or dense arrays (via types.ndarray) are supported."
135
+ )
136
+ if group.size() != len(loop_range.shape):
137
+ raise IndexError(
138
+ "Number of struct-for indices does not match loop variable dimensionality "
139
+ f"({group.size()} != {len(loop_range.shape)}). Maybe you wanted to "
140
+ 'use "for I in ti.grouped(x)" to group all indices into a single vector I?'
141
+ )
142
+ dbg_info = _ti_core.DebugInfo(get_runtime().get_current_src_info())
143
+ if isinstance(loop_range, (AnyArray, RWTextureAccessor)):
144
+ ast_builder.begin_frontend_struct_for_on_external_tensor(group, loop_range._loop_range(), dbg_info)
145
+ else:
146
+ ast_builder.begin_frontend_struct_for_on_snode(group, loop_range._loop_range(), dbg_info)
147
+
148
+
149
+ def begin_frontend_if(ast_builder, cond, stmt_dbg_info):
150
+ assert ast_builder is not None
151
+ if is_gstaichi_class(cond):
152
+ raise ValueError(
153
+ "The truth value of vectors/matrices is ambiguous.\n"
154
+ "Consider using `any` or `all` when comparing vectors/matrices:\n"
155
+ " if all(x == y):\n"
156
+ "or\n"
157
+ " if any(x != y):\n"
158
+ )
159
+ ast_builder.begin_frontend_if(Expr(cond).ptr, stmt_dbg_info)
160
+
161
+
162
+ @gstaichi_scope
163
+ def _calc_slice(index, default_stop):
164
+ start, stop, step = index.start or 0, index.stop or default_stop, index.step or 1
165
+
166
+ def check_validity(x):
167
+ # TODO(mzmzm): support variable in slice
168
+ if isinstance(x, Expr):
169
+ raise GsTaichiCompilationError(
170
+ "GsTaichi does not support variables in slice now, please use constant instead of it."
171
+ )
172
+
173
+ _ = check_validity(start), check_validity(stop), check_validity(step)
174
+ return [_ for _ in range(start, stop, step)]
175
+
176
+
177
+ def validate_subscript_index(value, index):
178
+ if isinstance(value, Field):
179
+ # field supports negative indices
180
+ return
181
+
182
+ if isinstance(index, Expr):
183
+ return
184
+
185
+ if isinstance(index, Iterable):
186
+ for ind in index:
187
+ validate_subscript_index(value, ind)
188
+
189
+ if isinstance(index, slice):
190
+ validate_subscript_index(value, index.start)
191
+ validate_subscript_index(value, index.stop)
192
+
193
+ if isinstance(index, int) and index < 0:
194
+ raise GsTaichiSyntaxError("Negative indices are not supported in GsTaichi kernels.")
195
+
196
+
197
+ @gstaichi_scope
198
+ def subscript(ast_builder, value, *_indices, skip_reordered=False):
199
+ dbg_info = _ti_core.DebugInfo(get_runtime().get_current_src_info())
200
+ ast_builder = get_runtime().compiling_callable.ast_builder()
201
+ # Directly evaluate in Python for non-GsTaichi types
202
+ if not isinstance(
203
+ value,
204
+ (
205
+ Expr,
206
+ Field,
207
+ AnyArray,
208
+ SparseMatrixProxy,
209
+ MeshElementFieldProxy,
210
+ MeshRelationAccessProxy,
211
+ SharedArray,
212
+ ),
213
+ ):
214
+ if isinstance(value, NdarrayType):
215
+ raise Exception(
216
+ "Cannot subscript NdarrayType. Did you access a global py dataclass inadvertently?", value, type(value)
217
+ )
218
+ if len(_indices) == 1:
219
+ _indices = _indices[0]
220
+ return value.__getitem__(_indices)
221
+
222
+ has_slice = False
223
+
224
+ flattened_indices = []
225
+ for _index in _indices:
226
+ if isinstance(_index, Matrix):
227
+ ind = _index.to_list()
228
+ elif isinstance(_index, slice):
229
+ ind = [_index]
230
+ has_slice = True
231
+ else:
232
+ ind = [_index]
233
+ flattened_indices += ind
234
+ indices = tuple(flattened_indices)
235
+ validate_subscript_index(value, indices)
236
+
237
+ if len(indices) == 1 and indices[0] is None:
238
+ indices = ()
239
+
240
+ indices_expr_group = None
241
+ if has_slice:
242
+ if not (isinstance(value, Expr) and value.is_tensor()):
243
+ raise GsTaichiSyntaxError(f"The type {type(value)} do not support index of slice type")
244
+ else:
245
+ indices_expr_group = make_expr_group(*indices)
246
+
247
+ if isinstance(value, SharedArray):
248
+ return value.subscript(*indices)
249
+ if isinstance(value, MeshElementFieldProxy):
250
+ return value.subscript(*indices) # type: ignore
251
+ if isinstance(value, MeshRelationAccessProxy):
252
+ return value.subscript(*indices)
253
+ if isinstance(value, (MeshReorderedScalarFieldProxy, MeshReorderedMatrixFieldProxy)) and not skip_reordered:
254
+ assert len(indices) > 0
255
+ reordered_index = tuple(
256
+ [
257
+ Expr(
258
+ ast_builder.mesh_index_conversion(
259
+ value.mesh_ptr, value.element_type, Expr(indices[0]).ptr, ConvType.g2r, dbg_info
260
+ )
261
+ )
262
+ ]
263
+ )
264
+ return subscript(ast_builder, value, *reordered_index, skip_reordered=True)
265
+ if isinstance(value, SparseMatrixProxy):
266
+ return value.subscript(*indices)
267
+ if isinstance(value, Field):
268
+ _var = value._get_field_members()[0].ptr
269
+ snode = _var.snode()
270
+ if snode is None:
271
+ if _var.is_primal():
272
+ raise RuntimeError(f"{_var.get_expr_name()} has not been placed.")
273
+ else:
274
+ raise RuntimeError(
275
+ f"Gradient {_var.get_expr_name()} has not been placed, check whether `needs_grad=True`"
276
+ )
277
+
278
+ assert indices_expr_group is not None
279
+ if isinstance(value, MatrixField):
280
+ return Expr(ast_builder.expr_subscript(value.ptr, indices_expr_group, dbg_info))
281
+ if isinstance(value, StructField):
282
+ entries = {k: subscript(ast_builder, v, *indices) for k, v in value._items}
283
+ entries["__struct_methods"] = value.struct_methods
284
+ return _IntermediateStruct(entries)
285
+ return Expr(ast_builder.expr_subscript(_var, indices_expr_group, dbg_info))
286
+ if isinstance(value, AnyArray):
287
+ assert indices_expr_group is not None
288
+ return Expr(ast_builder.expr_subscript(value.ptr, indices_expr_group, dbg_info))
289
+ assert isinstance(value, Expr)
290
+ # Index into TensorType
291
+ # value: IndexExpression with ret_type = TensorType
292
+ assert value.is_tensor()
293
+
294
+ if has_slice:
295
+ shape = value.get_shape()
296
+ dim = len(shape)
297
+ assert dim == len(indices)
298
+ indices = [
299
+ _calc_slice(index, shape[i]) if isinstance(index, slice) else index for i, index in enumerate(indices)
300
+ ]
301
+ if dim == 1:
302
+ assert isinstance(indices[0], list)
303
+ multiple_indices = [make_expr_group(i) for i in indices[0]]
304
+ return_shape = (len(indices[0]),)
305
+ else:
306
+ assert dim == 2
307
+ if isinstance(indices[0], list) and isinstance(indices[1], list):
308
+ multiple_indices = [make_expr_group(i, j) for i in indices[0] for j in indices[1]]
309
+ return_shape = (len(indices[0]), len(indices[1]))
310
+ elif isinstance(indices[0], list): # indices[1] is not list
311
+ multiple_indices = [make_expr_group(i, indices[1]) for i in indices[0]]
312
+ return_shape = (len(indices[0]),)
313
+ else: # indices[0] is not list while indices[1] is list
314
+ multiple_indices = [make_expr_group(indices[0], j) for j in indices[1]]
315
+ return_shape = (len(indices[1]),)
316
+ return Expr(
317
+ _ti_core.subscript_with_multiple_indices(
318
+ value.ptr,
319
+ multiple_indices,
320
+ return_shape,
321
+ dbg_info,
322
+ )
323
+ )
324
+ return Expr(ast_builder.expr_subscript(value.ptr, indices_expr_group, dbg_info))
325
+
326
+
327
+ class SrcInfoGuard:
328
+ def __init__(self, info_stack, info):
329
+ self.info_stack = info_stack
330
+ self.info = info
331
+
332
+ def __enter__(self):
333
+ self.info_stack.append(self.info)
334
+
335
+ def __exit__(self, exc_type, exc_val, exc_tb):
336
+ self.info_stack.pop()
337
+
338
+
339
+ class PyGsTaichi:
340
+ def __init__(self, kernels=None):
341
+ self.materialized = False
342
+ self._prog: Program | None = None
343
+ self.src_info_stack = []
344
+ self.inside_kernel: bool = False
345
+ self._compiling_callable: KernelCxx | Kernel | Function | None = None
346
+ self._current_kernel: "Kernel | None" = None
347
+ self.global_vars = []
348
+ self.grad_vars = []
349
+ self.dual_vars = []
350
+ self.matrix_fields = []
351
+ self.default_fp = f32
352
+ self.default_ip = i32
353
+ self.default_up = u32
354
+ self.print_full_traceback: bool = False
355
+ self.target_tape = None
356
+ self.fwd_mode_manager = None
357
+ self.grad_replaced = False
358
+ self.kernels: list[Kernel] = kernels or []
359
+ self.ndarrays: weakref.WeakSet[Ndarray] = weakref.WeakSet()
360
+ self._signal_handler_registry = None
361
+ self.unfinalized_fields_builder = {}
362
+ self.print_non_pure: bool = False
363
+ self.short_circuit_operators: bool = False
364
+ self.unrolling_limit: int = 0
365
+ self.src_ll_cache: bool = True
366
+
367
+ @property
368
+ def compiling_callable(self) -> KernelCxx | Kernel | Function:
369
+ if self._compiling_callable is None:
370
+ raise GsTaichiRuntimeError(
371
+ "_compiling_callable attribute not initialized. Maybe you forgot to call `ti.init()` first?"
372
+ )
373
+ return self._compiling_callable
374
+
375
+ @property
376
+ def prog(self) -> Program:
377
+ if self._prog is None:
378
+ raise GsTaichiRuntimeError("_prog attribute not initialized. Maybe you forgot to call `ti.init()` first?")
379
+ return self._prog
380
+
381
+ @property
382
+ def current_kernel(self) -> Kernel:
383
+ if self._current_kernel is None:
384
+ raise GsTaichiRuntimeError(
385
+ "_current_kernel attribute not initialized. Maybe you forgot to call `ti.init()` first?"
386
+ )
387
+ return self._current_kernel
388
+
389
+ def initialize_fields_builder(self, builder):
390
+ self.unfinalized_fields_builder[builder] = get_traceback(2)
391
+
392
+ def clear_compiled_functions(self):
393
+ for k in self.kernels:
394
+ k.materialized_kernels.clear()
395
+
396
+ def finalize_fields_builder(self, builder):
397
+ self.unfinalized_fields_builder.pop(builder)
398
+
399
+ def validate_fields_builder(self):
400
+ for builder, tb in self.unfinalized_fields_builder.items():
401
+ if builder == _root_fb:
402
+ continue
403
+
404
+ raise GsTaichiRuntimeError(
405
+ f"Field builder {builder} is not finalized. " f"Please call finalize() on it. Traceback:\n{tb}"
406
+ )
407
+
408
+ def get_num_compiled_functions(self):
409
+ count = 0
410
+ for k in self.kernels:
411
+ count += len(k.materialized_kernels)
412
+ return count
413
+
414
+ def src_info_guard(self, info):
415
+ return SrcInfoGuard(self.src_info_stack, info)
416
+
417
+ def get_current_src_info(self):
418
+ return self.src_info_stack[-1]
419
+
420
+ def set_default_fp(self, fp):
421
+ assert fp in [f16, f32, f64]
422
+ self.default_fp = fp
423
+ default_cfg().default_fp = self.default_fp
424
+
425
+ def set_default_ip(self, ip):
426
+ assert ip in [i32, i64]
427
+ self.default_ip = ip
428
+ self.default_up = u32 if ip == i32 else u64
429
+ default_cfg().default_ip = self.default_ip
430
+ default_cfg().default_up = self.default_up
431
+
432
+ def create_program(self):
433
+ if self._prog is None:
434
+ self._prog = _ti_core.Program()
435
+
436
+ @staticmethod
437
+ def materialize_root_fb(is_first_call):
438
+ if root.finalized:
439
+ return
440
+ if not is_first_call and root.empty:
441
+ # We have to forcefully finalize when `is_first_call` is True (even
442
+ # if the root itself is empty), so that there is a valid struct
443
+ # llvm::Module, if no field has been declared before the first kernel
444
+ # invocation. Example case:
445
+ # https://github.com/taichi-dev/gstaichi/blob/27bb1dc3227d9273a79fcb318fdb06fd053068f5/tests/python/test_ad_basics.py#L260-L266
446
+ return
447
+
448
+ if get_runtime().prog.config().debug:
449
+ if not root.finalized:
450
+ root._allocate_adjoint_checkbit()
451
+
452
+ root.finalize(raise_warning=not is_first_call)
453
+ global _root_fb
454
+ _root_fb = FieldsBuilder()
455
+
456
+ @staticmethod
457
+ def _get_tb(_var):
458
+ return getattr(_var, "declaration_tb", str(_var.ptr))
459
+
460
+ def _check_field_not_placed(self):
461
+ not_placed = []
462
+ for _var in self.global_vars:
463
+ if _var.ptr.snode() is None:
464
+ not_placed.append(self._get_tb(_var))
465
+
466
+ if len(not_placed):
467
+ bar = "=" * 44 + "\n"
468
+ raise RuntimeError(
469
+ f"These field(s) are not placed:\n{bar}"
470
+ + f"{bar}".join(not_placed)
471
+ + f"{bar}Please consider specifying a shape for them. E.g.,"
472
+ + "\n\n x = ti.field(float, shape=(2, 3))"
473
+ )
474
+
475
+ def _check_gradient_field_not_placed(self, gradient_type):
476
+ not_placed = set()
477
+ gradient_vars = []
478
+ if gradient_type == "grad":
479
+ gradient_vars = self.grad_vars
480
+ elif gradient_type == "dual":
481
+ gradient_vars = self.dual_vars
482
+ for _var in gradient_vars:
483
+ if _var.ptr.snode() is None:
484
+ not_placed.add(self._get_tb(_var))
485
+
486
+ if len(not_placed):
487
+ bar = "=" * 44 + "\n"
488
+ raise RuntimeError(
489
+ f"These field(s) requrie `needs_{gradient_type}=True`, however their {gradient_type} field(s) are not placed:\n{bar}"
490
+ + f"{bar}".join(not_placed)
491
+ + f"{bar}Please consider place the {gradient_type} field(s). E.g.,"
492
+ + "\n\n ti.root.dense(ti.i, 1).place(x.{gradient_type})"
493
+ + "\n\n Or specify a shape for the field(s). E.g.,"
494
+ + "\n\n x = ti.field(float, shape=(2, 3), needs_{gradient_type}=True)"
495
+ )
496
+
497
+ def _check_matrix_field_member_shape(self):
498
+ for _field in self.matrix_fields:
499
+ shapes = [_field.get_scalar_field(i, j).shape for i in range(_field.n) for j in range(_field.m)]
500
+ if any(shape != shapes[0] for shape in shapes):
501
+ raise RuntimeError(
502
+ "Members of the following field have different shapes "
503
+ + f"{shapes}:\n{self._get_tb(_field._get_field_members()[0])}"
504
+ )
505
+
506
+ def _calc_matrix_field_dynamic_index_stride(self):
507
+ for _field in self.matrix_fields:
508
+ _field._calc_dynamic_index_stride()
509
+
510
+ def materialize(self):
511
+ self.materialize_root_fb(not self.materialized)
512
+ self.materialized = True
513
+
514
+ self.validate_fields_builder()
515
+
516
+ self._check_field_not_placed()
517
+ self._check_gradient_field_not_placed("grad")
518
+ self._check_gradient_field_not_placed("dual")
519
+ self._check_matrix_field_member_shape()
520
+ self._calc_matrix_field_dynamic_index_stride()
521
+ self.global_vars = []
522
+ self.grad_vars = []
523
+ self.dual_vars = []
524
+ self.matrix_fields = []
525
+
526
+ def _register_signal_handlers(self):
527
+ if self._signal_handler_registry is None:
528
+ self._signal_handler_registry = _ti_core.HackedSignalRegister()
529
+
530
+ def clear(self):
531
+ if self._prog:
532
+ self._prog.finalize()
533
+ self._prog = None
534
+ self._signal_handler_registry = None
535
+ self.materialized = False
536
+
537
+ def sync(self):
538
+ self.materialize()
539
+ assert self._prog is not None
540
+ self._prog.synchronize()
541
+
542
+
543
+ pygstaichi = PyGsTaichi()
544
+
545
+
546
+ def get_runtime() -> PyGsTaichi:
547
+ return pygstaichi
548
+
549
+
550
+ def reset():
551
+ global pygstaichi
552
+ old_ndarrays = pygstaichi.ndarrays
553
+ old_kernels = pygstaichi.kernels
554
+ pygstaichi.clear()
555
+ pygstaichi = PyGsTaichi(old_kernels)
556
+ for nd in old_ndarrays:
557
+ nd._reset()
558
+ for k in old_kernels:
559
+ k.reset()
560
+ _ti_core.reset_default_compile_config()
561
+
562
+
563
+ @gstaichi_scope
564
+ def static_print(*args, __p=print, **kwargs):
565
+ """The print function in GsTaichi scope.
566
+
567
+ This function is called at compile time and has no runtime overhead.
568
+ """
569
+ __p(*args, **kwargs)
570
+
571
+
572
+ # we don't add @gstaichi_scope decorator for @ti.pyfunc to work
573
+ def static_assert(cond, msg=None):
574
+ """Throw AssertionError when `cond` is False.
575
+
576
+ This function is called at compile time and has no runtime overhead.
577
+ The bool value in `cond` must can be determined at compile time.
578
+
579
+ Args:
580
+ cond (bool): an expression with a bool value.
581
+ msg (str): assertion message.
582
+
583
+ Example::
584
+
585
+ >>> year = 2001
586
+ >>> @ti.kernel
587
+ >>> def test():
588
+ >>> ti.static_assert(year % 4 == 0, "the year must be a lunar year")
589
+ AssertionError: the year must be a lunar year
590
+ """
591
+ if isinstance(cond, Expr):
592
+ raise GsTaichiTypeError("Static assert with non-static condition")
593
+ if msg is not None:
594
+ assert cond, msg
595
+ else:
596
+ assert cond
597
+
598
+
599
+ def inside_kernel():
600
+ return pygstaichi.inside_kernel
601
+
602
+
603
+ def index_nd(dim):
604
+ return axes(*range(dim))
605
+
606
+
607
+ class _UninitializedRootFieldsBuilder:
608
+ def __getattr__(self, item):
609
+ if item == "__qualname__":
610
+ # For sphinx docstring extraction.
611
+ return "_UninitializedRootFieldsBuilder"
612
+ raise GsTaichiRuntimeError("Please call init() first")
613
+
614
+
615
+ # `root` initialization must be delayed until after the program is
616
+ # created. Unfortunately, `root` exists in both gstaichi.lang.impl module and
617
+ # the top-level gstaichi module at this point; so if `root` itself is written, we
618
+ # would have to make sure that `root` in all the modules get updated to the same
619
+ # instance. This is an error-prone process.
620
+ #
621
+ # To avoid this situation, we create `root` once during the import time, and
622
+ # never write to it. The core part, `_root_fb`, is the one whose initialization
623
+ # gets delayed. `_root_fb` will only exist in the gstaichi.lang.impl module, so
624
+ # writing to it is would result in less for maintenance cost.
625
+ #
626
+ # `_root_fb` will be overridden inside :func:`gstaichi.lang.init`.
627
+ _root_fb = _UninitializedRootFieldsBuilder()
628
+
629
+
630
+ def deactivate_all_snodes():
631
+ """Recursively deactivate all SNodes."""
632
+ for root_fb in FieldsBuilder._finalized_roots():
633
+ root_fb.deactivate_all()
634
+
635
+
636
+ class _Root:
637
+ """Wrapper around the default root FieldsBuilder instance."""
638
+
639
+ @staticmethod
640
+ def parent(n=1):
641
+ """Same as :func:`gstaichi.SNode.parent`"""
642
+ assert isinstance(_root_fb, FieldsBuilder)
643
+ return _root_fb.root.parent(n)
644
+
645
+ @staticmethod
646
+ def _loop_range():
647
+ """Same as :func:`gstaichi.SNode.loop_range`"""
648
+ assert isinstance(_root_fb, FieldsBuilder)
649
+ return _root_fb.root._loop_range()
650
+
651
+ @staticmethod
652
+ def _get_children():
653
+ """Same as :func:`gstaichi.SNode.get_children`"""
654
+ assert isinstance(_root_fb, FieldsBuilder)
655
+ return _root_fb.root._get_children()
656
+
657
+ # TODO: Record all of the SNodeTrees that finalized under 'ti.root'
658
+ @staticmethod
659
+ def deactivate_all():
660
+ warning("""'ti.root.deactivate_all()' would deactivate all finalized snodes.""")
661
+ deactivate_all_snodes()
662
+
663
+ @property
664
+ def shape(self):
665
+ """Same as :func:`gstaichi.SNode.shape`"""
666
+ assert isinstance(_root_fb, FieldsBuilder)
667
+ return _root_fb.root.shape
668
+
669
+ @property
670
+ def _id(self):
671
+ assert isinstance(_root_fb, FieldsBuilder)
672
+ return _root_fb.root._id
673
+
674
+ def __getattr__(self, item):
675
+ return getattr(_root_fb, item)
676
+
677
+ def __repr__(self):
678
+ return "ti.root"
679
+
680
+
681
+ root = _Root()
682
+ """Root of the declared GsTaichi :func:`~gstaichi.lang.impl.field`s.
683
+
684
+ See also https://docs.taichi-lang.org/docs/layout
685
+
686
+ Example::
687
+
688
+ >>> x = ti.field(ti.f32)
689
+ >>> ti.root.pointer(ti.ij, 4).dense(ti.ij, 8).place(x)
690
+ """
691
+
692
+
693
+ def _create_snode(axis_seq: Sequence[int], shape_seq: Sequence[numbers.Number], same_level: bool):
694
+ dim = len(axis_seq)
695
+ assert dim == len(shape_seq)
696
+ snode = root
697
+ if same_level:
698
+ snode = snode.dense(axes(*axis_seq), shape_seq)
699
+ else:
700
+ for i in range(dim):
701
+ snode = snode.dense(axes(axis_seq[i]), (shape_seq[i],))
702
+ return snode
703
+
704
+
705
+ @python_scope
706
+ def create_field_member(dtype, name, needs_grad, needs_dual):
707
+ dtype = cook_dtype(dtype)
708
+
709
+ # primal
710
+ prog = get_runtime().prog
711
+
712
+ x = Expr(prog.make_id_expr(""))
713
+ x.declaration_tb = get_traceback(stacklevel=4)
714
+ x.ptr = _ti_core.expr_field(x.ptr, dtype)
715
+ x.ptr.set_name(name)
716
+ x.ptr.set_grad_type(SNodeGradType.PRIMAL)
717
+ pygstaichi.global_vars.append(x)
718
+
719
+ x_grad = None
720
+ x_dual = None
721
+ # The x_grad_checkbit is used for global data access rule checker
722
+ x_grad_checkbit = None
723
+ if _ti_core.is_real(dtype):
724
+ # adjoint
725
+ x_grad = Expr(prog.make_id_expr(""))
726
+ x_grad.declaration_tb = get_traceback(stacklevel=4)
727
+ x_grad.ptr = _ti_core.expr_field(x_grad.ptr, dtype)
728
+ x_grad.ptr.set_name(name + ".grad")
729
+ x_grad.ptr.set_grad_type(SNodeGradType.ADJOINT)
730
+ x.ptr.set_adjoint(x_grad.ptr)
731
+ if needs_grad:
732
+ pygstaichi.grad_vars.append(x_grad)
733
+
734
+ if prog.config().debug:
735
+ # adjoint checkbit
736
+ x_grad_checkbit = Expr(prog.make_id_expr(""))
737
+ dtype = u8
738
+ if prog.config().arch == _ti_core.vulkan:
739
+ dtype = i32
740
+ x_grad_checkbit.ptr = _ti_core.expr_field(x_grad_checkbit.ptr, cook_dtype(dtype))
741
+ x_grad_checkbit.ptr.set_name(name + ".grad_checkbit")
742
+ x_grad_checkbit.ptr.set_grad_type(SNodeGradType.ADJOINT_CHECKBIT)
743
+ x.ptr.set_adjoint_checkbit(x_grad_checkbit.ptr)
744
+
745
+ # dual
746
+ x_dual = Expr(prog.make_id_expr(""))
747
+ x_dual.ptr = _ti_core.expr_field(x_dual.ptr, dtype)
748
+ x_dual.ptr.set_name(name + ".dual")
749
+ x_dual.ptr.set_grad_type(SNodeGradType.DUAL)
750
+ x.ptr.set_dual(x_dual.ptr)
751
+ if needs_dual:
752
+ pygstaichi.dual_vars.append(x_dual)
753
+ elif needs_grad or needs_dual:
754
+ raise GsTaichiRuntimeError(f"{dtype} is not supported for field with `needs_grad=True` or `needs_dual=True`.")
755
+
756
+ return x, x_grad, x_dual
757
+
758
+
759
+ @python_scope
760
+ def _field(
761
+ dtype,
762
+ shape=None,
763
+ order=None,
764
+ name="",
765
+ offset=None,
766
+ needs_grad=False,
767
+ needs_dual=False,
768
+ ):
769
+ x, x_grad, x_dual = create_field_member(dtype, name, needs_grad, needs_dual)
770
+ x = ScalarField(x)
771
+ if x_grad:
772
+ x_grad = ScalarField(x_grad)
773
+ x._set_grad(x_grad)
774
+ if x_dual:
775
+ x_dual = ScalarField(x_dual)
776
+ x._set_dual(x_dual)
777
+
778
+ if shape is None:
779
+ if offset is not None:
780
+ raise GsTaichiSyntaxError("shape cannot be None when offset is set")
781
+ if order is not None:
782
+ raise GsTaichiSyntaxError("shape cannot be None when order is set")
783
+ else:
784
+ if isinstance(shape, numbers.Number):
785
+ shape = (shape,)
786
+ if isinstance(offset, numbers.Number):
787
+ offset = (offset,)
788
+ dim = len(shape)
789
+ if offset is not None and dim != len(offset):
790
+ raise GsTaichiSyntaxError(
791
+ f"The dimensionality of shape and offset must be the same ({dim} != {len(offset)})"
792
+ )
793
+ axis_seq = []
794
+ shape_seq = []
795
+ if order is not None:
796
+ if dim != len(order):
797
+ raise GsTaichiSyntaxError(
798
+ f"The dimensionality of shape and order must be the same ({dim} != {len(order)})"
799
+ )
800
+ if dim != len(set(order)):
801
+ raise GsTaichiSyntaxError("The axes in order must be different")
802
+ for ch in order:
803
+ axis = ord(ch) - ord("i")
804
+ if axis < 0 or axis >= dim:
805
+ raise GsTaichiSyntaxError(f"Invalid axis {ch}")
806
+ axis_seq.append(axis)
807
+ shape_seq.append(shape[axis])
808
+ else:
809
+ axis_seq = list(range(dim))
810
+ shape_seq = list(shape)
811
+ same_level = order is None
812
+ _create_snode(axis_seq, shape_seq, same_level).place(x, offset=offset)
813
+ if needs_grad:
814
+ _create_snode(axis_seq, shape_seq, same_level).place(x_grad, offset=offset)
815
+ if needs_dual:
816
+ _create_snode(axis_seq, shape_seq, same_level).place(x_dual, offset=offset)
817
+ return x
818
+
819
+
820
+ @python_scope
821
+ def field(dtype, *args, **kwargs):
822
+ """Defines a GsTaichi field.
823
+
824
+ A GsTaichi field can be viewed as an abstract N-dimensional array, hiding away
825
+ the complexity of how its underlying :class:`~gstaichi.lang.snode.SNode` are
826
+ actually defined. The data in a GsTaichi field can be directly accessed by
827
+ a GsTaichi :func:`~gstaichi.lang.kernel_impl.kernel`.
828
+
829
+ See also https://docs.taichi-lang.org/docs/field
830
+
831
+ Args:
832
+ dtype (DataType): data type of the field. Note it can be vector or matrix types as well.
833
+ shape (Union[int, tuple[int]], optional): shape of the field.
834
+ order (str, optional): order of the shape laid out in memory.
835
+ name (str, optional): name of the field.
836
+ offset (Union[int, tuple[int]], optional): offset of the field domain.
837
+ needs_grad (bool, optional): whether this field participates in autodiff (reverse mode)
838
+ and thus needs an adjoint field to store the gradients.
839
+ needs_dual (bool, optional): whether this field participates in autodiff (forward mode)
840
+ and thus needs an dual field to store the gradients.
841
+
842
+ Example::
843
+
844
+ The code below shows how a GsTaichi field can be declared and defined::
845
+
846
+ >>> x1 = ti.field(ti.f32, shape=(16, 8))
847
+ >>> # Equivalently
848
+ >>> x2 = ti.field(ti.f32)
849
+ >>> ti.root.dense(ti.ij, shape=(16, 8)).place(x2)
850
+ >>>
851
+ >>> x3 = ti.field(ti.f32, shape=(16, 8), order='ji')
852
+ >>> # Equivalently
853
+ >>> x4 = ti.field(ti.f32)
854
+ >>> ti.root.dense(ti.j, shape=8).dense(ti.i, shape=16).place(x4)
855
+ >>>
856
+ >>> x5 = ti.field(ti.math.vec3, shape=(16, 8))
857
+
858
+ """
859
+ if isinstance(dtype, MatrixType):
860
+ if dtype.ndim == 1:
861
+ return Vector.field(dtype.n, dtype.dtype, *args, **kwargs)
862
+ return Matrix.field(dtype.n, dtype.m, dtype.dtype, *args, **kwargs)
863
+ return _field(dtype, *args, **kwargs)
864
+
865
+
866
+ @python_scope
867
+ def ndarray(dtype, shape, needs_grad=False):
868
+ """Defines a GsTaichi ndarray with scalar elements.
869
+
870
+ Args:
871
+ dtype (Union[DataType, MatrixType]): Data type of each element. This can be either a scalar type like ti.f32 or a compound type like ti.types.vector(3, ti.i32).
872
+ shape (Union[int, tuple[int]]): Shape of the ndarray.
873
+
874
+ Example:
875
+ The code below shows how a GsTaichi ndarray with scalar elements can be declared and defined::
876
+
877
+ >>> x = ti.ndarray(ti.f32, shape=(16, 8)) # ndarray of shape (16, 8), each element is ti.f32 scalar.
878
+ >>> vec3 = ti.types.vector(3, ti.i32)
879
+ >>> y = ti.ndarray(vec3, shape=(10, 2)) # ndarray of shape (10, 2), each element is a vector of 3 ti.i32 scalars.
880
+ >>> matrix_ty = ti.types.matrix(3, 4, float)
881
+ >>> z = ti.ndarray(matrix_ty, shape=(4, 5)) # ndarray of shape (4, 5), each element is a matrix of (3, 4) ti.float scalars.
882
+ """
883
+ # primal
884
+ if isinstance(shape, numbers.Number):
885
+ shape = (shape,)
886
+ if not all((isinstance(x, int) or isinstance(x, np.integer)) and x > 0 and x <= 2**31 - 1 for x in shape):
887
+ raise GsTaichiRuntimeError(f"{shape} is not a valid shape for ndarray")
888
+ if dtype in all_types:
889
+ dt = cook_dtype(dtype)
890
+ x = ScalarNdarray(dt, shape)
891
+ elif isinstance(dtype, MatrixType):
892
+ if dtype.ndim == 1:
893
+ x = VectorNdarray(dtype.n, dtype.dtype, shape)
894
+ else:
895
+ x = MatrixNdarray(dtype.n, dtype.m, dtype.dtype, shape)
896
+ dt = dtype.dtype
897
+ else:
898
+ raise GsTaichiRuntimeError(f"{dtype} is not supported as ndarray element type")
899
+ if needs_grad:
900
+ assert isinstance(dt, DataTypeCxx)
901
+ if not _ti_core.is_real(dt):
902
+ raise GsTaichiRuntimeError(
903
+ f"{dt} is not supported for ndarray with `needs_grad=True` or `needs_dual=True`."
904
+ )
905
+ x_grad = ndarray(dtype, shape, needs_grad=False)
906
+ x._set_grad(x_grad)
907
+ return x
908
+
909
+
910
+ @gstaichi_scope
911
+ def ti_format_list_to_content_entries(raw):
912
+ # return a pair of [content, format]
913
+ def entry2content(_var):
914
+ if isinstance(_var, str):
915
+ return [_var, None]
916
+ if isinstance(_var, list):
917
+ assert len(_var) == 2 and (isinstance(_var[1], str) or _var[1] is None)
918
+ _var[0] = Expr(_var[0]).ptr
919
+ return _var
920
+ return [Expr(_var).ptr, None]
921
+
922
+ def list_ti_repr(_var):
923
+ yield "[" # distinguishing tuple & list will increase maintenance cost
924
+ for i, v in enumerate(_var):
925
+ if i:
926
+ yield ", "
927
+ yield v
928
+ yield "]"
929
+
930
+ def vars2entries(_vars):
931
+ for _var in _vars:
932
+ # If the first element is '__ti_fmt_value__', this list is an Expr and its format.
933
+ if isinstance(_var, list) and len(_var) == 3 and isinstance(_var[0], str) and _var[0] == "__ti_fmt_value__":
934
+ # yield [Expr, format] as a whole and don't pass it to vars2entries() again
935
+ yield _var[1:]
936
+ continue
937
+ elif hasattr(_var, "__ti_repr__"):
938
+ res = _var.__ti_repr__() # type: ignore
939
+ elif isinstance(_var, (list, tuple)):
940
+ # If the first element is '__ti_format__', this list is the result of ti_format.
941
+ if len(_var) > 0 and isinstance(_var[0], str) and _var[0] == "__ti_format__":
942
+ res = _var[1:]
943
+ else:
944
+ res = list_ti_repr(_var)
945
+ else:
946
+ yield _var
947
+ continue
948
+
949
+ for v in vars2entries(res):
950
+ yield v
951
+
952
+ def fused_string(entries):
953
+ accumated = ""
954
+ for entry in entries:
955
+ if isinstance(entry, str):
956
+ accumated += entry
957
+ else:
958
+ if accumated:
959
+ yield accumated
960
+ accumated = ""
961
+ yield entry
962
+ if accumated:
963
+ yield accumated
964
+
965
+ def extract_formats(entries):
966
+ contents, formats = zip(*entries)
967
+ return list(contents), list(formats)
968
+
969
+ entries = vars2entries(raw)
970
+ entries = fused_string(entries)
971
+ entries = [entry2content(entry) for entry in entries]
972
+ return extract_formats(entries)
973
+
974
+
975
+ @gstaichi_scope
976
+ def ti_print(*_vars, sep=" ", end="\n"):
977
+ def add_separators(_vars):
978
+ for i, _var in enumerate(_vars):
979
+ if i:
980
+ yield sep
981
+ yield _var
982
+ yield end
983
+
984
+ _vars = add_separators(_vars)
985
+ contents, formats = ti_format_list_to_content_entries(_vars)
986
+ ast_builder = get_runtime().compiling_callable.ast_builder()
987
+ debug_info = _ti_core.DebugInfo(get_runtime().get_current_src_info())
988
+ ast_builder.create_print(contents, formats, debug_info)
989
+
990
+
991
+ @gstaichi_scope
992
+ def ti_format(*args):
993
+ content = args[0]
994
+ mixed = args[1:]
995
+ new_mixed = []
996
+ args = []
997
+ for x in mixed:
998
+ # x is a (formatted) Expr
999
+ if isinstance(x, Expr) or (isinstance(x, list) and len(x) == 3 and x[0] == "__ti_fmt_value__"):
1000
+ new_mixed.append("{}")
1001
+ args.append(x)
1002
+ else:
1003
+ new_mixed.append(x)
1004
+ content = content.format(*new_mixed)
1005
+ res = content.split("{}")
1006
+ assert len(res) == len(args) + 1, "Number of args is different from number of positions provided in string"
1007
+
1008
+ for i, arg in enumerate(args):
1009
+ res.insert(i * 2 + 1, arg)
1010
+ res.insert(0, "__ti_format__")
1011
+ return res
1012
+
1013
+
1014
+ @gstaichi_scope
1015
+ def ti_assert(cond, msg, extra_args, dbg_info):
1016
+ # Mostly a wrapper to help us convert from Expr (defined in Python) to
1017
+ # _ti_core.Expr (defined in C++)
1018
+ ast_builder = get_runtime().compiling_callable.ast_builder()
1019
+ ast_builder.create_assert_stmt(Expr(cond).ptr, msg, extra_args, dbg_info)
1020
+
1021
+
1022
+ @gstaichi_scope
1023
+ def ti_int(_var):
1024
+ if hasattr(_var, "__ti_int__"):
1025
+ return _var.__ti_int__()
1026
+ return int(_var)
1027
+
1028
+
1029
+ @gstaichi_scope
1030
+ def ti_bool(_var):
1031
+ if hasattr(_var, "__ti_bool__"):
1032
+ return _var.__ti_bool__()
1033
+ return bool(_var)
1034
+
1035
+
1036
+ @gstaichi_scope
1037
+ def ti_float(_var):
1038
+ if hasattr(_var, "__ti_float__"):
1039
+ return _var.__ti_float__()
1040
+ return float(_var)
1041
+
1042
+
1043
+ @gstaichi_scope
1044
+ def zero(x):
1045
+ # TODO: get dtype from Expr and Matrix:
1046
+ """Returns an array of zeros with the same shape and type as the input. It's also a scalar
1047
+ if the input is a scalar.
1048
+
1049
+ Args:
1050
+ x (Union[:mod:`~gstaichi.types.primitive_types`, :class:`~gstaichi.Matrix`]): The input.
1051
+
1052
+ Returns:
1053
+ A new copy of the input but filled with zeros.
1054
+
1055
+ Example::
1056
+
1057
+ >>> x = ti.Vector([1, 1])
1058
+ >>> @ti.kernel
1059
+ >>> def test():
1060
+ >>> y = ti.zero(x)
1061
+ >>> print(y)
1062
+ [0, 0]
1063
+ """
1064
+ return x * 0
1065
+
1066
+
1067
+ @gstaichi_scope
1068
+ def one(x):
1069
+ """Returns an array of ones with the same shape and type as the input. It's also a scalar
1070
+ if the input is a scalar.
1071
+
1072
+ Args:
1073
+ x (Union[:mod:`~gstaichi.types.primitive_types`, :class:`~gstaichi.Matrix`]): The input.
1074
+
1075
+ Returns:
1076
+ A new copy of the input but filled with ones.
1077
+
1078
+ Example::
1079
+
1080
+ >>> x = ti.Vector([0, 0])
1081
+ >>> @ti.kernel
1082
+ >>> def test():
1083
+ >>> y = ti.one(x)
1084
+ >>> print(y)
1085
+ [1, 1]
1086
+ """
1087
+ return zero(x) + 1
1088
+
1089
+
1090
+ def axes(*x: int):
1091
+ """Defines a list of axes to be used by a field.
1092
+
1093
+ Args:
1094
+ *x: A list of axes to be activated
1095
+
1096
+ Note that GsTaichi has already provided a set of commonly used axes. For example,
1097
+ `ti.ij` is just `axes(0, 1)` under the hood.
1098
+ """
1099
+ return [_ti_core.Axis(i) for i in x]
1100
+
1101
+
1102
+ Axis = _ti_core.Axis
1103
+
1104
+
1105
+ def static(x, *xs) -> Any:
1106
+ """Evaluates a GsTaichi-scope expression at compile time.
1107
+
1108
+ `static()` is what enables the so-called metaprogramming in GsTaichi. It is
1109
+ in many ways similar to ``constexpr`` in C++.
1110
+
1111
+ See also https://docs.taichi-lang.org/docs/meta.
1112
+
1113
+ Args:
1114
+ x (Any): an expression to be evaluated
1115
+ *xs (Any): for Python-ish swapping assignment
1116
+
1117
+ Example:
1118
+ The most common usage of `static()` is for compile-time evaluation::
1119
+
1120
+ >>> cond = False
1121
+ >>>
1122
+ >>> @ti.kernel
1123
+ >>> def run():
1124
+ >>> if ti.static(cond):
1125
+ >>> do_a()
1126
+ >>> else:
1127
+ >>> do_b()
1128
+
1129
+ Depending on the value of ``cond``, ``run()`` will be directly compiled
1130
+ into either ``do_a()`` or ``do_b()``. Thus there won't be a runtime
1131
+ condition check.
1132
+
1133
+ Another common usage is for compile-time loop unrolling::
1134
+
1135
+ >>> @ti.kernel
1136
+ >>> def run():
1137
+ >>> for i in ti.static(range(3)):
1138
+ >>> print(i)
1139
+ >>>
1140
+ >>> # The above will be unrolled to:
1141
+ >>> @ti.kernel
1142
+ >>> def run():
1143
+ >>> print(0)
1144
+ >>> print(1)
1145
+ >>> print(2)
1146
+ """
1147
+ if len(xs): # for python-ish pointer assign: x, y = ti.static(y, x)
1148
+ return [static(x)] + [static(x) for x in xs]
1149
+
1150
+ if (
1151
+ isinstance(
1152
+ x,
1153
+ (
1154
+ bool,
1155
+ int,
1156
+ float,
1157
+ range,
1158
+ list,
1159
+ tuple,
1160
+ enumerate,
1161
+ GroupedNDRange,
1162
+ _Ndrange,
1163
+ zip,
1164
+ filter,
1165
+ map,
1166
+ ),
1167
+ )
1168
+ or x is None
1169
+ ):
1170
+ return x
1171
+ if isinstance(x, (np.bool_, np.integer, np.floating)):
1172
+ return x
1173
+
1174
+ if isinstance(x, AnyArray):
1175
+ return x
1176
+ if isinstance(x, Field):
1177
+ return x
1178
+ if isinstance(x, (FunctionType, MethodType, BoundGsTaichiCallable, GsTaichiCallable)):
1179
+ return x
1180
+ raise ValueError(f"Input to ti.static must be compile-time constants or global pointers, instead of {type(x)}")
1181
+
1182
+
1183
+ @gstaichi_scope
1184
+ def grouped(x):
1185
+ """Groups the indices in the iterator returned by `ndrange()` into a 1-D vector.
1186
+
1187
+ This is often used when you want to iterate over all indices returned by `ndrange()`
1188
+ in one `for` loop and a single index.
1189
+
1190
+ Args:
1191
+ x (:func:`~gstaichi.ndrange`): an iterator object returned by `ti.ndrange`.
1192
+
1193
+ Example::
1194
+ >>> # without ti.grouped
1195
+ >>> for I in ti.ndrange(2, 3):
1196
+ >>> print(I)
1197
+ prints 0, 1, 2, 3, 4, 5
1198
+
1199
+ >>> # with ti.grouped
1200
+ >>> for I in ti.grouped(ti.ndrange(2, 3)):
1201
+ >>> print(I)
1202
+ prints [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]
1203
+ """
1204
+ if isinstance(x, _Ndrange):
1205
+ return x.grouped()
1206
+ return x
1207
+
1208
+
1209
+ def stop_grad(x):
1210
+ """Stops computing gradients during back propagation.
1211
+
1212
+ Args:
1213
+ x (:class:`~gstaichi.Field`): A field.
1214
+ """
1215
+ compiling_callable = get_runtime().compiling_callable
1216
+ assert compiling_callable is not None
1217
+ compiling_callable.ast_builder().stop_grad(x.snode.ptr)
1218
+
1219
+
1220
+ def current_cfg():
1221
+ return get_runtime().prog.config()
1222
+
1223
+
1224
+ def default_cfg():
1225
+ return _ti_core.default_compile_config()
1226
+
1227
+
1228
+ def call_internal(name, *args, with_runtime_context=True):
1229
+ return expr_init(_ti_core.insert_internal_func_call(getattr(_ti_core.InternalOp, name), make_expr_group(args)))
1230
+
1231
+
1232
+ def get_cuda_compute_capability():
1233
+ return _ti_core.query_int64("cuda_compute_capability")
1234
+
1235
+
1236
+ @gstaichi_scope
1237
+ def mesh_relation_access(mesh, from_index, to_element_type):
1238
+ # to support ti.mesh_local and access mesh attribute as field
1239
+ if isinstance(from_index, MeshInstance):
1240
+ return getattr(from_index, element_type_name(to_element_type))
1241
+ if isinstance(mesh, MeshInstance):
1242
+ return MeshRelationAccessProxy(mesh, from_index, to_element_type)
1243
+ raise RuntimeError("Relation access should be with a mesh instance!")
1244
+
1245
+
1246
+ __all__ = [
1247
+ "axes",
1248
+ "deactivate_all_snodes",
1249
+ "field",
1250
+ "grouped",
1251
+ "ndarray",
1252
+ "one",
1253
+ "root",
1254
+ "static",
1255
+ "static_assert",
1256
+ "static_print",
1257
+ "stop_grad",
1258
+ "zero",
1259
+ ]