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