warp-lang 1.0.2__py3-none-win_amd64.whl → 1.2.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of warp-lang might be problematic. Click here for more details.

Files changed (356) hide show
  1. warp/__init__.py +108 -97
  2. warp/__init__.pyi +1 -1
  3. warp/bin/warp-clang.dll +0 -0
  4. warp/bin/warp.dll +0 -0
  5. warp/build.py +88 -113
  6. warp/build_dll.py +383 -375
  7. warp/builtins.py +3693 -3354
  8. warp/codegen.py +2925 -2792
  9. warp/config.py +40 -36
  10. warp/constants.py +49 -45
  11. warp/context.py +5409 -5102
  12. warp/dlpack.py +442 -442
  13. warp/examples/__init__.py +16 -16
  14. warp/examples/assets/bear.usd +0 -0
  15. warp/examples/assets/bunny.usd +0 -0
  16. warp/examples/assets/cartpole.urdf +110 -110
  17. warp/examples/assets/crazyflie.usd +0 -0
  18. warp/examples/assets/cube.usd +0 -0
  19. warp/examples/assets/nv_ant.xml +92 -92
  20. warp/examples/assets/nv_humanoid.xml +183 -183
  21. warp/examples/assets/quadruped.urdf +267 -267
  22. warp/examples/assets/rocks.nvdb +0 -0
  23. warp/examples/assets/rocks.usd +0 -0
  24. warp/examples/assets/sphere.usd +0 -0
  25. warp/examples/benchmarks/benchmark_api.py +381 -383
  26. warp/examples/benchmarks/benchmark_cloth.py +278 -277
  27. warp/examples/benchmarks/benchmark_cloth_cupy.py +88 -88
  28. warp/examples/benchmarks/benchmark_cloth_jax.py +97 -100
  29. warp/examples/benchmarks/benchmark_cloth_numba.py +146 -142
  30. warp/examples/benchmarks/benchmark_cloth_numpy.py +77 -77
  31. warp/examples/benchmarks/benchmark_cloth_pytorch.py +86 -86
  32. warp/examples/benchmarks/benchmark_cloth_taichi.py +112 -112
  33. warp/examples/benchmarks/benchmark_cloth_warp.py +145 -146
  34. warp/examples/benchmarks/benchmark_launches.py +293 -295
  35. warp/examples/browse.py +29 -29
  36. warp/examples/core/example_dem.py +232 -219
  37. warp/examples/core/example_fluid.py +291 -267
  38. warp/examples/core/example_graph_capture.py +142 -126
  39. warp/examples/core/example_marching_cubes.py +186 -174
  40. warp/examples/core/example_mesh.py +172 -155
  41. warp/examples/core/example_mesh_intersect.py +203 -193
  42. warp/examples/core/example_nvdb.py +174 -170
  43. warp/examples/core/example_raycast.py +103 -90
  44. warp/examples/core/example_raymarch.py +197 -178
  45. warp/examples/core/example_render_opengl.py +183 -141
  46. warp/examples/core/example_sph.py +403 -387
  47. warp/examples/core/example_torch.py +219 -181
  48. warp/examples/core/example_wave.py +261 -248
  49. warp/examples/fem/bsr_utils.py +378 -380
  50. warp/examples/fem/example_apic_fluid.py +432 -389
  51. warp/examples/fem/example_burgers.py +262 -0
  52. warp/examples/fem/example_convection_diffusion.py +180 -168
  53. warp/examples/fem/example_convection_diffusion_dg.py +217 -209
  54. warp/examples/fem/example_deformed_geometry.py +175 -159
  55. warp/examples/fem/example_diffusion.py +199 -173
  56. warp/examples/fem/example_diffusion_3d.py +178 -152
  57. warp/examples/fem/example_diffusion_mgpu.py +219 -214
  58. warp/examples/fem/example_mixed_elasticity.py +242 -222
  59. warp/examples/fem/example_navier_stokes.py +257 -243
  60. warp/examples/fem/example_stokes.py +218 -192
  61. warp/examples/fem/example_stokes_transfer.py +263 -249
  62. warp/examples/fem/mesh_utils.py +133 -109
  63. warp/examples/fem/plot_utils.py +292 -287
  64. warp/examples/optim/example_bounce.py +258 -246
  65. warp/examples/optim/example_cloth_throw.py +220 -209
  66. warp/examples/optim/example_diffray.py +564 -536
  67. warp/examples/optim/example_drone.py +862 -835
  68. warp/examples/optim/example_inverse_kinematics.py +174 -168
  69. warp/examples/optim/example_inverse_kinematics_torch.py +183 -169
  70. warp/examples/optim/example_spring_cage.py +237 -231
  71. warp/examples/optim/example_trajectory.py +221 -199
  72. warp/examples/optim/example_walker.py +304 -293
  73. warp/examples/sim/example_cartpole.py +137 -129
  74. warp/examples/sim/example_cloth.py +194 -186
  75. warp/examples/sim/example_granular.py +122 -111
  76. warp/examples/sim/example_granular_collision_sdf.py +195 -186
  77. warp/examples/sim/example_jacobian_ik.py +234 -214
  78. warp/examples/sim/example_particle_chain.py +116 -105
  79. warp/examples/sim/example_quadruped.py +191 -180
  80. warp/examples/sim/example_rigid_chain.py +195 -187
  81. warp/examples/sim/example_rigid_contact.py +187 -177
  82. warp/examples/sim/example_rigid_force.py +125 -125
  83. warp/examples/sim/example_rigid_gyroscopic.py +107 -95
  84. warp/examples/sim/example_rigid_soft_contact.py +132 -122
  85. warp/examples/sim/example_soft_body.py +188 -177
  86. warp/fabric.py +337 -335
  87. warp/fem/__init__.py +61 -27
  88. warp/fem/cache.py +403 -388
  89. warp/fem/dirichlet.py +178 -179
  90. warp/fem/domain.py +262 -263
  91. warp/fem/field/__init__.py +100 -101
  92. warp/fem/field/field.py +148 -149
  93. warp/fem/field/nodal_field.py +298 -299
  94. warp/fem/field/restriction.py +22 -21
  95. warp/fem/field/test.py +180 -181
  96. warp/fem/field/trial.py +183 -183
  97. warp/fem/geometry/__init__.py +16 -19
  98. warp/fem/geometry/closest_point.py +69 -70
  99. warp/fem/geometry/deformed_geometry.py +270 -271
  100. warp/fem/geometry/element.py +748 -744
  101. warp/fem/geometry/geometry.py +184 -186
  102. warp/fem/geometry/grid_2d.py +380 -373
  103. warp/fem/geometry/grid_3d.py +437 -435
  104. warp/fem/geometry/hexmesh.py +953 -953
  105. warp/fem/geometry/nanogrid.py +455 -0
  106. warp/fem/geometry/partition.py +374 -376
  107. warp/fem/geometry/quadmesh_2d.py +532 -532
  108. warp/fem/geometry/tetmesh.py +840 -840
  109. warp/fem/geometry/trimesh_2d.py +577 -577
  110. warp/fem/integrate.py +1684 -1615
  111. warp/fem/operator.py +190 -191
  112. warp/fem/polynomial.py +214 -213
  113. warp/fem/quadrature/__init__.py +2 -2
  114. warp/fem/quadrature/pic_quadrature.py +243 -245
  115. warp/fem/quadrature/quadrature.py +295 -294
  116. warp/fem/space/__init__.py +179 -292
  117. warp/fem/space/basis_space.py +522 -489
  118. warp/fem/space/collocated_function_space.py +100 -105
  119. warp/fem/space/dof_mapper.py +236 -236
  120. warp/fem/space/function_space.py +148 -145
  121. warp/fem/space/grid_2d_function_space.py +148 -267
  122. warp/fem/space/grid_3d_function_space.py +167 -306
  123. warp/fem/space/hexmesh_function_space.py +253 -352
  124. warp/fem/space/nanogrid_function_space.py +202 -0
  125. warp/fem/space/partition.py +350 -350
  126. warp/fem/space/quadmesh_2d_function_space.py +261 -369
  127. warp/fem/space/restriction.py +161 -160
  128. warp/fem/space/shape/__init__.py +90 -15
  129. warp/fem/space/shape/cube_shape_function.py +728 -738
  130. warp/fem/space/shape/shape_function.py +102 -103
  131. warp/fem/space/shape/square_shape_function.py +611 -611
  132. warp/fem/space/shape/tet_shape_function.py +565 -567
  133. warp/fem/space/shape/triangle_shape_function.py +429 -429
  134. warp/fem/space/tetmesh_function_space.py +224 -292
  135. warp/fem/space/topology.py +297 -295
  136. warp/fem/space/trimesh_2d_function_space.py +153 -221
  137. warp/fem/types.py +77 -77
  138. warp/fem/utils.py +495 -495
  139. warp/jax.py +166 -141
  140. warp/jax_experimental.py +341 -339
  141. warp/native/array.h +1081 -1025
  142. warp/native/builtin.h +1603 -1560
  143. warp/native/bvh.cpp +402 -398
  144. warp/native/bvh.cu +533 -525
  145. warp/native/bvh.h +430 -429
  146. warp/native/clang/clang.cpp +496 -464
  147. warp/native/crt.cpp +42 -32
  148. warp/native/crt.h +352 -335
  149. warp/native/cuda_crt.h +1049 -1049
  150. warp/native/cuda_util.cpp +549 -540
  151. warp/native/cuda_util.h +288 -203
  152. warp/native/cutlass_gemm.cpp +34 -34
  153. warp/native/cutlass_gemm.cu +372 -372
  154. warp/native/error.cpp +66 -66
  155. warp/native/error.h +27 -27
  156. warp/native/exports.h +187 -0
  157. warp/native/fabric.h +228 -228
  158. warp/native/hashgrid.cpp +301 -278
  159. warp/native/hashgrid.cu +78 -77
  160. warp/native/hashgrid.h +227 -227
  161. warp/native/initializer_array.h +32 -32
  162. warp/native/intersect.h +1204 -1204
  163. warp/native/intersect_adj.h +365 -365
  164. warp/native/intersect_tri.h +322 -322
  165. warp/native/marching.cpp +2 -2
  166. warp/native/marching.cu +497 -497
  167. warp/native/marching.h +2 -2
  168. warp/native/mat.h +1545 -1498
  169. warp/native/matnn.h +333 -333
  170. warp/native/mesh.cpp +203 -203
  171. warp/native/mesh.cu +292 -293
  172. warp/native/mesh.h +1887 -1887
  173. warp/native/nanovdb/GridHandle.h +366 -0
  174. warp/native/nanovdb/HostBuffer.h +590 -0
  175. warp/native/nanovdb/NanoVDB.h +6624 -4782
  176. warp/native/nanovdb/PNanoVDB.h +3390 -2553
  177. warp/native/noise.h +850 -850
  178. warp/native/quat.h +1112 -1085
  179. warp/native/rand.h +303 -299
  180. warp/native/range.h +108 -108
  181. warp/native/reduce.cpp +156 -156
  182. warp/native/reduce.cu +348 -348
  183. warp/native/runlength_encode.cpp +61 -61
  184. warp/native/runlength_encode.cu +46 -46
  185. warp/native/scan.cpp +30 -30
  186. warp/native/scan.cu +36 -36
  187. warp/native/scan.h +7 -7
  188. warp/native/solid_angle.h +442 -442
  189. warp/native/sort.cpp +94 -94
  190. warp/native/sort.cu +97 -97
  191. warp/native/sort.h +14 -14
  192. warp/native/sparse.cpp +337 -337
  193. warp/native/sparse.cu +544 -544
  194. warp/native/spatial.h +630 -630
  195. warp/native/svd.h +562 -562
  196. warp/native/temp_buffer.h +30 -30
  197. warp/native/vec.h +1177 -1133
  198. warp/native/volume.cpp +529 -297
  199. warp/native/volume.cu +58 -32
  200. warp/native/volume.h +960 -538
  201. warp/native/volume_builder.cu +446 -425
  202. warp/native/volume_builder.h +34 -19
  203. warp/native/volume_impl.h +61 -0
  204. warp/native/warp.cpp +1057 -1052
  205. warp/native/warp.cu +2949 -2828
  206. warp/native/warp.h +321 -305
  207. warp/optim/__init__.py +9 -9
  208. warp/optim/adam.py +120 -120
  209. warp/optim/linear.py +1104 -939
  210. warp/optim/sgd.py +104 -92
  211. warp/render/__init__.py +10 -10
  212. warp/render/render_opengl.py +3356 -3204
  213. warp/render/render_usd.py +768 -749
  214. warp/render/utils.py +152 -150
  215. warp/sim/__init__.py +52 -59
  216. warp/sim/articulation.py +685 -685
  217. warp/sim/collide.py +1594 -1590
  218. warp/sim/import_mjcf.py +489 -481
  219. warp/sim/import_snu.py +220 -221
  220. warp/sim/import_urdf.py +536 -516
  221. warp/sim/import_usd.py +887 -881
  222. warp/sim/inertia.py +316 -317
  223. warp/sim/integrator.py +234 -233
  224. warp/sim/integrator_euler.py +1956 -1956
  225. warp/sim/integrator_featherstone.py +1917 -1991
  226. warp/sim/integrator_xpbd.py +3288 -3312
  227. warp/sim/model.py +4473 -4314
  228. warp/sim/particles.py +113 -112
  229. warp/sim/render.py +417 -403
  230. warp/sim/utils.py +413 -410
  231. warp/sparse.py +1289 -1227
  232. warp/stubs.py +2192 -2469
  233. warp/tape.py +1162 -225
  234. warp/tests/__init__.py +1 -1
  235. warp/tests/__main__.py +4 -4
  236. warp/tests/assets/test_index_grid.nvdb +0 -0
  237. warp/tests/assets/torus.usda +105 -105
  238. warp/tests/aux_test_class_kernel.py +26 -26
  239. warp/tests/aux_test_compile_consts_dummy.py +10 -10
  240. warp/tests/aux_test_conditional_unequal_types_kernels.py +21 -21
  241. warp/tests/aux_test_dependent.py +20 -22
  242. warp/tests/aux_test_grad_customs.py +21 -23
  243. warp/tests/aux_test_reference.py +9 -11
  244. warp/tests/aux_test_reference_reference.py +8 -10
  245. warp/tests/aux_test_square.py +15 -17
  246. warp/tests/aux_test_unresolved_func.py +14 -14
  247. warp/tests/aux_test_unresolved_symbol.py +14 -14
  248. warp/tests/disabled_kinematics.py +237 -239
  249. warp/tests/run_coverage_serial.py +31 -31
  250. warp/tests/test_adam.py +155 -157
  251. warp/tests/test_arithmetic.py +1088 -1124
  252. warp/tests/test_array.py +2415 -2326
  253. warp/tests/test_array_reduce.py +148 -150
  254. warp/tests/test_async.py +666 -656
  255. warp/tests/test_atomic.py +139 -141
  256. warp/tests/test_bool.py +212 -149
  257. warp/tests/test_builtins_resolution.py +1290 -1292
  258. warp/tests/test_bvh.py +162 -171
  259. warp/tests/test_closest_point_edge_edge.py +227 -228
  260. warp/tests/test_codegen.py +562 -553
  261. warp/tests/test_compile_consts.py +217 -101
  262. warp/tests/test_conditional.py +244 -246
  263. warp/tests/test_copy.py +230 -215
  264. warp/tests/test_ctypes.py +630 -632
  265. warp/tests/test_dense.py +65 -67
  266. warp/tests/test_devices.py +89 -98
  267. warp/tests/test_dlpack.py +528 -529
  268. warp/tests/test_examples.py +403 -378
  269. warp/tests/test_fabricarray.py +952 -955
  270. warp/tests/test_fast_math.py +60 -54
  271. warp/tests/test_fem.py +1298 -1278
  272. warp/tests/test_fp16.py +128 -130
  273. warp/tests/test_func.py +336 -337
  274. warp/tests/test_generics.py +596 -571
  275. warp/tests/test_grad.py +885 -640
  276. warp/tests/test_grad_customs.py +331 -336
  277. warp/tests/test_hash_grid.py +208 -164
  278. warp/tests/test_import.py +37 -39
  279. warp/tests/test_indexedarray.py +1132 -1134
  280. warp/tests/test_intersect.py +65 -67
  281. warp/tests/test_jax.py +305 -307
  282. warp/tests/test_large.py +169 -164
  283. warp/tests/test_launch.py +352 -354
  284. warp/tests/test_lerp.py +217 -261
  285. warp/tests/test_linear_solvers.py +189 -171
  286. warp/tests/test_lvalue.py +419 -493
  287. warp/tests/test_marching_cubes.py +63 -65
  288. warp/tests/test_mat.py +1799 -1827
  289. warp/tests/test_mat_lite.py +113 -115
  290. warp/tests/test_mat_scalar_ops.py +2905 -2889
  291. warp/tests/test_math.py +124 -193
  292. warp/tests/test_matmul.py +498 -499
  293. warp/tests/test_matmul_lite.py +408 -410
  294. warp/tests/test_mempool.py +186 -190
  295. warp/tests/test_mesh.py +281 -324
  296. warp/tests/test_mesh_query_aabb.py +226 -241
  297. warp/tests/test_mesh_query_point.py +690 -702
  298. warp/tests/test_mesh_query_ray.py +290 -303
  299. warp/tests/test_mlp.py +274 -276
  300. warp/tests/test_model.py +108 -110
  301. warp/tests/test_module_hashing.py +111 -0
  302. warp/tests/test_modules_lite.py +36 -39
  303. warp/tests/test_multigpu.py +161 -163
  304. warp/tests/test_noise.py +244 -248
  305. warp/tests/test_operators.py +248 -250
  306. warp/tests/test_options.py +121 -125
  307. warp/tests/test_peer.py +131 -137
  308. warp/tests/test_pinned.py +76 -78
  309. warp/tests/test_print.py +52 -54
  310. warp/tests/test_quat.py +2084 -2086
  311. warp/tests/test_rand.py +324 -288
  312. warp/tests/test_reload.py +207 -217
  313. warp/tests/test_rounding.py +177 -179
  314. warp/tests/test_runlength_encode.py +188 -190
  315. warp/tests/test_sim_grad.py +241 -0
  316. warp/tests/test_sim_kinematics.py +89 -97
  317. warp/tests/test_smoothstep.py +166 -168
  318. warp/tests/test_snippet.py +303 -266
  319. warp/tests/test_sparse.py +466 -460
  320. warp/tests/test_spatial.py +2146 -2148
  321. warp/tests/test_special_values.py +362 -0
  322. warp/tests/test_streams.py +484 -473
  323. warp/tests/test_struct.py +708 -675
  324. warp/tests/test_tape.py +171 -148
  325. warp/tests/test_torch.py +741 -743
  326. warp/tests/test_transient_module.py +85 -87
  327. warp/tests/test_types.py +554 -659
  328. warp/tests/test_utils.py +488 -499
  329. warp/tests/test_vec.py +1262 -1268
  330. warp/tests/test_vec_lite.py +71 -73
  331. warp/tests/test_vec_scalar_ops.py +2097 -2099
  332. warp/tests/test_verify_fp.py +92 -94
  333. warp/tests/test_volume.py +961 -736
  334. warp/tests/test_volume_write.py +338 -265
  335. warp/tests/unittest_serial.py +38 -37
  336. warp/tests/unittest_suites.py +367 -359
  337. warp/tests/unittest_utils.py +434 -578
  338. warp/tests/unused_test_misc.py +69 -71
  339. warp/tests/walkthrough_debug.py +85 -85
  340. warp/thirdparty/appdirs.py +598 -598
  341. warp/thirdparty/dlpack.py +143 -143
  342. warp/thirdparty/unittest_parallel.py +563 -561
  343. warp/torch.py +321 -295
  344. warp/types.py +4941 -4450
  345. warp/utils.py +1008 -821
  346. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/LICENSE.md +126 -126
  347. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/METADATA +365 -400
  348. warp_lang-1.2.0.dist-info/RECORD +359 -0
  349. warp/examples/assets/cube.usda +0 -42
  350. warp/examples/assets/sphere.usda +0 -56
  351. warp/examples/assets/torus.usda +0 -105
  352. warp/examples/fem/example_convection_diffusion_dg0.py +0 -194
  353. warp/native/nanovdb/PNanoVDBWrite.h +0 -295
  354. warp_lang-1.0.2.dist-info/RECORD +0 -352
  355. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/WHEEL +0 -0
  356. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/top_level.txt +0 -0
warp/fem/integrate.py CHANGED
@@ -1,1615 +1,1684 @@
1
- from typing import List, Dict, Set, Optional, Any, Union
2
-
3
- import warp as wp
4
-
5
- import re
6
- import ast
7
-
8
- from warp.sparse import BsrMatrix, bsr_zeros, bsr_set_from_triplets, bsr_copy, bsr_assign
9
- from warp.types import type_length
10
- from warp.utils import array_cast
11
- from warp.codegen import get_annotations
12
-
13
- from warp.fem.domain import GeometryDomain
14
- from warp.fem.field import (
15
- TestField,
16
- TrialField,
17
- FieldLike,
18
- DiscreteField,
19
- FieldRestriction,
20
- make_restriction,
21
- )
22
- from warp.fem.quadrature import Quadrature, RegularQuadrature
23
- from warp.fem.operator import Operator, Integrand
24
- from warp.fem import cache
25
- from warp.fem.types import Domain, Field, Sample, DofIndex, NULL_DOF_INDEX, OUTSIDE, make_free_sample
26
-
27
-
28
- def _resolve_path(func, node):
29
- """
30
- Resolves variable and path from ast node/attribute (adapted from warp.codegen)
31
- """
32
-
33
- modules = []
34
-
35
- while isinstance(node, ast.Attribute):
36
- modules.append(node.attr)
37
- node = node.value
38
-
39
- if isinstance(node, ast.Name):
40
- modules.append(node.id)
41
-
42
- # reverse list since ast presents it backward order
43
- path = [*reversed(modules)]
44
-
45
- if len(path) == 0:
46
- return None, path
47
-
48
- # try and evaluate object path
49
- try:
50
- # Look up the closure info and append it to adj.func.__globals__
51
- # in case you want to define a kernel inside a function and refer
52
- # to variables you've declared inside that function:
53
- capturedvars = dict(
54
- zip(
55
- func.__code__.co_freevars,
56
- [c.cell_contents for c in (func.__closure__ or [])],
57
- )
58
- )
59
-
60
- vars_dict = {**func.__globals__, **capturedvars}
61
- func = eval(".".join(path), vars_dict)
62
- return func, path
63
- except (NameError, AttributeError):
64
- pass
65
-
66
- return None, path
67
-
68
-
69
- def _path_to_ast_attribute(name: str) -> ast.Attribute:
70
- path = name.split(".")
71
- path.reverse()
72
-
73
- node = ast.Name(id=path.pop(), ctx=ast.Load())
74
- while len(path):
75
- node = ast.Attribute(
76
- value=node,
77
- attr=path.pop(),
78
- ctx=ast.Load(),
79
- )
80
- return node
81
-
82
-
83
- class IntegrandTransformer(ast.NodeTransformer):
84
- def __init__(self, integrand: Integrand, field_args: Dict[str, FieldLike]):
85
- self._integrand = integrand
86
- self._field_args = field_args
87
-
88
- def visit_Call(self, call: ast.Call):
89
- call = self.generic_visit(call)
90
-
91
- callee = getattr(call.func, "id", None)
92
- if callee in self._field_args:
93
- # Shortcut for evaluating fields as f(x...)
94
- field = self._field_args[callee]
95
-
96
- arg_type = self._integrand.argspec.annotations[callee]
97
- operator = arg_type.call_operator
98
-
99
- call.func = ast.Attribute(
100
- value=_path_to_ast_attribute(f"{arg_type.__module__}.{arg_type.__qualname__}"),
101
- attr="call_operator",
102
- ctx=ast.Load(),
103
- )
104
- call.args = [ast.Name(id=callee, ctx=ast.Load())] + call.args
105
-
106
- self._replace_call_func(call, operator, field)
107
-
108
- return call
109
-
110
- func, _ = _resolve_path(self._integrand.func, call.func)
111
-
112
- if isinstance(func, Operator) and len(call.args) > 0:
113
- # Evaluating operators as op(field, x, ...)
114
- callee = getattr(call.args[0], "id", None)
115
- if callee in self._field_args:
116
- field = self._field_args[callee]
117
- self._replace_call_func(call, func, field)
118
-
119
- if isinstance(func, Integrand):
120
- key = self._translate_callee(func, call.args)
121
- call.func = ast.Attribute(
122
- value=call.func,
123
- attr=key,
124
- ctx=ast.Load(),
125
- )
126
-
127
- # print(ast.dump(call, indent=4))
128
-
129
- return call
130
-
131
- def _replace_call_func(self, call: ast.Call, operator: Operator, field: FieldLike):
132
- try:
133
- pointer = operator.resolver(field)
134
- setattr(operator, pointer.key, pointer)
135
- except AttributeError:
136
- raise ValueError(f"Operator {operator.func.__name__} is not defined for field {field.name}")
137
- call.func = ast.Attribute(value=call.func, attr=pointer.key, ctx=ast.Load())
138
-
139
- def _translate_callee(self, callee: Integrand, args: List[ast.AST]):
140
- # Get field types for call site arguments
141
- call_site_field_args = []
142
- for arg in args:
143
- name = getattr(arg, "id", None)
144
- if name in self._field_args:
145
- call_site_field_args.append(self._field_args[name])
146
-
147
- call_site_field_args.reverse()
148
-
149
- # Pass to callee in same order
150
- callee_field_args = {}
151
- for arg in callee.argspec.args:
152
- arg_type = callee.argspec.annotations[arg]
153
- if arg_type in (Field, Domain):
154
- callee_field_args[arg] = call_site_field_args.pop()
155
-
156
- return _translate_integrand(callee, callee_field_args).key
157
-
158
-
159
- def _translate_integrand(integrand: Integrand, field_args: Dict[str, FieldLike]) -> wp.Function:
160
- # Specialize field argument types
161
- argspec = integrand.argspec
162
- annotations = {}
163
- for arg in argspec.args:
164
- arg_type = argspec.annotations[arg]
165
- if arg_type == Field:
166
- annotations[arg] = field_args[arg].ElementEvalArg
167
- elif arg_type == Domain:
168
- annotations[arg] = field_args[arg].ElementArg
169
- else:
170
- annotations[arg] = arg_type
171
-
172
- # Transform field evaluation calls
173
- transformer = IntegrandTransformer(integrand, field_args)
174
-
175
- suffix = "_".join([f.name for f in field_args.values()])
176
-
177
- func = cache.get_integrand_function(
178
- integrand=integrand,
179
- suffix=suffix,
180
- annotations=annotations,
181
- code_transformers=[transformer],
182
- )
183
-
184
- key = func.key
185
- setattr(integrand, key, integrand.module.functions[key])
186
-
187
- return getattr(integrand, key)
188
-
189
-
190
- def _get_integrand_field_arguments(
191
- integrand: Integrand,
192
- fields: Dict[str, FieldLike],
193
- domain: GeometryDomain = None,
194
- ):
195
- # parse argument types
196
- field_args = {}
197
- value_args = {}
198
-
199
- domain_name = None
200
- sample_name = None
201
-
202
- argspec = integrand.argspec
203
- for arg in argspec.args:
204
- arg_type = argspec.annotations[arg]
205
- if arg_type == Field:
206
- if arg not in fields:
207
- raise ValueError(f"Missing field for argument '{arg}'")
208
- field_args[arg] = fields[arg]
209
- elif arg_type == Domain:
210
- domain_name = arg
211
- field_args[arg] = domain
212
- elif arg_type == Sample:
213
- sample_name = arg
214
- else:
215
- value_args[arg] = arg_type
216
-
217
- return field_args, value_args, domain_name, sample_name
218
-
219
-
220
- def _get_test_and_trial_fields(
221
- fields: Dict[str, FieldLike],
222
- ):
223
- test = None
224
- trial = None
225
- test_name = None
226
- trial_name = None
227
-
228
- for name, field in fields.items():
229
- if isinstance(field, TestField):
230
- if test is not None:
231
- raise ValueError("Duplicate test field argument")
232
- test = field
233
- test_name = name
234
- elif isinstance(field, TrialField):
235
- if trial is not None:
236
- raise ValueError("Duplicate test field argument")
237
- trial = field
238
- trial_name = name
239
-
240
- if trial is not None:
241
- if test is None:
242
- raise ValueError("A trial field cannot be provided without a test field")
243
-
244
- if test.domain != trial.domain:
245
- raise ValueError("Incompatible test and trial domains")
246
-
247
- return test, test_name, trial, trial_name
248
-
249
-
250
- def _gen_field_struct(field_args: Dict[str, FieldLike]):
251
- class Fields:
252
- pass
253
-
254
- annotations = get_annotations(Fields)
255
-
256
- for name, arg in field_args.items():
257
- if isinstance(arg, GeometryDomain):
258
- continue
259
- setattr(Fields, name, arg.EvalArg())
260
- annotations[name] = arg.EvalArg
261
-
262
- try:
263
- Fields.__annotations__ = annotations
264
- except AttributeError:
265
- setattr(Fields.__dict__, "__annotations__", annotations)
266
-
267
- suffix = "_".join([f"{name}_{arg_struct.cls.__qualname__}" for name, arg_struct in annotations.items()])
268
-
269
- return cache.get_struct(Fields, suffix=suffix)
270
-
271
-
272
- def _gen_value_struct(value_args: Dict[str, type]):
273
- class Values:
274
- pass
275
-
276
- annotations = get_annotations(Values)
277
-
278
- for name, arg_type in value_args.items():
279
- setattr(Values, name, None)
280
- annotations[name] = arg_type
281
-
282
- def arg_type_name(arg_type):
283
- if isinstance(arg_type, wp.codegen.Struct):
284
- return arg_type_name(arg_type.cls)
285
- return getattr(arg_type, "__name__", str(arg_type))
286
-
287
- def arg_type_name(arg_type):
288
- if isinstance(arg_type, wp.codegen.Struct):
289
- return arg_type_name(arg_type.cls)
290
- return getattr(arg_type, "__name__", str(arg_type))
291
-
292
- try:
293
- Values.__annotations__ = annotations
294
- except AttributeError:
295
- setattr(Values.__dict__, "__annotations__", annotations)
296
-
297
- suffix = "_".join([f"{name}_{arg_type_name(arg_type)}" for name, arg_type in annotations.items()])
298
-
299
- return cache.get_struct(Values, suffix=suffix)
300
-
301
-
302
- def _get_trial_arg():
303
- pass
304
-
305
-
306
- def _get_test_arg():
307
- pass
308
-
309
-
310
- class _FieldWrappers:
311
- pass
312
-
313
-
314
- def _register_integrand_field_wrappers(integrand_func: wp.Function, fields: Dict[str, FieldLike]):
315
- integrand_func._field_wrappers = _FieldWrappers()
316
- for name, field in fields.items():
317
- setattr(integrand_func._field_wrappers, name, field.ElementEvalArg)
318
-
319
-
320
- class PassFieldArgsToIntegrand(ast.NodeTransformer):
321
- def __init__(
322
- self,
323
- arg_names: List[str],
324
- field_args: Set[str],
325
- value_args: Set[str],
326
- sample_name: str,
327
- domain_name: str,
328
- test_name: str = None,
329
- trial_name: str = None,
330
- func_name: str = "integrand_func",
331
- fields_var_name: str = "fields",
332
- values_var_name: str = "values",
333
- domain_var_name: str = "domain_arg",
334
- sample_var_name: str = "sample",
335
- field_wrappers_attr: str = "_field_wrappers",
336
- ):
337
- self._arg_names = arg_names
338
- self._field_args = field_args
339
- self._value_args = value_args
340
- self._domain_name = domain_name
341
- self._sample_name = sample_name
342
- self._func_name = func_name
343
- self._test_name = test_name
344
- self._trial_name = trial_name
345
- self._fields_var_name = fields_var_name
346
- self._values_var_name = values_var_name
347
- self._domain_var_name = domain_var_name
348
- self._sample_var_name = sample_var_name
349
- self._field_wrappers_attr = field_wrappers_attr
350
-
351
- def visit_Call(self, call: ast.Call):
352
- call = self.generic_visit(call)
353
-
354
- callee = getattr(call.func, "id", None)
355
-
356
- if callee == self._func_name:
357
- # Replace function arguments with ours generated structs
358
- call.args.clear()
359
- for arg in self._arg_names:
360
- if arg == self._domain_name:
361
- call.args.append(
362
- ast.Name(id=self._domain_var_name, ctx=ast.Load()),
363
- )
364
- elif arg == self._sample_name:
365
- call.args.append(
366
- ast.Name(id=self._sample_var_name, ctx=ast.Load()),
367
- )
368
- elif arg in self._field_args:
369
- call.args.append(
370
- ast.Call(
371
- func=ast.Attribute(
372
- value=ast.Attribute(
373
- value=ast.Name(id=self._func_name, ctx=ast.Load()),
374
- attr=self._field_wrappers_attr,
375
- ctx=ast.Load(),
376
- ),
377
- attr=arg,
378
- ctx=ast.Load(),
379
- ),
380
- args=[
381
- ast.Name(id=self._domain_var_name, ctx=ast.Load()),
382
- ast.Attribute(
383
- value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
384
- attr=arg,
385
- ctx=ast.Load(),
386
- ),
387
- ],
388
- keywords=[],
389
- )
390
- )
391
- elif arg in self._value_args:
392
- call.args.append(
393
- ast.Attribute(
394
- value=ast.Name(id=self._values_var_name, ctx=ast.Load()),
395
- attr=arg,
396
- ctx=ast.Load(),
397
- )
398
- )
399
- else:
400
- raise RuntimeError(f"Unhandled argument {arg}")
401
- # print(ast.dump(call, indent=4))
402
- elif callee == _get_test_arg.__name__:
403
- # print(ast.dump(call, indent=4))
404
- call = ast.Attribute(
405
- value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
406
- attr=self._test_name,
407
- ctx=ast.Load(),
408
- )
409
- elif callee == _get_trial_arg.__name__:
410
- # print(ast.dump(call, indent=4))
411
- call = ast.Attribute(
412
- value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
413
- attr=self._trial_name,
414
- ctx=ast.Load(),
415
- )
416
-
417
- return call
418
-
419
-
420
- def get_integrate_constant_kernel(
421
- integrand_func: wp.Function,
422
- domain: GeometryDomain,
423
- quadrature: Quadrature,
424
- FieldStruct: wp.codegen.Struct,
425
- ValueStruct: wp.codegen.Struct,
426
- accumulate_dtype,
427
- ):
428
- def integrate_kernel_fn(
429
- qp_arg: quadrature.Arg,
430
- domain_arg: domain.ElementArg,
431
- domain_index_arg: domain.ElementIndexArg,
432
- fields: FieldStruct,
433
- values: ValueStruct,
434
- result: wp.array(dtype=accumulate_dtype),
435
- ):
436
- element_index = domain.element_index(domain_index_arg, wp.tid())
437
- elem_sum = accumulate_dtype(0.0)
438
-
439
- test_dof_index = NULL_DOF_INDEX
440
- trial_dof_index = NULL_DOF_INDEX
441
-
442
- qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
443
- for k in range(qp_point_count):
444
- qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
445
- coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
446
- qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
447
-
448
- sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
449
- vol = domain.element_measure(domain_arg, sample)
450
-
451
- val = integrand_func(sample, fields, values)
452
-
453
- elem_sum += accumulate_dtype(qp_weight * vol * val)
454
-
455
- wp.atomic_add(result, 0, elem_sum)
456
-
457
- return integrate_kernel_fn
458
-
459
-
460
- def get_integrate_linear_kernel(
461
- integrand_func: wp.Function,
462
- domain: GeometryDomain,
463
- quadrature: Quadrature,
464
- FieldStruct: wp.codegen.Struct,
465
- ValueStruct: wp.codegen.Struct,
466
- test: TestField,
467
- output_dtype,
468
- accumulate_dtype,
469
- ):
470
- def integrate_kernel_fn(
471
- qp_arg: quadrature.Arg,
472
- domain_arg: domain.ElementArg,
473
- domain_index_arg: domain.ElementIndexArg,
474
- test_arg: test.space_restriction.NodeArg,
475
- fields: FieldStruct,
476
- values: ValueStruct,
477
- result: wp.array2d(dtype=output_dtype),
478
- ):
479
- local_node_index, test_dof = wp.tid()
480
- node_index = test.space_restriction.node_partition_index(test_arg, local_node_index)
481
- element_count = test.space_restriction.node_element_count(test_arg, local_node_index)
482
-
483
- trial_dof_index = NULL_DOF_INDEX
484
-
485
- val_sum = accumulate_dtype(0.0)
486
-
487
- for n in range(element_count):
488
- node_element_index = test.space_restriction.node_element_index(test_arg, local_node_index, n)
489
- element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
490
-
491
- test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
492
-
493
- qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
494
- for k in range(qp_point_count):
495
- qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
496
- qp_coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
497
- qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
498
-
499
- vol = domain.element_measure(domain_arg, make_free_sample(element_index, qp_coords))
500
-
501
- sample = Sample(element_index, qp_coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
502
- val = integrand_func(sample, fields, values)
503
-
504
- val_sum += accumulate_dtype(qp_weight * vol * val)
505
-
506
- result[node_index, test_dof] = output_dtype(val_sum)
507
-
508
- return integrate_kernel_fn
509
-
510
-
511
- def get_integrate_linear_nodal_kernel(
512
- integrand_func: wp.Function,
513
- domain: GeometryDomain,
514
- FieldStruct: wp.codegen.Struct,
515
- ValueStruct: wp.codegen.Struct,
516
- test: TestField,
517
- output_dtype,
518
- accumulate_dtype,
519
- ):
520
- def integrate_kernel_fn(
521
- domain_arg: domain.ElementArg,
522
- domain_index_arg: domain.ElementIndexArg,
523
- test_restriction_arg: test.space_restriction.NodeArg,
524
- fields: FieldStruct,
525
- values: ValueStruct,
526
- result: wp.array2d(dtype=output_dtype),
527
- ):
528
- local_node_index, dof = wp.tid()
529
-
530
- node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
531
- element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
532
-
533
- trial_dof_index = NULL_DOF_INDEX
534
-
535
- val_sum = accumulate_dtype(0.0)
536
-
537
- for n in range(element_count):
538
- node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
539
- element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
540
-
541
- coords = test.space.node_coords_in_element(
542
- domain_arg,
543
- _get_test_arg(),
544
- element_index,
545
- node_element_index.node_index_in_element,
546
- )
547
-
548
- if coords[0] != OUTSIDE:
549
- node_weight = test.space.node_quadrature_weight(
550
- domain_arg,
551
- _get_test_arg(),
552
- element_index,
553
- node_element_index.node_index_in_element,
554
- )
555
-
556
- test_dof_index = DofIndex(node_element_index.node_index_in_element, dof)
557
-
558
- sample = Sample(
559
- element_index,
560
- coords,
561
- node_index,
562
- node_weight,
563
- test_dof_index,
564
- trial_dof_index,
565
- )
566
- vol = domain.element_measure(domain_arg, sample)
567
- val = integrand_func(sample, fields, values)
568
-
569
- val_sum += accumulate_dtype(node_weight * vol * val)
570
-
571
- result[node_index, dof] = output_dtype(val_sum)
572
-
573
- return integrate_kernel_fn
574
-
575
-
576
- def get_integrate_bilinear_kernel(
577
- integrand_func: wp.Function,
578
- domain: GeometryDomain,
579
- quadrature: Quadrature,
580
- FieldStruct: wp.codegen.Struct,
581
- ValueStruct: wp.codegen.Struct,
582
- test: TestField,
583
- trial: TrialField,
584
- output_dtype,
585
- accumulate_dtype,
586
- ):
587
- NODES_PER_ELEMENT = trial.space.topology.NODES_PER_ELEMENT
588
-
589
- def integrate_kernel_fn(
590
- qp_arg: quadrature.Arg,
591
- domain_arg: domain.ElementArg,
592
- domain_index_arg: domain.ElementIndexArg,
593
- test_arg: test.space_restriction.NodeArg,
594
- trial_partition_arg: trial.space_partition.PartitionArg,
595
- trial_topology_arg: trial.space_partition.space_topology.TopologyArg,
596
- fields: FieldStruct,
597
- values: ValueStruct,
598
- row_offsets: wp.array(dtype=int),
599
- triplet_rows: wp.array(dtype=int),
600
- triplet_cols: wp.array(dtype=int),
601
- triplet_values: wp.array3d(dtype=output_dtype),
602
- ):
603
- test_local_node_index, trial_node, test_dof, trial_dof = wp.tid()
604
-
605
- element_count = test.space_restriction.node_element_count(test_arg, test_local_node_index)
606
- test_node_index = test.space_restriction.node_partition_index(test_arg, test_local_node_index)
607
-
608
- trial_dof_index = DofIndex(trial_node, trial_dof)
609
-
610
- for element in range(element_count):
611
- test_element_index = test.space_restriction.node_element_index(test_arg, test_local_node_index, element)
612
- element_index = domain.element_index(domain_index_arg, test_element_index.domain_element_index)
613
- qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
614
-
615
- test_dof_index = DofIndex(
616
- test_element_index.node_index_in_element,
617
- test_dof,
618
- )
619
-
620
- val_sum = accumulate_dtype(0.0)
621
-
622
- for k in range(qp_point_count):
623
- qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
624
- coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
625
-
626
- qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
627
- vol = domain.element_measure(domain_arg, make_free_sample(element_index, coords))
628
-
629
- sample = Sample(
630
- element_index,
631
- coords,
632
- qp_index,
633
- qp_weight,
634
- test_dof_index,
635
- trial_dof_index,
636
- )
637
- val = integrand_func(sample, fields, values)
638
- val_sum += accumulate_dtype(qp_weight * vol * val)
639
-
640
- block_offset = (row_offsets[test_node_index] + element) * NODES_PER_ELEMENT + trial_node
641
- triplet_values[block_offset, test_dof, trial_dof] = output_dtype(val_sum)
642
-
643
- # Set row and column indices
644
- if test_dof == 0 and trial_dof == 0:
645
- trial_node_index = trial.space_partition.partition_node_index(
646
- trial_partition_arg,
647
- trial.space.topology.element_node_index(domain_arg, trial_topology_arg, element_index, trial_node),
648
- )
649
- triplet_rows[block_offset] = test_node_index
650
- triplet_cols[block_offset] = trial_node_index
651
-
652
- return integrate_kernel_fn
653
-
654
-
655
- def get_integrate_bilinear_nodal_kernel(
656
- integrand_func: wp.Function,
657
- domain: GeometryDomain,
658
- FieldStruct: wp.codegen.Struct,
659
- ValueStruct: wp.codegen.Struct,
660
- test: TestField,
661
- output_dtype,
662
- accumulate_dtype,
663
- ):
664
- def integrate_kernel_fn(
665
- domain_arg: domain.ElementArg,
666
- domain_index_arg: domain.ElementIndexArg,
667
- test_restriction_arg: test.space_restriction.NodeArg,
668
- fields: FieldStruct,
669
- values: ValueStruct,
670
- triplet_rows: wp.array(dtype=int),
671
- triplet_cols: wp.array(dtype=int),
672
- triplet_values: wp.array3d(dtype=output_dtype),
673
- ):
674
- local_node_index, test_dof, trial_dof = wp.tid()
675
-
676
- element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
677
- node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
678
-
679
- val_sum = accumulate_dtype(0.0)
680
-
681
- for n in range(element_count):
682
- node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
683
- element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
684
-
685
- coords = test.space.node_coords_in_element(
686
- domain_arg,
687
- _get_test_arg(),
688
- element_index,
689
- node_element_index.node_index_in_element,
690
- )
691
-
692
- if coords[0] != OUTSIDE:
693
- node_weight = test.space.node_quadrature_weight(
694
- domain_arg,
695
- _get_test_arg(),
696
- element_index,
697
- node_element_index.node_index_in_element,
698
- )
699
-
700
- test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
701
- trial_dof_index = DofIndex(node_element_index.node_index_in_element, trial_dof)
702
-
703
- sample = Sample(
704
- element_index,
705
- coords,
706
- node_index,
707
- node_weight,
708
- test_dof_index,
709
- trial_dof_index,
710
- )
711
- vol = domain.element_measure(domain_arg, sample)
712
- val = integrand_func(sample, fields, values)
713
-
714
- val_sum += accumulate_dtype(node_weight * vol * val)
715
-
716
- triplet_values[local_node_index, test_dof, trial_dof] = output_dtype(val_sum)
717
- triplet_rows[local_node_index] = node_index
718
- triplet_cols[local_node_index] = node_index
719
-
720
- return integrate_kernel_fn
721
-
722
-
723
- def _generate_integrate_kernel(
724
- integrand: Integrand,
725
- domain: GeometryDomain,
726
- nodal: bool,
727
- quadrature: Quadrature,
728
- test: Optional[TestField],
729
- test_name: str,
730
- trial: Optional[TrialField],
731
- trial_name: str,
732
- fields: Dict[str, FieldLike],
733
- output_dtype: type,
734
- accumulate_dtype: type,
735
- kernel_options: Dict[str, Any] = {},
736
- ) -> wp.Kernel:
737
- output_dtype = wp.types.type_scalar_type(output_dtype)
738
-
739
- # Extract field arguments from integrand
740
- field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
741
- integrand, fields=fields, domain=domain
742
- )
743
-
744
- FieldStruct = _gen_field_struct(field_args)
745
- ValueStruct = _gen_value_struct(value_args)
746
-
747
- # Check if kernel exist in cache
748
- kernel_suffix = f"_itg_{wp.types.type_typestr(output_dtype)}{wp.types.type_typestr(accumulate_dtype)}_{domain.name}_{FieldStruct.key}"
749
- if nodal:
750
- kernel_suffix += "_nodal"
751
- else:
752
- kernel_suffix += quadrature.name
753
-
754
- if test:
755
- kernel_suffix += f"_test_{test.space_partition.name}_{test.space.name}"
756
- if trial:
757
- kernel_suffix += f"_trial_{trial.space_partition.name}_{trial.space.name}"
758
-
759
- kernel = cache.get_integrand_kernel(
760
- integrand=integrand,
761
- suffix=kernel_suffix,
762
- )
763
- if kernel is not None:
764
- return kernel, FieldStruct, ValueStruct
765
-
766
- # Not found in cache, transform integrand and generate kernel
767
-
768
- integrand_func = _translate_integrand(
769
- integrand,
770
- field_args,
771
- )
772
-
773
- _register_integrand_field_wrappers(integrand_func, fields)
774
-
775
- if test is None and trial is None:
776
- integrate_kernel_fn = get_integrate_constant_kernel(
777
- integrand_func,
778
- domain,
779
- quadrature,
780
- FieldStruct,
781
- ValueStruct,
782
- accumulate_dtype=accumulate_dtype,
783
- )
784
- elif trial is None:
785
- if nodal:
786
- integrate_kernel_fn = get_integrate_linear_nodal_kernel(
787
- integrand_func,
788
- domain,
789
- FieldStruct,
790
- ValueStruct,
791
- test=test,
792
- output_dtype=output_dtype,
793
- accumulate_dtype=accumulate_dtype,
794
- )
795
- else:
796
- integrate_kernel_fn = get_integrate_linear_kernel(
797
- integrand_func,
798
- domain,
799
- quadrature,
800
- FieldStruct,
801
- ValueStruct,
802
- test=test,
803
- output_dtype=output_dtype,
804
- accumulate_dtype=accumulate_dtype,
805
- )
806
- else:
807
- if nodal:
808
- integrate_kernel_fn = get_integrate_bilinear_nodal_kernel(
809
- integrand_func,
810
- domain,
811
- FieldStruct,
812
- ValueStruct,
813
- test=test,
814
- output_dtype=output_dtype,
815
- accumulate_dtype=accumulate_dtype,
816
- )
817
- else:
818
- integrate_kernel_fn = get_integrate_bilinear_kernel(
819
- integrand_func,
820
- domain,
821
- quadrature,
822
- FieldStruct,
823
- ValueStruct,
824
- test=test,
825
- trial=trial,
826
- output_dtype=output_dtype,
827
- accumulate_dtype=accumulate_dtype,
828
- )
829
-
830
- kernel = cache.get_integrand_kernel(
831
- integrand=integrand,
832
- kernel_fn=integrate_kernel_fn,
833
- suffix=kernel_suffix,
834
- kernel_options=kernel_options,
835
- code_transformers=[
836
- PassFieldArgsToIntegrand(
837
- arg_names=integrand.argspec.args,
838
- field_args=field_args.keys(),
839
- value_args=value_args.keys(),
840
- sample_name=sample_name,
841
- domain_name=domain_name,
842
- test_name=test_name,
843
- trial_name=trial_name,
844
- )
845
- ],
846
- )
847
-
848
- return kernel, FieldStruct, ValueStruct
849
-
850
-
851
- def _launch_integrate_kernel(
852
- kernel: wp.Kernel,
853
- FieldStruct: wp.codegen.Struct,
854
- ValueStruct: wp.codegen.Struct,
855
- domain: GeometryDomain,
856
- nodal: bool,
857
- quadrature: Quadrature,
858
- test: Optional[TestField],
859
- trial: Optional[TrialField],
860
- fields: Dict[str, FieldLike],
861
- values: Dict[str, Any],
862
- accumulate_dtype: type,
863
- temporary_store: Optional[cache.TemporaryStore],
864
- output_dtype: type,
865
- output: Optional[Union[wp.array, BsrMatrix]],
866
- device,
867
- ):
868
- # Set-up launch arguments
869
- domain_elt_arg = domain.element_arg_value(device=device)
870
- domain_elt_index_arg = domain.element_index_arg_value(device=device)
871
-
872
- if quadrature is not None:
873
- qp_arg = quadrature.arg_value(device=device)
874
-
875
- field_arg_values = FieldStruct()
876
- for k, v in fields.items():
877
- setattr(field_arg_values, k, v.eval_arg_value(device=device))
878
-
879
- value_struct_values = ValueStruct()
880
- for k, v in values.items():
881
- setattr(value_struct_values, k, v)
882
-
883
- # Constant form
884
- if test is None and trial is None:
885
- if output is not None and output.dtype == accumulate_dtype:
886
- if output.size < 1:
887
- raise RuntimeError("Output array must be of size at least 1")
888
- accumulate_array = output
889
- else:
890
- accumulate_temporary = cache.borrow_temporary(
891
- shape=(1),
892
- device=device,
893
- dtype=accumulate_dtype,
894
- temporary_store=temporary_store,
895
- requires_grad=output is not None and output.requires_grad,
896
- )
897
- accumulate_array = accumulate_temporary.array
898
-
899
- accumulate_array.zero_()
900
- wp.launch(
901
- kernel=kernel,
902
- dim=domain.element_count(),
903
- inputs=[
904
- qp_arg,
905
- domain_elt_arg,
906
- domain_elt_index_arg,
907
- field_arg_values,
908
- value_struct_values,
909
- accumulate_array,
910
- ],
911
- device=device,
912
- )
913
-
914
- if output == accumulate_array:
915
- return output
916
- elif output is None:
917
- return accumulate_array.numpy()[0]
918
- else:
919
- array_cast(in_array=accumulate_array, out_array=output)
920
- return output
921
-
922
- test_arg = test.space_restriction.node_arg(device=device)
923
-
924
- # Linear form
925
- if trial is None:
926
- # If an output array is provided with the correct type, accumulate directly into it
927
- # Otherwise, grab a temporary array
928
- if output is None:
929
- if type_length(output_dtype) == test.space.VALUE_DOF_COUNT:
930
- output_shape = (test.space_partition.node_count(),)
931
- elif type_length(output_dtype) == 1:
932
- output_shape = (test.space_partition.node_count(), test.space.VALUE_DOF_COUNT)
933
- else:
934
- raise RuntimeError(
935
- f"Incompatible output type {wp.types.type_repr(output_dtype)}, must be scalar or vector of length {test.space.VALUE_DOF_COUNT}"
936
- )
937
-
938
- output_temporary = cache.borrow_temporary(
939
- temporary_store=temporary_store,
940
- shape=output_shape,
941
- dtype=output_dtype,
942
- device=device,
943
- )
944
-
945
- output = output_temporary.array
946
-
947
- else:
948
- output_temporary = None
949
-
950
- if output.shape[0] < test.space_partition.node_count():
951
- raise RuntimeError(f"Output array must have at least {test.space_partition.node_count()} rows")
952
-
953
- output_dtype = output.dtype
954
- if type_length(output_dtype) != test.space.VALUE_DOF_COUNT:
955
- if type_length(output_dtype) != 1:
956
- raise RuntimeError(
957
- f"Incompatible output type {wp.types.type_repr(output_dtype)}, must be scalar or vector of length {test.space.VALUE_DOF_COUNT}"
958
- )
959
- if output.ndim != 2 and output.shape[1] != test.space.VALUE_DOF_COUNT:
960
- raise RuntimeError(
961
- f"Incompatible output array shape, last dimension must be of size {test.space.VALUE_DOF_COUNT}"
962
- )
963
-
964
- # Launch the integration on the kernel on a 2d scalar view of the actual array
965
- output.zero_()
966
-
967
- def as_2d_array(array):
968
- return wp.array(
969
- data=None,
970
- ptr=array.ptr,
971
- capacity=array.capacity,
972
- device=array.device,
973
- shape=(test.space_partition.node_count(), test.space.VALUE_DOF_COUNT),
974
- dtype=wp.types.type_scalar_type(output_dtype),
975
- grad=None if array.grad is None else as_2d_array(array.grad),
976
- )
977
-
978
- output_view = output if output.ndim == 2 else as_2d_array(output)
979
-
980
- if nodal:
981
- wp.launch(
982
- kernel=kernel,
983
- dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
984
- inputs=[
985
- domain_elt_arg,
986
- domain_elt_index_arg,
987
- test_arg,
988
- field_arg_values,
989
- value_struct_values,
990
- output_view,
991
- ],
992
- device=device,
993
- )
994
- else:
995
- wp.launch(
996
- kernel=kernel,
997
- dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
998
- inputs=[
999
- qp_arg,
1000
- domain_elt_arg,
1001
- domain_elt_index_arg,
1002
- test_arg,
1003
- field_arg_values,
1004
- value_struct_values,
1005
- output_view,
1006
- ],
1007
- device=device,
1008
- )
1009
-
1010
- if output_temporary is not None:
1011
- return output_temporary.detach()
1012
-
1013
- return output
1014
-
1015
- # Bilinear form
1016
-
1017
- if test.space.VALUE_DOF_COUNT == 1 and trial.space.VALUE_DOF_COUNT == 1:
1018
- block_type = output_dtype
1019
- else:
1020
- block_type = cache.cached_mat_type(
1021
- shape=(test.space.VALUE_DOF_COUNT, trial.space.VALUE_DOF_COUNT), dtype=output_dtype
1022
- )
1023
-
1024
- if nodal:
1025
- nnz = test.space_restriction.node_count()
1026
- else:
1027
- nnz = test.space_restriction.total_node_element_count() * trial.space.topology.NODES_PER_ELEMENT
1028
-
1029
- triplet_rows_temp = cache.borrow_temporary(temporary_store, shape=(nnz,), dtype=int, device=device)
1030
- triplet_cols_temp = cache.borrow_temporary(temporary_store, shape=(nnz,), dtype=int, device=device)
1031
- triplet_values_temp = cache.borrow_temporary(
1032
- temporary_store,
1033
- shape=(
1034
- nnz,
1035
- test.space.VALUE_DOF_COUNT,
1036
- trial.space.VALUE_DOF_COUNT,
1037
- ),
1038
- dtype=output_dtype,
1039
- device=device,
1040
- )
1041
- triplet_cols = triplet_cols_temp.array
1042
- triplet_rows = triplet_rows_temp.array
1043
- triplet_values = triplet_values_temp.array
1044
-
1045
- triplet_values.zero_()
1046
-
1047
- if nodal:
1048
- wp.launch(
1049
- kernel=kernel,
1050
- dim=triplet_values.shape,
1051
- inputs=[
1052
- domain_elt_arg,
1053
- domain_elt_index_arg,
1054
- test_arg,
1055
- field_arg_values,
1056
- value_struct_values,
1057
- triplet_rows,
1058
- triplet_cols,
1059
- triplet_values,
1060
- ],
1061
- device=device,
1062
- )
1063
-
1064
- else:
1065
- offsets = test.space_restriction.partition_element_offsets()
1066
-
1067
- trial_partition_arg = trial.space_partition.partition_arg_value(device)
1068
- trial_topology_arg = trial.space_partition.space_topology.topo_arg_value(device)
1069
- wp.launch(
1070
- kernel=kernel,
1071
- dim=(
1072
- test.space_restriction.node_count(),
1073
- trial.space.topology.NODES_PER_ELEMENT,
1074
- test.space.VALUE_DOF_COUNT,
1075
- trial.space.VALUE_DOF_COUNT,
1076
- ),
1077
- inputs=[
1078
- qp_arg,
1079
- domain_elt_arg,
1080
- domain_elt_index_arg,
1081
- test_arg,
1082
- trial_partition_arg,
1083
- trial_topology_arg,
1084
- field_arg_values,
1085
- value_struct_values,
1086
- offsets,
1087
- triplet_rows,
1088
- triplet_cols,
1089
- triplet_values,
1090
- ],
1091
- device=device,
1092
- )
1093
-
1094
- if output is not None:
1095
- if output.nrow != test.space_partition.node_count() or output.ncol != trial.space_partition.node_count():
1096
- raise RuntimeError(
1097
- f"Output matrix must have {test.space_partition.node_count()} rows and {trial.space_partition.node_count()} columns of blocks"
1098
- )
1099
-
1100
- else:
1101
- output = bsr_zeros(
1102
- rows_of_blocks=test.space_partition.node_count(),
1103
- cols_of_blocks=trial.space_partition.node_count(),
1104
- block_type=block_type,
1105
- device=device,
1106
- )
1107
-
1108
- bsr_set_from_triplets(output, triplet_rows, triplet_cols, triplet_values)
1109
-
1110
- # Do not wait for garbage collection
1111
- triplet_values_temp.release()
1112
- triplet_rows_temp.release()
1113
- triplet_cols_temp.release()
1114
-
1115
- return output
1116
-
1117
-
1118
- def integrate(
1119
- integrand: Integrand,
1120
- domain: Optional[GeometryDomain] = None,
1121
- quadrature: Optional[Quadrature] = None,
1122
- nodal: bool = False,
1123
- fields: Dict[str, FieldLike] = {},
1124
- values: Dict[str, Any] = {},
1125
- accumulate_dtype: type = wp.float64,
1126
- output_dtype: Optional[type] = None,
1127
- output: Optional[Union[BsrMatrix, wp.array]] = None,
1128
- device=None,
1129
- temporary_store: Optional[cache.TemporaryStore] = None,
1130
- kernel_options: Dict[str, Any] = {},
1131
- ):
1132
- """
1133
- Integrates a constant, linear or bilinear form, and returns a scalar, array, or sparse matrix, respectively.
1134
-
1135
- Args:
1136
- integrand: Form to be integrated, must have :func:`integrand` decorator
1137
- domain: Integration domain. If None, deduced from fields
1138
- quadrature: Quadrature formula. If None, deduced from domain and fields degree.
1139
- nodal: For linear or bilinear form only, use the test function nodes as the quadrature points. Assumes Lagrange interpolation functions are used, and no differential or DG operator is evaluated on the test or trial functions.
1140
- fields: Discrete, test, and trial fields to be passed to the integrand. Keys in the dictionary must match integrand parameter names.
1141
- values: Additional variable values to be passed to the integrand, can be of any type accepted by warp kernel launches. Keys in the dictionary must match integrand parameter names.
1142
- temporary_store: shared pool from which to allocate temporary arrays
1143
- accumulate_dtype: Scalar type to be used for accumulating integration samples
1144
- output: Sparse matrix or warp array into which to store the result of the integration
1145
- output_dtype: Scalar type for returned results in `output` is not provided. If None, defaults to `accumulate_dtype`
1146
- device: Device on which to perform the integration
1147
- kernel_options: Overloaded options to be passed to the kernel builder (e.g, ``{"enable_backward": True}``)
1148
- """
1149
- if not isinstance(integrand, Integrand):
1150
- raise ValueError("integrand must be tagged with @warp.fem.integrand decorator")
1151
-
1152
- test, test_name, trial, trial_name = _get_test_and_trial_fields(fields)
1153
-
1154
- if domain is None:
1155
- if quadrature is not None:
1156
- domain = quadrature.domain
1157
- elif test is not None:
1158
- domain = test.domain
1159
-
1160
- if domain is None:
1161
- raise ValueError("Must provide at least one of domain, quadrature, or test field")
1162
- if test is not None and domain != test.domain:
1163
- raise NotImplementedError("Mixing integration and test domain is not supported yet")
1164
-
1165
- if nodal:
1166
- if quadrature is not None:
1167
- raise ValueError("Cannot specify quadrature for nodal integration")
1168
-
1169
- if test is None:
1170
- raise ValueError("Nodal integration requires specifying a test function")
1171
-
1172
- if trial is not None and test.space_partition != trial.space_partition:
1173
- raise ValueError(
1174
- "Bilinear nodal integration requires test and trial to be defined on the same function space"
1175
- )
1176
- else:
1177
- if quadrature is None:
1178
- order = sum(field.degree for field in fields.values())
1179
- quadrature = RegularQuadrature(domain=domain, order=order)
1180
- elif domain != quadrature.domain:
1181
- raise ValueError("Incompatible integration and quadrature domain")
1182
-
1183
- # Canonicalize types
1184
- accumulate_dtype = wp.types.type_to_warp(accumulate_dtype)
1185
- if output is not None:
1186
- if isinstance(output, BsrMatrix):
1187
- output_dtype = output.scalar_type
1188
- else:
1189
- output_dtype = output.dtype
1190
- elif output_dtype is None:
1191
- output_dtype = accumulate_dtype
1192
- else:
1193
- output_dtype = wp.types.type_to_warp(output_dtype)
1194
-
1195
- kernel, FieldStruct, ValueStruct = _generate_integrate_kernel(
1196
- integrand=integrand,
1197
- domain=domain,
1198
- nodal=nodal,
1199
- quadrature=quadrature,
1200
- test=test,
1201
- test_name=test_name,
1202
- trial=trial,
1203
- trial_name=trial_name,
1204
- fields=fields,
1205
- accumulate_dtype=accumulate_dtype,
1206
- output_dtype=output_dtype,
1207
- kernel_options=kernel_options,
1208
- )
1209
-
1210
- return _launch_integrate_kernel(
1211
- kernel=kernel,
1212
- FieldStruct=FieldStruct,
1213
- ValueStruct=ValueStruct,
1214
- domain=domain,
1215
- nodal=nodal,
1216
- quadrature=quadrature,
1217
- test=test,
1218
- trial=trial,
1219
- fields=fields,
1220
- values=values,
1221
- accumulate_dtype=accumulate_dtype,
1222
- temporary_store=temporary_store,
1223
- output_dtype=output_dtype,
1224
- output=output,
1225
- device=device,
1226
- )
1227
-
1228
-
1229
- def get_interpolate_to_field_function(
1230
- integrand_func: wp.Function,
1231
- domain: GeometryDomain,
1232
- FieldStruct: wp.codegen.Struct,
1233
- ValueStruct: wp.codegen.Struct,
1234
- dest: FieldRestriction,
1235
- ):
1236
- value_type = dest.space.dtype
1237
-
1238
- def interpolate_to_field_fn(
1239
- local_node_index: int,
1240
- domain_arg: domain.ElementArg,
1241
- domain_index_arg: domain.ElementIndexArg,
1242
- dest_node_arg: dest.space_restriction.NodeArg,
1243
- dest_eval_arg: dest.field.EvalArg,
1244
- fields: FieldStruct,
1245
- values: ValueStruct,
1246
- ):
1247
- node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
1248
- element_count = dest.space_restriction.node_element_count(dest_node_arg, local_node_index)
1249
-
1250
- test_dof_index = NULL_DOF_INDEX
1251
- trial_dof_index = NULL_DOF_INDEX
1252
- node_weight = 1.0
1253
-
1254
- # Volume-weighted average across elements
1255
- # Superfluous if the interpolated function is continuous, but helpful for visualizing discontinuous spaces
1256
-
1257
- val_sum = value_type(0.0)
1258
- vol_sum = float(0.0)
1259
-
1260
- for n in range(element_count):
1261
- node_element_index = dest.space_restriction.node_element_index(dest_node_arg, local_node_index, n)
1262
- element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
1263
-
1264
- coords = dest.space.node_coords_in_element(
1265
- domain_arg,
1266
- dest_eval_arg.space_arg,
1267
- element_index,
1268
- node_element_index.node_index_in_element,
1269
- )
1270
-
1271
- if coords[0] != OUTSIDE:
1272
- sample = Sample(
1273
- element_index,
1274
- coords,
1275
- node_index,
1276
- node_weight,
1277
- test_dof_index,
1278
- trial_dof_index,
1279
- )
1280
- vol = domain.element_measure(domain_arg, sample)
1281
- val = integrand_func(sample, fields, values)
1282
-
1283
- vol_sum += vol
1284
- val_sum += vol * val
1285
-
1286
- return val_sum, vol_sum
1287
-
1288
- return interpolate_to_field_fn
1289
-
1290
-
1291
- def get_interpolate_to_field_kernel(
1292
- interpolate_to_field_fn: wp.Function,
1293
- domain: GeometryDomain,
1294
- FieldStruct: wp.codegen.Struct,
1295
- ValueStruct: wp.codegen.Struct,
1296
- dest: FieldRestriction,
1297
- ):
1298
- def interpolate_to_field_kernel_fn(
1299
- domain_arg: domain.ElementArg,
1300
- domain_index_arg: domain.ElementIndexArg,
1301
- dest_node_arg: dest.space_restriction.NodeArg,
1302
- dest_eval_arg: dest.field.EvalArg,
1303
- fields: FieldStruct,
1304
- values: ValueStruct,
1305
- ):
1306
- local_node_index = wp.tid()
1307
-
1308
- val_sum, vol_sum = interpolate_to_field_fn(
1309
- local_node_index, domain_arg, domain_index_arg, dest_node_arg, dest_eval_arg, fields, values
1310
- )
1311
-
1312
- if vol_sum > 0.0:
1313
- node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
1314
- dest.field.set_node_value(dest_eval_arg, node_index, val_sum / vol_sum)
1315
-
1316
- return interpolate_to_field_kernel_fn
1317
-
1318
-
1319
- def get_interpolate_to_array_kernel(
1320
- integrand_func: wp.Function,
1321
- domain: GeometryDomain,
1322
- quadrature: Quadrature,
1323
- FieldStruct: wp.codegen.Struct,
1324
- ValueStruct: wp.codegen.Struct,
1325
- value_type: type,
1326
- ):
1327
- def interpolate_to_array_kernel_fn(
1328
- qp_arg: quadrature.Arg,
1329
- domain_arg: quadrature.domain.ElementArg,
1330
- domain_index_arg: quadrature.domain.ElementIndexArg,
1331
- fields: FieldStruct,
1332
- values: ValueStruct,
1333
- result: wp.array(dtype=value_type),
1334
- ):
1335
- element_index = domain.element_index(domain_index_arg, wp.tid())
1336
-
1337
- test_dof_index = NULL_DOF_INDEX
1338
- trial_dof_index = NULL_DOF_INDEX
1339
-
1340
- qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
1341
- for k in range(qp_point_count):
1342
- qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
1343
- coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
1344
- qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
1345
-
1346
- sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
1347
-
1348
- result[qp_index] = integrand_func(sample, fields, values)
1349
-
1350
- return interpolate_to_array_kernel_fn
1351
-
1352
-
1353
- def get_interpolate_nonvalued_kernel(
1354
- integrand_func: wp.Function,
1355
- domain: GeometryDomain,
1356
- quadrature: Quadrature,
1357
- FieldStruct: wp.codegen.Struct,
1358
- ValueStruct: wp.codegen.Struct,
1359
- ):
1360
- def interpolate_nonvalued_kernel_fn(
1361
- qp_arg: quadrature.Arg,
1362
- domain_arg: quadrature.domain.ElementArg,
1363
- domain_index_arg: quadrature.domain.ElementIndexArg,
1364
- fields: FieldStruct,
1365
- values: ValueStruct,
1366
- ):
1367
- element_index = domain.element_index(domain_index_arg, wp.tid())
1368
-
1369
- test_dof_index = NULL_DOF_INDEX
1370
- trial_dof_index = NULL_DOF_INDEX
1371
-
1372
- qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
1373
- for k in range(qp_point_count):
1374
- qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
1375
- coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
1376
- qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
1377
-
1378
- sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
1379
- integrand_func(sample, fields, values)
1380
-
1381
- return interpolate_nonvalued_kernel_fn
1382
-
1383
-
1384
- def _generate_interpolate_kernel(
1385
- integrand: Integrand,
1386
- domain: GeometryDomain,
1387
- dest: Optional[Union[FieldLike, wp.array]],
1388
- quadrature: Optional[Quadrature],
1389
- fields: Dict[str, FieldLike],
1390
- kernel_options: Dict[str, Any] = {},
1391
- ) -> wp.Kernel:
1392
- # Extract field arguments from integrand
1393
- field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
1394
- integrand, fields=fields, domain=domain
1395
- )
1396
-
1397
- # Generate field struct
1398
- integrand_func = _translate_integrand(
1399
- integrand,
1400
- field_args,
1401
- )
1402
-
1403
- _register_integrand_field_wrappers(integrand_func, fields)
1404
-
1405
- FieldStruct = _gen_field_struct(field_args)
1406
- ValueStruct = _gen_value_struct(value_args)
1407
-
1408
- # Check if kernel exist in cache
1409
- if isinstance(dest, FieldRestriction):
1410
- kernel_suffix = (
1411
- f"_itp_{FieldStruct.key}_{dest.domain.name}_{dest.space_restriction.space_partition.name}_{dest.space.name}"
1412
- )
1413
- elif wp.types.is_array(dest):
1414
- kernel_suffix = f"_itp_{FieldStruct.key}_{quadrature.name}_{wp.types.type_repr(dest.dtype)}"
1415
- else:
1416
- kernel_suffix = f"_itp_{FieldStruct.key}_{quadrature.name}"
1417
-
1418
- kernel = cache.get_integrand_kernel(
1419
- integrand=integrand,
1420
- suffix=kernel_suffix,
1421
- )
1422
- if kernel is not None:
1423
- return kernel, FieldStruct, ValueStruct
1424
-
1425
- # Generate interpolation kernel
1426
- if isinstance(dest, FieldRestriction):
1427
- # need to split into kernel + function for diffferentiability
1428
- interpolate_fn = get_interpolate_to_field_function(
1429
- integrand_func,
1430
- domain,
1431
- dest=dest,
1432
- FieldStruct=FieldStruct,
1433
- ValueStruct=ValueStruct,
1434
- )
1435
-
1436
- interpolate_fn = cache.get_integrand_function(
1437
- integrand=integrand,
1438
- func=interpolate_fn,
1439
- suffix=kernel_suffix,
1440
- code_transformers=[
1441
- PassFieldArgsToIntegrand(
1442
- arg_names=integrand.argspec.args,
1443
- field_args=field_args.keys(),
1444
- value_args=value_args.keys(),
1445
- sample_name=sample_name,
1446
- domain_name=domain_name,
1447
- )
1448
- ],
1449
- )
1450
-
1451
- interpolate_kernel_fn = get_interpolate_to_field_kernel(
1452
- interpolate_fn,
1453
- domain,
1454
- dest=dest,
1455
- FieldStruct=FieldStruct,
1456
- ValueStruct=ValueStruct,
1457
- )
1458
- elif wp.types.is_array(dest):
1459
- interpolate_kernel_fn = get_interpolate_to_array_kernel(
1460
- integrand_func,
1461
- domain=domain,
1462
- quadrature=quadrature,
1463
- value_type=dest.dtype,
1464
- FieldStruct=FieldStruct,
1465
- ValueStruct=ValueStruct,
1466
- )
1467
- else:
1468
- interpolate_kernel_fn = get_interpolate_nonvalued_kernel(
1469
- integrand_func,
1470
- domain=domain,
1471
- quadrature=quadrature,
1472
- FieldStruct=FieldStruct,
1473
- ValueStruct=ValueStruct,
1474
- )
1475
-
1476
- kernel = cache.get_integrand_kernel(
1477
- integrand=integrand,
1478
- kernel_fn=interpolate_kernel_fn,
1479
- suffix=kernel_suffix,
1480
- kernel_options=kernel_options,
1481
- code_transformers=[
1482
- PassFieldArgsToIntegrand(
1483
- arg_names=integrand.argspec.args,
1484
- field_args=field_args.keys(),
1485
- value_args=value_args.keys(),
1486
- sample_name=sample_name,
1487
- domain_name=domain_name,
1488
- )
1489
- ],
1490
- )
1491
-
1492
- return kernel, FieldStruct, ValueStruct
1493
-
1494
-
1495
- def _launch_interpolate_kernel(
1496
- kernel: wp.kernel,
1497
- FieldStruct: wp.codegen.Struct,
1498
- ValueStruct: wp.codegen.Struct,
1499
- domain: GeometryDomain,
1500
- dest: Optional[Union[FieldRestriction, wp.array]],
1501
- quadrature: Optional[Quadrature],
1502
- fields: Dict[str, FieldLike],
1503
- values: Dict[str, Any],
1504
- device,
1505
- ) -> wp.Kernel:
1506
- # Set-up launch arguments
1507
- elt_arg = domain.element_arg_value(device=device)
1508
- elt_index_arg = domain.element_index_arg_value(device=device)
1509
-
1510
- field_arg_values = FieldStruct()
1511
- for k, v in fields.items():
1512
- setattr(field_arg_values, k, v.eval_arg_value(device=device))
1513
-
1514
- value_struct_values = ValueStruct()
1515
- for k, v in values.items():
1516
- setattr(value_struct_values, k, v)
1517
-
1518
- if isinstance(dest, FieldRestriction):
1519
- dest_node_arg = dest.space_restriction.node_arg(device=device)
1520
- dest_eval_arg = dest.field.eval_arg_value(device=device)
1521
-
1522
- wp.launch(
1523
- kernel=kernel,
1524
- dim=dest.space_restriction.node_count(),
1525
- inputs=[
1526
- elt_arg,
1527
- elt_index_arg,
1528
- dest_node_arg,
1529
- dest_eval_arg,
1530
- field_arg_values,
1531
- value_struct_values,
1532
- ],
1533
- device=device,
1534
- )
1535
- elif wp.types.is_array(dest):
1536
- qp_arg = quadrature.arg_value(device)
1537
- wp.launch(
1538
- kernel=kernel,
1539
- dim=domain.element_count(),
1540
- inputs=[qp_arg, elt_arg, elt_index_arg, field_arg_values, value_struct_values, dest],
1541
- device=device,
1542
- )
1543
- else:
1544
- qp_arg = quadrature.arg_value(device)
1545
- wp.launch(
1546
- kernel=kernel,
1547
- dim=domain.element_count(),
1548
- inputs=[qp_arg, elt_arg, elt_index_arg, field_arg_values, value_struct_values],
1549
- device=device,
1550
- )
1551
-
1552
-
1553
- def interpolate(
1554
- integrand: Integrand,
1555
- dest: Optional[Union[DiscreteField, FieldRestriction, wp.array]] = None,
1556
- quadrature: Optional[Quadrature] = None,
1557
- fields: Dict[str, FieldLike] = {},
1558
- values: Dict[str, Any] = {},
1559
- device=None,
1560
- kernel_options: Dict[str, Any] = {},
1561
- ):
1562
- """
1563
- Interpolates a function at a finite set of sample points and optionally assigns the result to a discrete field or a raw warp array.
1564
-
1565
- Args:
1566
- integrand: Function to be interpolated, must have :func:`integrand` decorator
1567
- dest: Where to store the interpolation result. Can be either
1568
-
1569
- - a :class:`DiscreteField`, or restriction of a discrete field to a domain (from :func:`make_restriction`). In this case, interpolation will be performed at each node.
1570
- - a normal warp array. In this case, the `quadrature` argument defining the interpolation locations must be provided and the result of the `integrand` at each quadrature point will be assigned to the array.
1571
- - ``None``. In this case, the `quadrature` argument must also be provided and the `integrand` function is responsible for dealing with the interpolation result.
1572
- quadrature: Quadrature formula defining the interpolation samples if `dest` is not a discrete field or field restriction.
1573
- fields: Discrete fields to be passed to the integrand. Keys in the dictionary must match integrand parameters names.
1574
- values: Additional variable values to be passed to the integrand, can be of any type accepted by warp kernel launches. Keys in the dictionary must match integrand parameter names.
1575
- device: Device on which to perform the interpolation
1576
- kernel_options: Overloaded options to be passed to the kernel builder (e.g, ``{"enable_backward": True}``)
1577
- """
1578
- if not isinstance(integrand, Integrand):
1579
- raise ValueError("integrand must be tagged with @integrand decorator")
1580
-
1581
- test, _, trial, __ = _get_test_and_trial_fields(fields)
1582
- if test is not None or trial is not None:
1583
- raise ValueError("Test or Trial fields should not be used for interpolation")
1584
-
1585
- if isinstance(dest, DiscreteField):
1586
- dest = make_restriction(dest)
1587
-
1588
- if isinstance(dest, FieldRestriction):
1589
- domain = dest.domain
1590
- else:
1591
- if quadrature is None:
1592
- raise ValueError("When not interpolating to a field, a quadrature formula must be provided")
1593
-
1594
- domain = quadrature.domain
1595
-
1596
- kernel, FieldStruct, ValueStruct = _generate_interpolate_kernel(
1597
- integrand=integrand,
1598
- domain=domain,
1599
- dest=dest,
1600
- quadrature=quadrature,
1601
- fields=fields,
1602
- kernel_options=kernel_options,
1603
- )
1604
-
1605
- return _launch_interpolate_kernel(
1606
- kernel=kernel,
1607
- FieldStruct=FieldStruct,
1608
- ValueStruct=ValueStruct,
1609
- domain=domain,
1610
- dest=dest,
1611
- quadrature=quadrature,
1612
- fields=fields,
1613
- values=values,
1614
- device=device,
1615
- )
1
+ import ast
2
+ from typing import Any, Dict, List, Optional, Set, Union
3
+
4
+ import warp as wp
5
+ from warp.codegen import get_annotations
6
+ from warp.fem import cache
7
+ from warp.fem.domain import GeometryDomain
8
+ from warp.fem.field import (
9
+ DiscreteField,
10
+ FieldLike,
11
+ FieldRestriction,
12
+ SpaceField,
13
+ TestField,
14
+ TrialField,
15
+ make_restriction,
16
+ )
17
+ from warp.fem.operator import Integrand, Operator
18
+ from warp.fem.quadrature import Quadrature, RegularQuadrature
19
+ from warp.fem.types import NULL_DOF_INDEX, OUTSIDE, DofIndex, Domain, Field, Sample, make_free_sample
20
+ from warp.sparse import BsrMatrix, bsr_set_from_triplets, bsr_zeros
21
+ from warp.types import type_length
22
+ from warp.utils import array_cast
23
+
24
+
25
+ def _resolve_path(func, node):
26
+ """
27
+ Resolves variable and path from ast node/attribute (adapted from warp.codegen)
28
+ """
29
+
30
+ modules = []
31
+
32
+ while isinstance(node, ast.Attribute):
33
+ modules.append(node.attr)
34
+ node = node.value
35
+
36
+ if isinstance(node, ast.Name):
37
+ modules.append(node.id)
38
+
39
+ # reverse list since ast presents it backward order
40
+ path = [*reversed(modules)]
41
+
42
+ if len(path) == 0:
43
+ return None, path
44
+
45
+ # try and evaluate object path
46
+ try:
47
+ # Look up the closure info and append it to adj.func.__globals__
48
+ # in case you want to define a kernel inside a function and refer
49
+ # to variables you've declared inside that function:
50
+ capturedvars = dict(zip(func.__code__.co_freevars, [c.cell_contents for c in (func.__closure__ or [])]))
51
+
52
+ vars_dict = {**func.__globals__, **capturedvars}
53
+ func = eval(".".join(path), vars_dict)
54
+ return func, path
55
+ except (NameError, AttributeError):
56
+ pass
57
+
58
+ return None, path
59
+
60
+
61
+ def _path_to_ast_attribute(name: str) -> ast.Attribute:
62
+ path = name.split(".")
63
+ path.reverse()
64
+
65
+ node = ast.Name(id=path.pop(), ctx=ast.Load())
66
+ while len(path):
67
+ node = ast.Attribute(
68
+ value=node,
69
+ attr=path.pop(),
70
+ ctx=ast.Load(),
71
+ )
72
+ return node
73
+
74
+
75
+ class IntegrandTransformer(ast.NodeTransformer):
76
+ def __init__(self, integrand: Integrand, field_args: Dict[str, FieldLike]):
77
+ self._integrand = integrand
78
+ self._field_args = field_args
79
+
80
+ def visit_Call(self, call: ast.Call):
81
+ call = self.generic_visit(call)
82
+
83
+ callee = getattr(call.func, "id", None)
84
+ if callee in self._field_args:
85
+ # Shortcut for evaluating fields as f(x...)
86
+ field = self._field_args[callee]
87
+
88
+ arg_type = self._integrand.argspec.annotations[callee]
89
+ operator = arg_type.call_operator
90
+
91
+ call.func = ast.Attribute(
92
+ value=_path_to_ast_attribute(f"{arg_type.__module__}.{arg_type.__qualname__}"),
93
+ attr="call_operator",
94
+ ctx=ast.Load(),
95
+ )
96
+ call.args = [ast.Name(id=callee, ctx=ast.Load())] + call.args
97
+
98
+ self._replace_call_func(call, operator, field)
99
+
100
+ return call
101
+
102
+ func, _ = _resolve_path(self._integrand.func, call.func)
103
+
104
+ if isinstance(func, Operator) and len(call.args) > 0:
105
+ # Evaluating operators as op(field, x, ...)
106
+ callee = getattr(call.args[0], "id", None)
107
+ if callee in self._field_args:
108
+ field = self._field_args[callee]
109
+ self._replace_call_func(call, func, field)
110
+
111
+ if isinstance(func, Integrand):
112
+ key = self._translate_callee(func, call.args)
113
+ call.func = ast.Attribute(
114
+ value=call.func,
115
+ attr=key,
116
+ ctx=ast.Load(),
117
+ )
118
+
119
+ # print(ast.dump(call, indent=4))
120
+
121
+ return call
122
+
123
+ def _replace_call_func(self, call: ast.Call, operator: Operator, field: FieldLike):
124
+ try:
125
+ pointer = operator.resolver(field)
126
+ setattr(operator, pointer.key, pointer)
127
+ except AttributeError as e:
128
+ raise ValueError(f"Operator {operator.func.__name__} is not defined for field {field.name}") from e
129
+ call.func = ast.Attribute(value=call.func, attr=pointer.key, ctx=ast.Load())
130
+
131
+ def _translate_callee(self, callee: Integrand, args: List[ast.AST]):
132
+ # Get field types for call site arguments
133
+ call_site_field_args = []
134
+ for arg in args:
135
+ name = getattr(arg, "id", None)
136
+ if name in self._field_args:
137
+ call_site_field_args.append(self._field_args[name])
138
+
139
+ call_site_field_args.reverse()
140
+
141
+ # Pass to callee in same order
142
+ callee_field_args = {}
143
+ for arg in callee.argspec.args:
144
+ arg_type = callee.argspec.annotations[arg]
145
+ if arg_type in (Field, Domain):
146
+ callee_field_args[arg] = call_site_field_args.pop()
147
+
148
+ return _translate_integrand(callee, callee_field_args).key
149
+
150
+
151
+ def _translate_integrand(integrand: Integrand, field_args: Dict[str, FieldLike]) -> wp.Function:
152
+ # Specialize field argument types
153
+ argspec = integrand.argspec
154
+ annotations = {}
155
+ for arg in argspec.args:
156
+ arg_type = argspec.annotations[arg]
157
+ if arg_type == Field:
158
+ annotations[arg] = field_args[arg].ElementEvalArg
159
+ elif arg_type == Domain:
160
+ annotations[arg] = field_args[arg].ElementArg
161
+ else:
162
+ annotations[arg] = arg_type
163
+
164
+ # Transform field evaluation calls
165
+ transformer = IntegrandTransformer(integrand, field_args)
166
+
167
+ suffix = "_".join([f.name for f in field_args.values()])
168
+
169
+ func = cache.get_integrand_function(
170
+ integrand=integrand,
171
+ suffix=suffix,
172
+ annotations=annotations,
173
+ code_transformers=[transformer],
174
+ )
175
+
176
+ key = func.key
177
+ setattr(integrand, key, integrand.module.functions[key])
178
+
179
+ return getattr(integrand, key)
180
+
181
+
182
+ def _get_integrand_field_arguments(
183
+ integrand: Integrand,
184
+ fields: Dict[str, FieldLike],
185
+ domain: GeometryDomain = None,
186
+ ):
187
+ # parse argument types
188
+ field_args = {}
189
+ value_args = {}
190
+
191
+ domain_name = None
192
+ sample_name = None
193
+
194
+ argspec = integrand.argspec
195
+ for arg in argspec.args:
196
+ arg_type = argspec.annotations[arg]
197
+ if arg_type == Field:
198
+ if arg not in fields:
199
+ raise ValueError(f"Missing field for argument '{arg}' of integrand '{integrand.name}'")
200
+ field_args[arg] = fields[arg]
201
+ elif arg_type == Domain:
202
+ domain_name = arg
203
+ field_args[arg] = domain
204
+ elif arg_type == Sample:
205
+ sample_name = arg
206
+ else:
207
+ value_args[arg] = arg_type
208
+
209
+ return field_args, value_args, domain_name, sample_name
210
+
211
+
212
+ def _check_field_compat(
213
+ integrand: Integrand,
214
+ fields: Dict[str, FieldLike],
215
+ field_args: Dict[str, FieldLike],
216
+ domain: GeometryDomain = None,
217
+ ):
218
+ # Check field compatilibity
219
+ for name, field in fields.items():
220
+ if name not in field_args:
221
+ raise ValueError(
222
+ f"Passed field argument '{name}' does not match any parameter of integrand '{integrand.name}'"
223
+ )
224
+
225
+ if isinstance(field, SpaceField) and domain is not None:
226
+ space = field.space
227
+ if space.geometry != domain.geometry:
228
+ raise ValueError(f"Field '{name}' must be defined on the same geometry as the integration domain")
229
+ if space.dimension != domain.dimension:
230
+ raise ValueError(
231
+ f"Field '{name}' dimension ({space.dimension}) does not match that of the integration domain ({domain.dimension}). Maybe a forgotten `.trace()`?"
232
+ )
233
+
234
+
235
+ def _populate_value_struct(ValueStruct: wp.codegen.Struct, values: Dict[str, Any], integrand_name: str):
236
+ value_struct_values = ValueStruct()
237
+ for k, v in values.items():
238
+ try:
239
+ setattr(value_struct_values, k, v)
240
+ except Exception as err:
241
+ if k not in ValueStruct.vars:
242
+ raise ValueError(
243
+ f"Passed value argument '{k}' does not match any of the integrand '{integrand_name}' parameters"
244
+ ) from err
245
+ raise ValueError(
246
+ f"Passed value argument '{k}' of type '{wp.types.type_repr(v)}' is incompatible with the integrand '{integrand_name}' parameter of type '{wp.types.type_repr(ValueStruct.vars[k].type)}'"
247
+ ) from err
248
+
249
+ missing_values = ValueStruct.vars.keys() - values.keys()
250
+ if missing_values:
251
+ wp.utils.warn(
252
+ f"Missing values for parameter(s) '{', '.join(missing_values)}' of the integrand '{integrand_name}', will be zero-initialized"
253
+ )
254
+
255
+ return value_struct_values
256
+
257
+
258
+ def _get_test_and_trial_fields(
259
+ fields: Dict[str, FieldLike],
260
+ ):
261
+ test = None
262
+ trial = None
263
+ test_name = None
264
+ trial_name = None
265
+
266
+ for name, field in fields.items():
267
+ if not isinstance(field, FieldLike):
268
+ raise ValueError(f"Passed field argument '{name}' is not a proper Field")
269
+
270
+ if isinstance(field, TestField):
271
+ if test is not None:
272
+ raise ValueError(f"More than one test field argument: '{test_name}' and '{name}'")
273
+ test = field
274
+ test_name = name
275
+ elif isinstance(field, TrialField):
276
+ if trial is not None:
277
+ raise ValueError(f"More than one trial field argument: '{trial_name}' and '{name}'")
278
+ trial = field
279
+ trial_name = name
280
+
281
+ if trial is not None:
282
+ if test is None:
283
+ raise ValueError("A trial field cannot be provided without a test field")
284
+
285
+ if test.domain != trial.domain:
286
+ raise ValueError("Incompatible test and trial domains")
287
+
288
+ return test, test_name, trial, trial_name
289
+
290
+
291
+ def _gen_field_struct(field_args: Dict[str, FieldLike]):
292
+ class Fields:
293
+ pass
294
+
295
+ annotations = get_annotations(Fields)
296
+
297
+ for name, arg in field_args.items():
298
+ if isinstance(arg, GeometryDomain):
299
+ continue
300
+ setattr(Fields, name, arg.EvalArg())
301
+ annotations[name] = arg.EvalArg
302
+
303
+ try:
304
+ Fields.__annotations__ = annotations
305
+ except AttributeError:
306
+ Fields.__dict__.__annotations__ = annotations
307
+
308
+ suffix = "_".join([f"{name}_{arg_struct.cls.__qualname__}" for name, arg_struct in annotations.items()])
309
+
310
+ return cache.get_struct(Fields, suffix=suffix)
311
+
312
+
313
+ def _gen_value_struct(value_args: Dict[str, type]):
314
+ class Values:
315
+ pass
316
+
317
+ annotations = get_annotations(Values)
318
+
319
+ for name, arg_type in value_args.items():
320
+ setattr(Values, name, None)
321
+ annotations[name] = arg_type
322
+
323
+ def arg_type_name(arg_type):
324
+ if isinstance(arg_type, wp.codegen.Struct):
325
+ return arg_type_name(arg_type.cls)
326
+ return getattr(arg_type, "__name__", str(arg_type))
327
+
328
+ def arg_type_name(arg_type):
329
+ if isinstance(arg_type, wp.codegen.Struct):
330
+ return arg_type_name(arg_type.cls)
331
+ return getattr(arg_type, "__name__", str(arg_type))
332
+
333
+ try:
334
+ Values.__annotations__ = annotations
335
+ except AttributeError:
336
+ Values.__dict__.__annotations__ = annotations
337
+
338
+ suffix = "_".join([f"{name}_{arg_type_name(arg_type)}" for name, arg_type in annotations.items()])
339
+
340
+ return cache.get_struct(Values, suffix=suffix)
341
+
342
+
343
+ def _get_trial_arg():
344
+ pass
345
+
346
+
347
+ def _get_test_arg():
348
+ pass
349
+
350
+
351
+ class _FieldWrappers:
352
+ pass
353
+
354
+
355
+ def _register_integrand_field_wrappers(integrand_func: wp.Function, fields: Dict[str, FieldLike]):
356
+ integrand_func._field_wrappers = _FieldWrappers()
357
+ for name, field in fields.items():
358
+ setattr(integrand_func._field_wrappers, name, field.ElementEvalArg)
359
+
360
+
361
+ class PassFieldArgsToIntegrand(ast.NodeTransformer):
362
+ def __init__(
363
+ self,
364
+ arg_names: List[str],
365
+ field_args: Set[str],
366
+ value_args: Set[str],
367
+ sample_name: str,
368
+ domain_name: str,
369
+ test_name: str = None,
370
+ trial_name: str = None,
371
+ func_name: str = "integrand_func",
372
+ fields_var_name: str = "fields",
373
+ values_var_name: str = "values",
374
+ domain_var_name: str = "domain_arg",
375
+ sample_var_name: str = "sample",
376
+ field_wrappers_attr: str = "_field_wrappers",
377
+ ):
378
+ self._arg_names = arg_names
379
+ self._field_args = field_args
380
+ self._value_args = value_args
381
+ self._domain_name = domain_name
382
+ self._sample_name = sample_name
383
+ self._func_name = func_name
384
+ self._test_name = test_name
385
+ self._trial_name = trial_name
386
+ self._fields_var_name = fields_var_name
387
+ self._values_var_name = values_var_name
388
+ self._domain_var_name = domain_var_name
389
+ self._sample_var_name = sample_var_name
390
+ self._field_wrappers_attr = field_wrappers_attr
391
+
392
+ def visit_Call(self, call: ast.Call):
393
+ call = self.generic_visit(call)
394
+
395
+ callee = getattr(call.func, "id", None)
396
+
397
+ if callee == self._func_name:
398
+ # Replace function arguments with ours generated structs
399
+ call.args.clear()
400
+ for arg in self._arg_names:
401
+ if arg == self._domain_name:
402
+ call.args.append(
403
+ ast.Name(id=self._domain_var_name, ctx=ast.Load()),
404
+ )
405
+ elif arg == self._sample_name:
406
+ call.args.append(
407
+ ast.Name(id=self._sample_var_name, ctx=ast.Load()),
408
+ )
409
+ elif arg in self._field_args:
410
+ call.args.append(
411
+ ast.Call(
412
+ func=ast.Attribute(
413
+ value=ast.Attribute(
414
+ value=ast.Name(id=self._func_name, ctx=ast.Load()),
415
+ attr=self._field_wrappers_attr,
416
+ ctx=ast.Load(),
417
+ ),
418
+ attr=arg,
419
+ ctx=ast.Load(),
420
+ ),
421
+ args=[
422
+ ast.Name(id=self._domain_var_name, ctx=ast.Load()),
423
+ ast.Attribute(
424
+ value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
425
+ attr=arg,
426
+ ctx=ast.Load(),
427
+ ),
428
+ ],
429
+ keywords=[],
430
+ )
431
+ )
432
+ elif arg in self._value_args:
433
+ call.args.append(
434
+ ast.Attribute(
435
+ value=ast.Name(id=self._values_var_name, ctx=ast.Load()),
436
+ attr=arg,
437
+ ctx=ast.Load(),
438
+ )
439
+ )
440
+ else:
441
+ raise RuntimeError(f"Unhandled argument {arg}")
442
+ # print(ast.dump(call, indent=4))
443
+ elif callee == _get_test_arg.__name__:
444
+ # print(ast.dump(call, indent=4))
445
+ call = ast.Attribute(
446
+ value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
447
+ attr=self._test_name,
448
+ ctx=ast.Load(),
449
+ )
450
+ elif callee == _get_trial_arg.__name__:
451
+ # print(ast.dump(call, indent=4))
452
+ call = ast.Attribute(
453
+ value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
454
+ attr=self._trial_name,
455
+ ctx=ast.Load(),
456
+ )
457
+
458
+ return call
459
+
460
+
461
+ def get_integrate_constant_kernel(
462
+ integrand_func: wp.Function,
463
+ domain: GeometryDomain,
464
+ quadrature: Quadrature,
465
+ FieldStruct: wp.codegen.Struct,
466
+ ValueStruct: wp.codegen.Struct,
467
+ accumulate_dtype,
468
+ ):
469
+ def integrate_kernel_fn(
470
+ qp_arg: quadrature.Arg,
471
+ domain_arg: domain.ElementArg,
472
+ domain_index_arg: domain.ElementIndexArg,
473
+ fields: FieldStruct,
474
+ values: ValueStruct,
475
+ result: wp.array(dtype=accumulate_dtype),
476
+ ):
477
+ element_index = domain.element_index(domain_index_arg, wp.tid())
478
+ elem_sum = accumulate_dtype(0.0)
479
+
480
+ test_dof_index = NULL_DOF_INDEX
481
+ trial_dof_index = NULL_DOF_INDEX
482
+
483
+ qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
484
+ for k in range(qp_point_count):
485
+ qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
486
+ coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
487
+ qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
488
+
489
+ sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
490
+ vol = domain.element_measure(domain_arg, sample)
491
+
492
+ val = integrand_func(sample, fields, values)
493
+
494
+ elem_sum += accumulate_dtype(qp_weight * vol * val)
495
+
496
+ wp.atomic_add(result, 0, elem_sum)
497
+
498
+ return integrate_kernel_fn
499
+
500
+
501
+ def get_integrate_linear_kernel(
502
+ integrand_func: wp.Function,
503
+ domain: GeometryDomain,
504
+ quadrature: Quadrature,
505
+ FieldStruct: wp.codegen.Struct,
506
+ ValueStruct: wp.codegen.Struct,
507
+ test: TestField,
508
+ output_dtype,
509
+ accumulate_dtype,
510
+ ):
511
+ def integrate_kernel_fn(
512
+ qp_arg: quadrature.Arg,
513
+ domain_arg: domain.ElementArg,
514
+ domain_index_arg: domain.ElementIndexArg,
515
+ test_arg: test.space_restriction.NodeArg,
516
+ fields: FieldStruct,
517
+ values: ValueStruct,
518
+ result: wp.array2d(dtype=output_dtype),
519
+ ):
520
+ local_node_index, test_dof = wp.tid()
521
+ node_index = test.space_restriction.node_partition_index(test_arg, local_node_index)
522
+ element_count = test.space_restriction.node_element_count(test_arg, local_node_index)
523
+
524
+ trial_dof_index = NULL_DOF_INDEX
525
+
526
+ val_sum = accumulate_dtype(0.0)
527
+
528
+ for n in range(element_count):
529
+ node_element_index = test.space_restriction.node_element_index(test_arg, local_node_index, n)
530
+ element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
531
+
532
+ test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
533
+
534
+ qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
535
+ for k in range(qp_point_count):
536
+ qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
537
+ qp_coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
538
+ qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
539
+
540
+ vol = domain.element_measure(domain_arg, make_free_sample(element_index, qp_coords))
541
+
542
+ sample = Sample(element_index, qp_coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
543
+ val = integrand_func(sample, fields, values)
544
+
545
+ val_sum += accumulate_dtype(qp_weight * vol * val)
546
+
547
+ result[node_index, test_dof] = output_dtype(val_sum)
548
+
549
+ return integrate_kernel_fn
550
+
551
+
552
+ def get_integrate_linear_nodal_kernel(
553
+ integrand_func: wp.Function,
554
+ domain: GeometryDomain,
555
+ FieldStruct: wp.codegen.Struct,
556
+ ValueStruct: wp.codegen.Struct,
557
+ test: TestField,
558
+ output_dtype,
559
+ accumulate_dtype,
560
+ ):
561
+ def integrate_kernel_fn(
562
+ domain_arg: domain.ElementArg,
563
+ domain_index_arg: domain.ElementIndexArg,
564
+ test_restriction_arg: test.space_restriction.NodeArg,
565
+ fields: FieldStruct,
566
+ values: ValueStruct,
567
+ result: wp.array2d(dtype=output_dtype),
568
+ ):
569
+ local_node_index, dof = wp.tid()
570
+
571
+ node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
572
+ element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
573
+
574
+ trial_dof_index = NULL_DOF_INDEX
575
+
576
+ val_sum = accumulate_dtype(0.0)
577
+
578
+ for n in range(element_count):
579
+ node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
580
+ element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
581
+
582
+ coords = test.space.node_coords_in_element(
583
+ domain_arg,
584
+ _get_test_arg(),
585
+ element_index,
586
+ node_element_index.node_index_in_element,
587
+ )
588
+
589
+ if coords[0] != OUTSIDE:
590
+ node_weight = test.space.node_quadrature_weight(
591
+ domain_arg,
592
+ _get_test_arg(),
593
+ element_index,
594
+ node_element_index.node_index_in_element,
595
+ )
596
+
597
+ test_dof_index = DofIndex(node_element_index.node_index_in_element, dof)
598
+
599
+ sample = Sample(
600
+ element_index,
601
+ coords,
602
+ node_index,
603
+ node_weight,
604
+ test_dof_index,
605
+ trial_dof_index,
606
+ )
607
+ vol = domain.element_measure(domain_arg, sample)
608
+ val = integrand_func(sample, fields, values)
609
+
610
+ val_sum += accumulate_dtype(node_weight * vol * val)
611
+
612
+ result[node_index, dof] = output_dtype(val_sum)
613
+
614
+ return integrate_kernel_fn
615
+
616
+
617
+ def get_integrate_bilinear_kernel(
618
+ integrand_func: wp.Function,
619
+ domain: GeometryDomain,
620
+ quadrature: Quadrature,
621
+ FieldStruct: wp.codegen.Struct,
622
+ ValueStruct: wp.codegen.Struct,
623
+ test: TestField,
624
+ trial: TrialField,
625
+ output_dtype,
626
+ accumulate_dtype,
627
+ ):
628
+ NODES_PER_ELEMENT = trial.space.topology.NODES_PER_ELEMENT
629
+
630
+ def integrate_kernel_fn(
631
+ qp_arg: quadrature.Arg,
632
+ domain_arg: domain.ElementArg,
633
+ domain_index_arg: domain.ElementIndexArg,
634
+ test_arg: test.space_restriction.NodeArg,
635
+ trial_partition_arg: trial.space_partition.PartitionArg,
636
+ trial_topology_arg: trial.space_partition.space_topology.TopologyArg,
637
+ fields: FieldStruct,
638
+ values: ValueStruct,
639
+ row_offsets: wp.array(dtype=int),
640
+ triplet_rows: wp.array(dtype=int),
641
+ triplet_cols: wp.array(dtype=int),
642
+ triplet_values: wp.array3d(dtype=output_dtype),
643
+ ):
644
+ test_local_node_index, trial_node, test_dof, trial_dof = wp.tid()
645
+
646
+ element_count = test.space_restriction.node_element_count(test_arg, test_local_node_index)
647
+ test_node_index = test.space_restriction.node_partition_index(test_arg, test_local_node_index)
648
+
649
+ trial_dof_index = DofIndex(trial_node, trial_dof)
650
+
651
+ for element in range(element_count):
652
+ test_element_index = test.space_restriction.node_element_index(test_arg, test_local_node_index, element)
653
+ element_index = domain.element_index(domain_index_arg, test_element_index.domain_element_index)
654
+ qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
655
+
656
+ test_dof_index = DofIndex(
657
+ test_element_index.node_index_in_element,
658
+ test_dof,
659
+ )
660
+
661
+ val_sum = accumulate_dtype(0.0)
662
+
663
+ for k in range(qp_point_count):
664
+ qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
665
+ coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
666
+
667
+ qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
668
+ vol = domain.element_measure(domain_arg, make_free_sample(element_index, coords))
669
+
670
+ sample = Sample(
671
+ element_index,
672
+ coords,
673
+ qp_index,
674
+ qp_weight,
675
+ test_dof_index,
676
+ trial_dof_index,
677
+ )
678
+ val = integrand_func(sample, fields, values)
679
+ val_sum += accumulate_dtype(qp_weight * vol * val)
680
+
681
+ block_offset = (row_offsets[test_node_index] + element) * NODES_PER_ELEMENT + trial_node
682
+ triplet_values[block_offset, test_dof, trial_dof] = output_dtype(val_sum)
683
+
684
+ # Set row and column indices
685
+ if test_dof == 0 and trial_dof == 0:
686
+ trial_node_index = trial.space_partition.partition_node_index(
687
+ trial_partition_arg,
688
+ trial.space.topology.element_node_index(domain_arg, trial_topology_arg, element_index, trial_node),
689
+ )
690
+ triplet_rows[block_offset] = test_node_index
691
+ triplet_cols[block_offset] = trial_node_index
692
+
693
+ return integrate_kernel_fn
694
+
695
+
696
+ def get_integrate_bilinear_nodal_kernel(
697
+ integrand_func: wp.Function,
698
+ domain: GeometryDomain,
699
+ FieldStruct: wp.codegen.Struct,
700
+ ValueStruct: wp.codegen.Struct,
701
+ test: TestField,
702
+ output_dtype,
703
+ accumulate_dtype,
704
+ ):
705
+ def integrate_kernel_fn(
706
+ domain_arg: domain.ElementArg,
707
+ domain_index_arg: domain.ElementIndexArg,
708
+ test_restriction_arg: test.space_restriction.NodeArg,
709
+ fields: FieldStruct,
710
+ values: ValueStruct,
711
+ triplet_rows: wp.array(dtype=int),
712
+ triplet_cols: wp.array(dtype=int),
713
+ triplet_values: wp.array3d(dtype=output_dtype),
714
+ ):
715
+ local_node_index, test_dof, trial_dof = wp.tid()
716
+
717
+ element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
718
+ node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
719
+
720
+ val_sum = accumulate_dtype(0.0)
721
+
722
+ for n in range(element_count):
723
+ node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
724
+ element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
725
+
726
+ coords = test.space.node_coords_in_element(
727
+ domain_arg,
728
+ _get_test_arg(),
729
+ element_index,
730
+ node_element_index.node_index_in_element,
731
+ )
732
+
733
+ if coords[0] != OUTSIDE:
734
+ node_weight = test.space.node_quadrature_weight(
735
+ domain_arg,
736
+ _get_test_arg(),
737
+ element_index,
738
+ node_element_index.node_index_in_element,
739
+ )
740
+
741
+ test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
742
+ trial_dof_index = DofIndex(node_element_index.node_index_in_element, trial_dof)
743
+
744
+ sample = Sample(
745
+ element_index,
746
+ coords,
747
+ node_index,
748
+ node_weight,
749
+ test_dof_index,
750
+ trial_dof_index,
751
+ )
752
+ vol = domain.element_measure(domain_arg, sample)
753
+ val = integrand_func(sample, fields, values)
754
+
755
+ val_sum += accumulate_dtype(node_weight * vol * val)
756
+
757
+ triplet_values[local_node_index, test_dof, trial_dof] = output_dtype(val_sum)
758
+ triplet_rows[local_node_index] = node_index
759
+ triplet_cols[local_node_index] = node_index
760
+
761
+ return integrate_kernel_fn
762
+
763
+
764
+ def _generate_integrate_kernel(
765
+ integrand: Integrand,
766
+ domain: GeometryDomain,
767
+ nodal: bool,
768
+ quadrature: Quadrature,
769
+ test: Optional[TestField],
770
+ test_name: str,
771
+ trial: Optional[TrialField],
772
+ trial_name: str,
773
+ fields: Dict[str, FieldLike],
774
+ output_dtype: type,
775
+ accumulate_dtype: type,
776
+ kernel_options: Optional[Dict[str, Any]] = None,
777
+ ) -> wp.Kernel:
778
+ if kernel_options is None:
779
+ kernel_options = {}
780
+
781
+ output_dtype = wp.types.type_scalar_type(output_dtype)
782
+
783
+ # Extract field arguments from integrand
784
+ field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
785
+ integrand, fields=fields, domain=domain
786
+ )
787
+
788
+ FieldStruct = _gen_field_struct(field_args)
789
+ ValueStruct = _gen_value_struct(value_args)
790
+
791
+ # Check if kernel exist in cache
792
+ kernel_suffix = f"_itg_{wp.types.type_typestr(output_dtype)}{wp.types.type_typestr(accumulate_dtype)}_{domain.name}_{FieldStruct.key}"
793
+ if nodal:
794
+ kernel_suffix += "_nodal"
795
+ else:
796
+ kernel_suffix += quadrature.name
797
+
798
+ if test:
799
+ kernel_suffix += f"_test_{test.space_partition.name}_{test.space.name}"
800
+ if trial:
801
+ kernel_suffix += f"_trial_{trial.space_partition.name}_{trial.space.name}"
802
+
803
+ kernel = cache.get_integrand_kernel(
804
+ integrand=integrand,
805
+ suffix=kernel_suffix,
806
+ )
807
+ if kernel is not None:
808
+ return kernel, FieldStruct, ValueStruct
809
+
810
+ # Not found in cache, transform integrand and generate kernel
811
+
812
+ _check_field_compat(integrand, fields, field_args, domain)
813
+
814
+ integrand_func = _translate_integrand(
815
+ integrand,
816
+ field_args,
817
+ )
818
+
819
+ _register_integrand_field_wrappers(integrand_func, fields)
820
+
821
+ if test is None and trial is None:
822
+ integrate_kernel_fn = get_integrate_constant_kernel(
823
+ integrand_func,
824
+ domain,
825
+ quadrature,
826
+ FieldStruct,
827
+ ValueStruct,
828
+ accumulate_dtype=accumulate_dtype,
829
+ )
830
+ elif trial is None:
831
+ if nodal:
832
+ integrate_kernel_fn = get_integrate_linear_nodal_kernel(
833
+ integrand_func,
834
+ domain,
835
+ FieldStruct,
836
+ ValueStruct,
837
+ test=test,
838
+ output_dtype=output_dtype,
839
+ accumulate_dtype=accumulate_dtype,
840
+ )
841
+ else:
842
+ integrate_kernel_fn = get_integrate_linear_kernel(
843
+ integrand_func,
844
+ domain,
845
+ quadrature,
846
+ FieldStruct,
847
+ ValueStruct,
848
+ test=test,
849
+ output_dtype=output_dtype,
850
+ accumulate_dtype=accumulate_dtype,
851
+ )
852
+ else:
853
+ if nodal:
854
+ integrate_kernel_fn = get_integrate_bilinear_nodal_kernel(
855
+ integrand_func,
856
+ domain,
857
+ FieldStruct,
858
+ ValueStruct,
859
+ test=test,
860
+ output_dtype=output_dtype,
861
+ accumulate_dtype=accumulate_dtype,
862
+ )
863
+ else:
864
+ integrate_kernel_fn = get_integrate_bilinear_kernel(
865
+ integrand_func,
866
+ domain,
867
+ quadrature,
868
+ FieldStruct,
869
+ ValueStruct,
870
+ test=test,
871
+ trial=trial,
872
+ output_dtype=output_dtype,
873
+ accumulate_dtype=accumulate_dtype,
874
+ )
875
+
876
+ kernel = cache.get_integrand_kernel(
877
+ integrand=integrand,
878
+ kernel_fn=integrate_kernel_fn,
879
+ suffix=kernel_suffix,
880
+ kernel_options=kernel_options,
881
+ code_transformers=[
882
+ PassFieldArgsToIntegrand(
883
+ arg_names=integrand.argspec.args,
884
+ field_args=field_args.keys(),
885
+ value_args=value_args.keys(),
886
+ sample_name=sample_name,
887
+ domain_name=domain_name,
888
+ test_name=test_name,
889
+ trial_name=trial_name,
890
+ )
891
+ ],
892
+ )
893
+
894
+ return kernel, FieldStruct, ValueStruct
895
+
896
+
897
+ def _launch_integrate_kernel(
898
+ integrand: Integrand,
899
+ kernel: wp.Kernel,
900
+ FieldStruct: wp.codegen.Struct,
901
+ ValueStruct: wp.codegen.Struct,
902
+ domain: GeometryDomain,
903
+ nodal: bool,
904
+ quadrature: Quadrature,
905
+ test: Optional[TestField],
906
+ trial: Optional[TrialField],
907
+ fields: Dict[str, FieldLike],
908
+ values: Dict[str, Any],
909
+ accumulate_dtype: type,
910
+ temporary_store: Optional[cache.TemporaryStore],
911
+ output_dtype: type,
912
+ output: Optional[Union[wp.array, BsrMatrix]],
913
+ device,
914
+ ):
915
+ # Set-up launch arguments
916
+ domain_elt_arg = domain.element_arg_value(device=device)
917
+ domain_elt_index_arg = domain.element_index_arg_value(device=device)
918
+
919
+ if quadrature is not None:
920
+ qp_arg = quadrature.arg_value(device=device)
921
+
922
+ field_arg_values = FieldStruct()
923
+ for k, v in fields.items():
924
+ setattr(field_arg_values, k, v.eval_arg_value(device=device))
925
+
926
+ value_struct_values = _populate_value_struct(ValueStruct, values, integrand_name=integrand.name)
927
+
928
+ # Constant form
929
+ if test is None and trial is None:
930
+ if output is not None and output.dtype == accumulate_dtype:
931
+ if output.size < 1:
932
+ raise RuntimeError("Output array must be of size at least 1")
933
+ accumulate_array = output
934
+ else:
935
+ accumulate_temporary = cache.borrow_temporary(
936
+ shape=(1),
937
+ device=device,
938
+ dtype=accumulate_dtype,
939
+ temporary_store=temporary_store,
940
+ requires_grad=output is not None and output.requires_grad,
941
+ )
942
+ accumulate_array = accumulate_temporary.array
943
+
944
+ accumulate_array.zero_()
945
+ wp.launch(
946
+ kernel=kernel,
947
+ dim=domain.element_count(),
948
+ inputs=[
949
+ qp_arg,
950
+ domain_elt_arg,
951
+ domain_elt_index_arg,
952
+ field_arg_values,
953
+ value_struct_values,
954
+ accumulate_array,
955
+ ],
956
+ device=device,
957
+ )
958
+
959
+ if output == accumulate_array:
960
+ return output
961
+ elif output is None:
962
+ return accumulate_array.numpy()[0]
963
+ else:
964
+ array_cast(in_array=accumulate_array, out_array=output)
965
+ return output
966
+
967
+ test_arg = test.space_restriction.node_arg(device=device)
968
+
969
+ # Linear form
970
+ if trial is None:
971
+ # If an output array is provided with the correct type, accumulate directly into it
972
+ # Otherwise, grab a temporary array
973
+ if output is None:
974
+ if type_length(output_dtype) == test.space.VALUE_DOF_COUNT:
975
+ output_shape = (test.space_partition.node_count(),)
976
+ elif type_length(output_dtype) == 1:
977
+ output_shape = (test.space_partition.node_count(), test.space.VALUE_DOF_COUNT)
978
+ else:
979
+ raise RuntimeError(
980
+ f"Incompatible output type {wp.types.type_repr(output_dtype)}, must be scalar or vector of length {test.space.VALUE_DOF_COUNT}"
981
+ )
982
+
983
+ output_temporary = cache.borrow_temporary(
984
+ temporary_store=temporary_store,
985
+ shape=output_shape,
986
+ dtype=output_dtype,
987
+ device=device,
988
+ )
989
+
990
+ output = output_temporary.array
991
+
992
+ else:
993
+ output_temporary = None
994
+
995
+ if output.shape[0] < test.space_partition.node_count():
996
+ raise RuntimeError(f"Output array must have at least {test.space_partition.node_count()} rows")
997
+
998
+ output_dtype = output.dtype
999
+ if type_length(output_dtype) != test.space.VALUE_DOF_COUNT:
1000
+ if type_length(output_dtype) != 1:
1001
+ raise RuntimeError(
1002
+ f"Incompatible output type {wp.types.type_repr(output_dtype)}, must be scalar or vector of length {test.space.VALUE_DOF_COUNT}"
1003
+ )
1004
+ if output.ndim != 2 and output.shape[1] != test.space.VALUE_DOF_COUNT:
1005
+ raise RuntimeError(
1006
+ f"Incompatible output array shape, last dimension must be of size {test.space.VALUE_DOF_COUNT}"
1007
+ )
1008
+
1009
+ # Launch the integration on the kernel on a 2d scalar view of the actual array
1010
+ output.zero_()
1011
+
1012
+ def as_2d_array(array):
1013
+ return wp.array(
1014
+ data=None,
1015
+ ptr=array.ptr,
1016
+ capacity=array.capacity,
1017
+ device=array.device,
1018
+ shape=(test.space_partition.node_count(), test.space.VALUE_DOF_COUNT),
1019
+ dtype=wp.types.type_scalar_type(output_dtype),
1020
+ grad=None if array.grad is None else as_2d_array(array.grad),
1021
+ )
1022
+
1023
+ output_view = output if output.ndim == 2 else as_2d_array(output)
1024
+
1025
+ if nodal:
1026
+ wp.launch(
1027
+ kernel=kernel,
1028
+ dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
1029
+ inputs=[
1030
+ domain_elt_arg,
1031
+ domain_elt_index_arg,
1032
+ test_arg,
1033
+ field_arg_values,
1034
+ value_struct_values,
1035
+ output_view,
1036
+ ],
1037
+ device=device,
1038
+ )
1039
+ else:
1040
+ wp.launch(
1041
+ kernel=kernel,
1042
+ dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
1043
+ inputs=[
1044
+ qp_arg,
1045
+ domain_elt_arg,
1046
+ domain_elt_index_arg,
1047
+ test_arg,
1048
+ field_arg_values,
1049
+ value_struct_values,
1050
+ output_view,
1051
+ ],
1052
+ device=device,
1053
+ )
1054
+
1055
+ if output_temporary is not None:
1056
+ return output_temporary.detach()
1057
+
1058
+ return output
1059
+
1060
+ # Bilinear form
1061
+
1062
+ if test.space.VALUE_DOF_COUNT == 1 and trial.space.VALUE_DOF_COUNT == 1:
1063
+ block_type = output_dtype
1064
+ else:
1065
+ block_type = cache.cached_mat_type(
1066
+ shape=(test.space.VALUE_DOF_COUNT, trial.space.VALUE_DOF_COUNT), dtype=output_dtype
1067
+ )
1068
+
1069
+ if nodal:
1070
+ nnz = test.space_restriction.node_count()
1071
+ else:
1072
+ nnz = test.space_restriction.total_node_element_count() * trial.space.topology.NODES_PER_ELEMENT
1073
+
1074
+ triplet_rows_temp = cache.borrow_temporary(temporary_store, shape=(nnz,), dtype=int, device=device)
1075
+ triplet_cols_temp = cache.borrow_temporary(temporary_store, shape=(nnz,), dtype=int, device=device)
1076
+ triplet_values_temp = cache.borrow_temporary(
1077
+ temporary_store,
1078
+ shape=(
1079
+ nnz,
1080
+ test.space.VALUE_DOF_COUNT,
1081
+ trial.space.VALUE_DOF_COUNT,
1082
+ ),
1083
+ dtype=output_dtype,
1084
+ device=device,
1085
+ )
1086
+ triplet_cols = triplet_cols_temp.array
1087
+ triplet_rows = triplet_rows_temp.array
1088
+ triplet_values = triplet_values_temp.array
1089
+
1090
+ triplet_values.zero_()
1091
+
1092
+ if nodal:
1093
+ wp.launch(
1094
+ kernel=kernel,
1095
+ dim=triplet_values.shape,
1096
+ inputs=[
1097
+ domain_elt_arg,
1098
+ domain_elt_index_arg,
1099
+ test_arg,
1100
+ field_arg_values,
1101
+ value_struct_values,
1102
+ triplet_rows,
1103
+ triplet_cols,
1104
+ triplet_values,
1105
+ ],
1106
+ device=device,
1107
+ )
1108
+
1109
+ else:
1110
+ offsets = test.space_restriction.partition_element_offsets()
1111
+
1112
+ trial_partition_arg = trial.space_partition.partition_arg_value(device)
1113
+ trial_topology_arg = trial.space_partition.space_topology.topo_arg_value(device)
1114
+ wp.launch(
1115
+ kernel=kernel,
1116
+ dim=(
1117
+ test.space_restriction.node_count(),
1118
+ trial.space.topology.NODES_PER_ELEMENT,
1119
+ test.space.VALUE_DOF_COUNT,
1120
+ trial.space.VALUE_DOF_COUNT,
1121
+ ),
1122
+ inputs=[
1123
+ qp_arg,
1124
+ domain_elt_arg,
1125
+ domain_elt_index_arg,
1126
+ test_arg,
1127
+ trial_partition_arg,
1128
+ trial_topology_arg,
1129
+ field_arg_values,
1130
+ value_struct_values,
1131
+ offsets,
1132
+ triplet_rows,
1133
+ triplet_cols,
1134
+ triplet_values,
1135
+ ],
1136
+ device=device,
1137
+ )
1138
+
1139
+ if output is not None:
1140
+ if output.nrow != test.space_partition.node_count() or output.ncol != trial.space_partition.node_count():
1141
+ raise RuntimeError(
1142
+ f"Output matrix must have {test.space_partition.node_count()} rows and {trial.space_partition.node_count()} columns of blocks"
1143
+ )
1144
+
1145
+ else:
1146
+ output = bsr_zeros(
1147
+ rows_of_blocks=test.space_partition.node_count(),
1148
+ cols_of_blocks=trial.space_partition.node_count(),
1149
+ block_type=block_type,
1150
+ device=device,
1151
+ )
1152
+
1153
+ bsr_set_from_triplets(output, triplet_rows, triplet_cols, triplet_values)
1154
+
1155
+ # Do not wait for garbage collection
1156
+ triplet_values_temp.release()
1157
+ triplet_rows_temp.release()
1158
+ triplet_cols_temp.release()
1159
+
1160
+ return output
1161
+
1162
+
1163
+ def integrate(
1164
+ integrand: Integrand,
1165
+ domain: Optional[GeometryDomain] = None,
1166
+ quadrature: Optional[Quadrature] = None,
1167
+ nodal: bool = False,
1168
+ fields: Optional[Dict[str, FieldLike]] = None,
1169
+ values: Optional[Dict[str, Any]] = None,
1170
+ accumulate_dtype: type = wp.float64,
1171
+ output_dtype: Optional[type] = None,
1172
+ output: Optional[Union[BsrMatrix, wp.array]] = None,
1173
+ device=None,
1174
+ temporary_store: Optional[cache.TemporaryStore] = None,
1175
+ kernel_options: Optional[Dict[str, Any]] = None,
1176
+ ):
1177
+ """
1178
+ Integrates a constant, linear or bilinear form, and returns a scalar, array, or sparse matrix, respectively.
1179
+
1180
+ Args:
1181
+ integrand: Form to be integrated, must have :func:`integrand` decorator
1182
+ domain: Integration domain. If None, deduced from fields
1183
+ quadrature: Quadrature formula. If None, deduced from domain and fields degree.
1184
+ nodal: For linear or bilinear form only, use the test function nodes as the quadrature points. Assumes Lagrange interpolation functions are used, and no differential or DG operator is evaluated on the test or trial functions.
1185
+ fields: Discrete, test, and trial fields to be passed to the integrand. Keys in the dictionary must match integrand parameter names.
1186
+ values: Additional variable values to be passed to the integrand, can be of any type accepted by warp kernel launches. Keys in the dictionary must match integrand parameter names.
1187
+ temporary_store: shared pool from which to allocate temporary arrays
1188
+ accumulate_dtype: Scalar type to be used for accumulating integration samples
1189
+ output: Sparse matrix or warp array into which to store the result of the integration
1190
+ output_dtype: Scalar type for returned results in `output` is not provided. If None, defaults to `accumulate_dtype`
1191
+ device: Device on which to perform the integration
1192
+ kernel_options: Overloaded options to be passed to the kernel builder (e.g, ``{"enable_backward": True}``)
1193
+ """
1194
+ if fields is None:
1195
+ fields = {}
1196
+
1197
+ if values is None:
1198
+ values = {}
1199
+
1200
+ if kernel_options is None:
1201
+ kernel_options = {}
1202
+
1203
+ if not isinstance(integrand, Integrand):
1204
+ raise ValueError("integrand must be tagged with @warp.fem.integrand decorator")
1205
+
1206
+ test, test_name, trial, trial_name = _get_test_and_trial_fields(fields)
1207
+
1208
+ if domain is None:
1209
+ if quadrature is not None:
1210
+ domain = quadrature.domain
1211
+ elif test is not None:
1212
+ domain = test.domain
1213
+
1214
+ if domain is None:
1215
+ raise ValueError("Must provide at least one of domain, quadrature, or test field")
1216
+ if test is not None and domain != test.domain:
1217
+ raise NotImplementedError("Mixing integration and test domain is not supported yet")
1218
+
1219
+ if nodal:
1220
+ if quadrature is not None:
1221
+ raise ValueError("Cannot specify quadrature for nodal integration")
1222
+
1223
+ if test is None:
1224
+ raise ValueError("Nodal integration requires specifying a test function")
1225
+
1226
+ if trial is not None and test.space_partition != trial.space_partition:
1227
+ raise ValueError(
1228
+ "Bilinear nodal integration requires test and trial to be defined on the same function space"
1229
+ )
1230
+ else:
1231
+ if quadrature is None:
1232
+ order = sum(field.degree for field in fields.values())
1233
+ quadrature = RegularQuadrature(domain=domain, order=order)
1234
+ elif domain != quadrature.domain:
1235
+ raise ValueError("Incompatible integration and quadrature domain")
1236
+
1237
+ # Canonicalize types
1238
+ accumulate_dtype = wp.types.type_to_warp(accumulate_dtype)
1239
+ if output is not None:
1240
+ if isinstance(output, BsrMatrix):
1241
+ output_dtype = output.scalar_type
1242
+ else:
1243
+ output_dtype = output.dtype
1244
+ elif output_dtype is None:
1245
+ output_dtype = accumulate_dtype
1246
+ else:
1247
+ output_dtype = wp.types.type_to_warp(output_dtype)
1248
+
1249
+ kernel, FieldStruct, ValueStruct = _generate_integrate_kernel(
1250
+ integrand=integrand,
1251
+ domain=domain,
1252
+ nodal=nodal,
1253
+ quadrature=quadrature,
1254
+ test=test,
1255
+ test_name=test_name,
1256
+ trial=trial,
1257
+ trial_name=trial_name,
1258
+ fields=fields,
1259
+ accumulate_dtype=accumulate_dtype,
1260
+ output_dtype=output_dtype,
1261
+ kernel_options=kernel_options,
1262
+ )
1263
+
1264
+ return _launch_integrate_kernel(
1265
+ integrand=integrand,
1266
+ kernel=kernel,
1267
+ FieldStruct=FieldStruct,
1268
+ ValueStruct=ValueStruct,
1269
+ domain=domain,
1270
+ nodal=nodal,
1271
+ quadrature=quadrature,
1272
+ test=test,
1273
+ trial=trial,
1274
+ fields=fields,
1275
+ values=values,
1276
+ accumulate_dtype=accumulate_dtype,
1277
+ temporary_store=temporary_store,
1278
+ output_dtype=output_dtype,
1279
+ output=output,
1280
+ device=device,
1281
+ )
1282
+
1283
+
1284
+ def get_interpolate_to_field_function(
1285
+ integrand_func: wp.Function,
1286
+ domain: GeometryDomain,
1287
+ FieldStruct: wp.codegen.Struct,
1288
+ ValueStruct: wp.codegen.Struct,
1289
+ dest: FieldRestriction,
1290
+ ):
1291
+ value_type = dest.space.dtype
1292
+
1293
+ def interpolate_to_field_fn(
1294
+ local_node_index: int,
1295
+ domain_arg: domain.ElementArg,
1296
+ domain_index_arg: domain.ElementIndexArg,
1297
+ dest_node_arg: dest.space_restriction.NodeArg,
1298
+ dest_eval_arg: dest.field.EvalArg,
1299
+ fields: FieldStruct,
1300
+ values: ValueStruct,
1301
+ ):
1302
+ node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
1303
+ element_count = dest.space_restriction.node_element_count(dest_node_arg, local_node_index)
1304
+
1305
+ test_dof_index = NULL_DOF_INDEX
1306
+ trial_dof_index = NULL_DOF_INDEX
1307
+ node_weight = 1.0
1308
+
1309
+ # Volume-weighted average across elements
1310
+ # Superfluous if the interpolated function is continuous, but helpful for visualizing discontinuous spaces
1311
+
1312
+ val_sum = value_type(0.0)
1313
+ vol_sum = float(0.0)
1314
+
1315
+ for n in range(element_count):
1316
+ node_element_index = dest.space_restriction.node_element_index(dest_node_arg, local_node_index, n)
1317
+ element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
1318
+
1319
+ coords = dest.space.node_coords_in_element(
1320
+ domain_arg,
1321
+ dest_eval_arg.space_arg,
1322
+ element_index,
1323
+ node_element_index.node_index_in_element,
1324
+ )
1325
+
1326
+ if coords[0] != OUTSIDE:
1327
+ sample = Sample(
1328
+ element_index,
1329
+ coords,
1330
+ node_index,
1331
+ node_weight,
1332
+ test_dof_index,
1333
+ trial_dof_index,
1334
+ )
1335
+ vol = domain.element_measure(domain_arg, sample)
1336
+ val = integrand_func(sample, fields, values)
1337
+
1338
+ vol_sum += vol
1339
+ val_sum += vol * val
1340
+
1341
+ return val_sum, vol_sum
1342
+
1343
+ return interpolate_to_field_fn
1344
+
1345
+
1346
+ def get_interpolate_to_field_kernel(
1347
+ interpolate_to_field_fn: wp.Function,
1348
+ domain: GeometryDomain,
1349
+ FieldStruct: wp.codegen.Struct,
1350
+ ValueStruct: wp.codegen.Struct,
1351
+ dest: FieldRestriction,
1352
+ ):
1353
+ def interpolate_to_field_kernel_fn(
1354
+ domain_arg: domain.ElementArg,
1355
+ domain_index_arg: domain.ElementIndexArg,
1356
+ dest_node_arg: dest.space_restriction.NodeArg,
1357
+ dest_eval_arg: dest.field.EvalArg,
1358
+ fields: FieldStruct,
1359
+ values: ValueStruct,
1360
+ ):
1361
+ local_node_index = wp.tid()
1362
+
1363
+ val_sum, vol_sum = interpolate_to_field_fn(
1364
+ local_node_index, domain_arg, domain_index_arg, dest_node_arg, dest_eval_arg, fields, values
1365
+ )
1366
+
1367
+ if vol_sum > 0.0:
1368
+ node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
1369
+ dest.field.set_node_value(dest_eval_arg, node_index, val_sum / vol_sum)
1370
+
1371
+ return interpolate_to_field_kernel_fn
1372
+
1373
+
1374
+ def get_interpolate_to_array_kernel(
1375
+ integrand_func: wp.Function,
1376
+ domain: GeometryDomain,
1377
+ quadrature: Quadrature,
1378
+ FieldStruct: wp.codegen.Struct,
1379
+ ValueStruct: wp.codegen.Struct,
1380
+ value_type: type,
1381
+ ):
1382
+ def interpolate_to_array_kernel_fn(
1383
+ qp_arg: quadrature.Arg,
1384
+ domain_arg: quadrature.domain.ElementArg,
1385
+ domain_index_arg: quadrature.domain.ElementIndexArg,
1386
+ fields: FieldStruct,
1387
+ values: ValueStruct,
1388
+ result: wp.array(dtype=value_type),
1389
+ ):
1390
+ element_index = domain.element_index(domain_index_arg, wp.tid())
1391
+
1392
+ test_dof_index = NULL_DOF_INDEX
1393
+ trial_dof_index = NULL_DOF_INDEX
1394
+
1395
+ qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
1396
+ for k in range(qp_point_count):
1397
+ qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
1398
+ coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
1399
+ qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
1400
+
1401
+ sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
1402
+
1403
+ result[qp_index] = integrand_func(sample, fields, values)
1404
+
1405
+ return interpolate_to_array_kernel_fn
1406
+
1407
+
1408
+ def get_interpolate_nonvalued_kernel(
1409
+ integrand_func: wp.Function,
1410
+ domain: GeometryDomain,
1411
+ quadrature: Quadrature,
1412
+ FieldStruct: wp.codegen.Struct,
1413
+ ValueStruct: wp.codegen.Struct,
1414
+ ):
1415
+ def interpolate_nonvalued_kernel_fn(
1416
+ qp_arg: quadrature.Arg,
1417
+ domain_arg: quadrature.domain.ElementArg,
1418
+ domain_index_arg: quadrature.domain.ElementIndexArg,
1419
+ fields: FieldStruct,
1420
+ values: ValueStruct,
1421
+ ):
1422
+ element_index = domain.element_index(domain_index_arg, wp.tid())
1423
+
1424
+ test_dof_index = NULL_DOF_INDEX
1425
+ trial_dof_index = NULL_DOF_INDEX
1426
+
1427
+ qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
1428
+ for k in range(qp_point_count):
1429
+ qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
1430
+ coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
1431
+ qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
1432
+
1433
+ sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
1434
+ integrand_func(sample, fields, values)
1435
+
1436
+ return interpolate_nonvalued_kernel_fn
1437
+
1438
+
1439
+ def _generate_interpolate_kernel(
1440
+ integrand: Integrand,
1441
+ domain: GeometryDomain,
1442
+ dest: Optional[Union[FieldLike, wp.array]],
1443
+ quadrature: Optional[Quadrature],
1444
+ fields: Dict[str, FieldLike],
1445
+ kernel_options: Optional[Dict[str, Any]] = None,
1446
+ ) -> wp.Kernel:
1447
+ if kernel_options is None:
1448
+ kernel_options = {}
1449
+
1450
+ # Extract field arguments from integrand
1451
+ field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
1452
+ integrand, fields=fields, domain=domain
1453
+ )
1454
+
1455
+ # Generate field struct
1456
+ integrand_func = _translate_integrand(
1457
+ integrand,
1458
+ field_args,
1459
+ )
1460
+
1461
+ _register_integrand_field_wrappers(integrand_func, fields)
1462
+
1463
+ FieldStruct = _gen_field_struct(field_args)
1464
+ ValueStruct = _gen_value_struct(value_args)
1465
+
1466
+ # Check if kernel exist in cache
1467
+ if isinstance(dest, FieldRestriction):
1468
+ kernel_suffix = (
1469
+ f"_itp_{FieldStruct.key}_{dest.domain.name}_{dest.space_restriction.space_partition.name}_{dest.space.name}"
1470
+ )
1471
+ elif wp.types.is_array(dest):
1472
+ kernel_suffix = f"_itp_{FieldStruct.key}_{quadrature.name}_{wp.types.type_repr(dest.dtype)}"
1473
+ else:
1474
+ kernel_suffix = f"_itp_{FieldStruct.key}_{quadrature.name}"
1475
+
1476
+ kernel = cache.get_integrand_kernel(
1477
+ integrand=integrand,
1478
+ suffix=kernel_suffix,
1479
+ )
1480
+ if kernel is not None:
1481
+ return kernel, FieldStruct, ValueStruct
1482
+
1483
+ _check_field_compat(integrand, fields, field_args, domain)
1484
+
1485
+ # Generate interpolation kernel
1486
+ if isinstance(dest, FieldRestriction):
1487
+ # need to split into kernel + function for diffferentiability
1488
+ interpolate_fn = get_interpolate_to_field_function(
1489
+ integrand_func,
1490
+ domain,
1491
+ dest=dest,
1492
+ FieldStruct=FieldStruct,
1493
+ ValueStruct=ValueStruct,
1494
+ )
1495
+
1496
+ interpolate_fn = cache.get_integrand_function(
1497
+ integrand=integrand,
1498
+ func=interpolate_fn,
1499
+ suffix=kernel_suffix,
1500
+ code_transformers=[
1501
+ PassFieldArgsToIntegrand(
1502
+ arg_names=integrand.argspec.args,
1503
+ field_args=field_args.keys(),
1504
+ value_args=value_args.keys(),
1505
+ sample_name=sample_name,
1506
+ domain_name=domain_name,
1507
+ )
1508
+ ],
1509
+ )
1510
+
1511
+ interpolate_kernel_fn = get_interpolate_to_field_kernel(
1512
+ interpolate_fn,
1513
+ domain,
1514
+ dest=dest,
1515
+ FieldStruct=FieldStruct,
1516
+ ValueStruct=ValueStruct,
1517
+ )
1518
+ elif wp.types.is_array(dest):
1519
+ interpolate_kernel_fn = get_interpolate_to_array_kernel(
1520
+ integrand_func,
1521
+ domain=domain,
1522
+ quadrature=quadrature,
1523
+ value_type=dest.dtype,
1524
+ FieldStruct=FieldStruct,
1525
+ ValueStruct=ValueStruct,
1526
+ )
1527
+ else:
1528
+ interpolate_kernel_fn = get_interpolate_nonvalued_kernel(
1529
+ integrand_func,
1530
+ domain=domain,
1531
+ quadrature=quadrature,
1532
+ FieldStruct=FieldStruct,
1533
+ ValueStruct=ValueStruct,
1534
+ )
1535
+
1536
+ kernel = cache.get_integrand_kernel(
1537
+ integrand=integrand,
1538
+ kernel_fn=interpolate_kernel_fn,
1539
+ suffix=kernel_suffix,
1540
+ kernel_options=kernel_options,
1541
+ code_transformers=[
1542
+ PassFieldArgsToIntegrand(
1543
+ arg_names=integrand.argspec.args,
1544
+ field_args=field_args.keys(),
1545
+ value_args=value_args.keys(),
1546
+ sample_name=sample_name,
1547
+ domain_name=domain_name,
1548
+ )
1549
+ ],
1550
+ )
1551
+
1552
+ return kernel, FieldStruct, ValueStruct
1553
+
1554
+
1555
+ def _launch_interpolate_kernel(
1556
+ integrand: Integrand,
1557
+ kernel: wp.kernel,
1558
+ FieldStruct: wp.codegen.Struct,
1559
+ ValueStruct: wp.codegen.Struct,
1560
+ domain: GeometryDomain,
1561
+ dest: Optional[Union[FieldRestriction, wp.array]],
1562
+ quadrature: Optional[Quadrature],
1563
+ fields: Dict[str, FieldLike],
1564
+ values: Dict[str, Any],
1565
+ device,
1566
+ ) -> wp.Kernel:
1567
+ # Set-up launch arguments
1568
+ elt_arg = domain.element_arg_value(device=device)
1569
+ elt_index_arg = domain.element_index_arg_value(device=device)
1570
+
1571
+ field_arg_values = FieldStruct()
1572
+ for k, v in fields.items():
1573
+ setattr(field_arg_values, k, v.eval_arg_value(device=device))
1574
+
1575
+ value_struct_values = _populate_value_struct(ValueStruct, values, integrand_name=integrand.name)
1576
+
1577
+ if isinstance(dest, FieldRestriction):
1578
+ dest_node_arg = dest.space_restriction.node_arg(device=device)
1579
+ dest_eval_arg = dest.field.eval_arg_value(device=device)
1580
+
1581
+ wp.launch(
1582
+ kernel=kernel,
1583
+ dim=dest.space_restriction.node_count(),
1584
+ inputs=[
1585
+ elt_arg,
1586
+ elt_index_arg,
1587
+ dest_node_arg,
1588
+ dest_eval_arg,
1589
+ field_arg_values,
1590
+ value_struct_values,
1591
+ ],
1592
+ device=device,
1593
+ )
1594
+ elif wp.types.is_array(dest):
1595
+ qp_arg = quadrature.arg_value(device)
1596
+ wp.launch(
1597
+ kernel=kernel,
1598
+ dim=domain.element_count(),
1599
+ inputs=[qp_arg, elt_arg, elt_index_arg, field_arg_values, value_struct_values, dest],
1600
+ device=device,
1601
+ )
1602
+ else:
1603
+ qp_arg = quadrature.arg_value(device)
1604
+ wp.launch(
1605
+ kernel=kernel,
1606
+ dim=domain.element_count(),
1607
+ inputs=[qp_arg, elt_arg, elt_index_arg, field_arg_values, value_struct_values],
1608
+ device=device,
1609
+ )
1610
+
1611
+
1612
+ def interpolate(
1613
+ integrand: Integrand,
1614
+ dest: Optional[Union[DiscreteField, FieldRestriction, wp.array]] = None,
1615
+ quadrature: Optional[Quadrature] = None,
1616
+ fields: Optional[Dict[str, FieldLike]] = None,
1617
+ values: Optional[Dict[str, Any]] = None,
1618
+ device=None,
1619
+ kernel_options: Optional[Dict[str, Any]] = None,
1620
+ ):
1621
+ """
1622
+ Interpolates a function at a finite set of sample points and optionally assigns the result to a discrete field or a raw warp array.
1623
+
1624
+ Args:
1625
+ integrand: Function to be interpolated, must have :func:`integrand` decorator
1626
+ dest: Where to store the interpolation result. Can be either
1627
+
1628
+ - a :class:`DiscreteField`, or restriction of a discrete field to a domain (from :func:`make_restriction`). In this case, interpolation will be performed at each node.
1629
+ - a normal warp array. In this case, the `quadrature` argument defining the interpolation locations must be provided and the result of the `integrand` at each quadrature point will be assigned to the array.
1630
+ - ``None``. In this case, the `quadrature` argument must also be provided and the `integrand` function is responsible for dealing with the interpolation result.
1631
+ quadrature: Quadrature formula defining the interpolation samples if `dest` is not a discrete field or field restriction.
1632
+ fields: Discrete fields to be passed to the integrand. Keys in the dictionary must match integrand parameters names.
1633
+ values: Additional variable values to be passed to the integrand, can be of any type accepted by warp kernel launches. Keys in the dictionary must match integrand parameter names.
1634
+ device: Device on which to perform the interpolation
1635
+ kernel_options: Overloaded options to be passed to the kernel builder (e.g, ``{"enable_backward": True}``)
1636
+ """
1637
+ if fields is None:
1638
+ fields = {}
1639
+
1640
+ if values is None:
1641
+ values = {}
1642
+
1643
+ if kernel_options is None:
1644
+ kernel_options = {}
1645
+
1646
+ if not isinstance(integrand, Integrand):
1647
+ raise ValueError("integrand must be tagged with @integrand decorator")
1648
+
1649
+ test, _, trial, __ = _get_test_and_trial_fields(fields)
1650
+ if test is not None or trial is not None:
1651
+ raise ValueError("Test or Trial fields should not be used for interpolation")
1652
+
1653
+ if isinstance(dest, DiscreteField):
1654
+ dest = make_restriction(dest)
1655
+
1656
+ if isinstance(dest, FieldRestriction):
1657
+ domain = dest.domain
1658
+ else:
1659
+ if quadrature is None:
1660
+ raise ValueError("When not interpolating to a field, a quadrature formula must be provided")
1661
+
1662
+ domain = quadrature.domain
1663
+
1664
+ kernel, FieldStruct, ValueStruct = _generate_interpolate_kernel(
1665
+ integrand=integrand,
1666
+ domain=domain,
1667
+ dest=dest,
1668
+ quadrature=quadrature,
1669
+ fields=fields,
1670
+ kernel_options=kernel_options,
1671
+ )
1672
+
1673
+ return _launch_interpolate_kernel(
1674
+ integrand=integrand,
1675
+ kernel=kernel,
1676
+ FieldStruct=FieldStruct,
1677
+ ValueStruct=ValueStruct,
1678
+ domain=domain,
1679
+ dest=dest,
1680
+ quadrature=quadrature,
1681
+ fields=fields,
1682
+ values=values,
1683
+ device=device,
1684
+ )