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