warp-lang 1.0.2__py3-none-manylinux2014_x86_64.whl → 1.2.0__py3-none-manylinux2014_x86_64.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.so +0 -0
  4. warp/bin/warp.so +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
@@ -1,835 +1,862 @@
1
- # Copyright (c) 2024 NVIDIA CORPORATION. All rights reserved.
2
- # NVIDIA CORPORATION and its licensors retain all intellectual property
3
- # and proprietary rights in and to this software, related documentation
4
- # and any modifications thereto. Any use, reproduction, disclosure or
5
- # distribution of this software and related documentation without an express
6
- # license agreement from NVIDIA CORPORATION is strictly prohibited.
7
-
8
- ###########################################################################
9
- # Example Drone
10
- #
11
- # A drone and its 4 propellers is simulated with the goal of reaching
12
- # different targets via model-predictive control (MPC) that continuously
13
- # optimizes the control trajectory.
14
- #
15
- ###########################################################################
16
-
17
- import os
18
- from typing import Optional, Tuple
19
-
20
- import numpy as np
21
- from pxr import UsdGeom
22
-
23
- import warp as wp
24
- import warp.examples
25
- import warp.optim
26
- import warp.sim
27
- import warp.sim.render
28
- from warp.sim.collide import (
29
- box_sdf,
30
- capsule_sdf,
31
- cone_sdf,
32
- cylinder_sdf,
33
- mesh_sdf,
34
- plane_sdf,
35
- sphere_sdf,
36
- )
37
-
38
- wp.init()
39
-
40
-
41
- @wp.struct
42
- class Propeller:
43
- body: int
44
- pos: wp.vec3
45
- dir: wp.vec3
46
- thrust: float
47
- power: float
48
- diameter: float
49
- height: float
50
- max_rpm: float
51
- max_thrust: float
52
- max_torque: float
53
- turning_direction: float
54
- max_speed_square: float
55
-
56
-
57
- @wp.kernel
58
- def increment_seed(
59
- seed: wp.array(dtype=int),
60
- ):
61
- seed[0] += 1
62
-
63
-
64
- @wp.kernel
65
- def sample_gaussian(
66
- mean_trajectory: wp.array(dtype=float, ndim=3),
67
- noise_scale: float,
68
- num_control_points: int,
69
- control_dim: int,
70
- control_limits: wp.array(dtype=float, ndim=2),
71
- seed: wp.array(dtype=int),
72
- rollout_trajectories: wp.array(dtype=float, ndim=3),
73
- ):
74
- env_id, point_id, control_id = wp.tid()
75
- unique_id = (env_id * num_control_points + point_id) * control_dim + control_id
76
- r = wp.rand_init(seed[0], unique_id)
77
- mean = mean_trajectory[0, point_id, control_id]
78
- lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
79
- sample = mean + noise_scale * wp.randn(r)
80
- for i in range(10):
81
- if sample < lo or sample > hi:
82
- sample = mean + noise_scale * wp.randn(r)
83
- else:
84
- break
85
- rollout_trajectories[env_id, point_id, control_id] = wp.clamp(sample, lo, hi)
86
-
87
-
88
- @wp.kernel
89
- def replicate_states(
90
- body_q_in: wp.array(dtype=wp.transform),
91
- body_qd_in: wp.array(dtype=wp.spatial_vector),
92
- bodies_per_env: int,
93
- body_q_out: wp.array(dtype=wp.transform),
94
- body_qd_out: wp.array(dtype=wp.spatial_vector),
95
- ):
96
- tid = wp.tid()
97
- env_offset = tid * bodies_per_env
98
- for i in range(bodies_per_env):
99
- body_q_out[env_offset + i] = body_q_in[i]
100
- body_qd_out[env_offset + i] = body_qd_in[i]
101
-
102
-
103
- @wp.kernel
104
- def drone_cost(
105
- body_q: wp.array(dtype=wp.transform),
106
- body_qd: wp.array(dtype=wp.spatial_vector),
107
- target: wp.vec3,
108
- prop_control: wp.array(dtype=float),
109
- step: int,
110
- horizon_length: int,
111
- weighting: float,
112
- cost: wp.array(dtype=wp.float32),
113
- ):
114
- env_id = wp.tid()
115
- tf = body_q[env_id]
116
-
117
- pos_drone = wp.transform_get_translation(tf)
118
- pos_cost = wp.length_sq(pos_drone - target)
119
- altitude_cost = wp.max(pos_drone[1] - 0.75, 0.0) + wp.max(0.25 - pos_drone[1], 0.0)
120
- upvector = wp.vec3(0.0, 1.0, 0.0)
121
- drone_up = wp.transform_vector(tf, upvector)
122
- upright_cost = 1.0 - wp.dot(drone_up, upvector)
123
-
124
- vel_drone = body_qd[env_id]
125
-
126
- # Encourage zero velocity.
127
- vel_cost = wp.length_sq(vel_drone)
128
-
129
- control = wp.vec4(
130
- prop_control[env_id * 4 + 0],
131
- prop_control[env_id * 4 + 1],
132
- prop_control[env_id * 4 + 2],
133
- prop_control[env_id * 4 + 3],
134
- )
135
- control_cost = wp.dot(control, control)
136
-
137
- discount = 0.8 ** wp.float(horizon_length - step - 1) / wp.float(horizon_length) ** 2.0
138
-
139
- pos_weight = 1000.0
140
- altitude_weight = 100.0
141
- control_weight = 0.05
142
- vel_weight = 0.1
143
- upright_weight = 10.0
144
- total_weight = pos_weight + altitude_weight + control_weight + vel_weight + upright_weight
145
-
146
- wp.atomic_add(
147
- cost,
148
- env_id,
149
- (
150
- pos_cost * pos_weight
151
- + altitude_cost * altitude_weight
152
- + control_cost * control_weight
153
- + vel_cost * vel_weight
154
- + upright_cost * upright_weight
155
- )
156
- * (weighting / total_weight)
157
- * discount,
158
- )
159
-
160
-
161
- @wp.kernel
162
- def collision_cost(
163
- body_q: wp.array(dtype=wp.transform),
164
- obstacle_ids: wp.array(dtype=int, ndim=2),
165
- shape_X_bs: wp.array(dtype=wp.transform),
166
- geo: wp.sim.ModelShapeGeometry,
167
- margin: float,
168
- weighting: float,
169
- cost: wp.array(dtype=wp.float32),
170
- ):
171
- env_id, obs_id = wp.tid()
172
- shape_index = obstacle_ids[env_id, obs_id]
173
-
174
- px = wp.transform_get_translation(body_q[env_id])
175
-
176
- X_bs = shape_X_bs[shape_index]
177
-
178
- # transform particle position to shape local space
179
- x_local = wp.transform_point(X_bs, px)
180
-
181
- # geo description
182
- geo_type = geo.type[shape_index]
183
- geo_scale = geo.scale[shape_index]
184
-
185
- # evaluate shape sdf
186
- d = 1e6
187
-
188
- if geo_type == wp.sim.GEO_SPHERE:
189
- d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
190
- elif geo_type == wp.sim.GEO_BOX:
191
- d = box_sdf(geo_scale, x_local)
192
- elif geo_type == wp.sim.GEO_CAPSULE:
193
- d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
194
- elif geo_type == wp.sim.GEO_CYLINDER:
195
- d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
196
- elif geo_type == wp.sim.GEO_CONE:
197
- d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
198
- elif geo_type == wp.sim.GEO_MESH:
199
- mesh = geo.source[shape_index]
200
- min_scale = wp.min(geo_scale)
201
- max_dist = margin / min_scale
202
- d = mesh_sdf(mesh, wp.cw_div(x_local, geo_scale), max_dist)
203
- d *= min_scale # TODO fix this, mesh scaling needs to be handled properly
204
- elif geo_type == wp.sim.GEO_SDF:
205
- volume = geo.source[shape_index]
206
- xpred_local = wp.volume_world_to_index(volume, wp.cw_div(x_local, geo_scale))
207
- nn = wp.vec3(0.0, 0.0, 0.0)
208
- d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, nn)
209
- elif geo_type == wp.sim.GEO_PLANE:
210
- d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
211
-
212
- d = wp.max(d, 0.0)
213
- if d < margin:
214
- c = margin - d
215
- wp.atomic_add(cost, env_id, weighting * c)
216
-
217
-
218
- @wp.kernel
219
- def enforce_control_limits(
220
- control_limits: wp.array(dtype=float, ndim=2),
221
- control_points: wp.array(dtype=float, ndim=3),
222
- ):
223
- env_id, t_id, control_id = wp.tid()
224
- lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
225
- control_points[env_id, t_id, control_id] = wp.clamp(control_points[env_id, t_id, control_id], lo, hi)
226
-
227
-
228
- @wp.kernel
229
- def pick_best_trajectory(
230
- rollout_trajectories: wp.array(dtype=float, ndim=3),
231
- lowest_cost_id: int,
232
- best_traj: wp.array(dtype=float, ndim=3),
233
- ):
234
- t_id, control_id = wp.tid()
235
- best_traj[0, t_id, control_id] = rollout_trajectories[lowest_cost_id, t_id, control_id]
236
-
237
-
238
- @wp.kernel
239
- def interpolate_control_linear(
240
- control_points: wp.array(dtype=float, ndim=3),
241
- control_dofs: wp.array(dtype=int),
242
- control_gains: wp.array(dtype=float),
243
- t: float,
244
- torque_dim: int,
245
- torques: wp.array(dtype=float),
246
- ):
247
- env_id, control_id = wp.tid()
248
- t_id = int(t)
249
- frac = t - wp.floor(t)
250
- control_left = control_points[env_id, t_id, control_id]
251
- control_right = control_points[env_id, t_id + 1, control_id]
252
- torque_id = env_id * torque_dim + control_dofs[control_id]
253
- action = control_left * (1.0 - frac) + control_right * frac
254
- torques[torque_id] = action * control_gains[control_id]
255
-
256
-
257
- @wp.kernel
258
- def compute_prop_wrenches(
259
- props: wp.array(dtype=Propeller),
260
- controls: wp.array(dtype=float),
261
- body_q: wp.array(dtype=wp.transform),
262
- body_com: wp.array(dtype=wp.vec3),
263
- body_f: wp.array(dtype=wp.spatial_vector),
264
- ):
265
- tid = wp.tid()
266
- prop = props[tid]
267
- control = controls[tid]
268
- tf = body_q[prop.body]
269
- dir = wp.transform_vector(tf, prop.dir)
270
- force = dir * prop.max_thrust * control
271
- torque = dir * prop.max_torque * control * prop.turning_direction
272
- moment_arm = wp.transform_point(tf, prop.pos) - wp.transform_point(tf, body_com[prop.body])
273
- torque += wp.cross(moment_arm, force)
274
- # Apply angular damping.
275
- torque *= 0.8
276
- wp.atomic_add(body_f, prop.body, wp.spatial_vector(torque, force))
277
-
278
-
279
- def define_propeller(
280
- drone: int,
281
- pos: wp.vec3,
282
- fps: float,
283
- thrust: float = 0.109919,
284
- power: float = 0.040164,
285
- diameter: float = 0.2286,
286
- height: float = 0.01,
287
- max_rpm: float = 6396.667,
288
- turning_direction: float = 1.0,
289
- ):
290
- # Air density at sea level.
291
- air_density = 1.225 # kg / m^3
292
-
293
- rps = max_rpm / fps
294
- max_speed = rps * wp.TAU # radians / sec
295
- rps_square = rps**2
296
-
297
- prop = Propeller()
298
- prop.body = drone
299
- prop.pos = pos
300
- prop.dir = wp.vec3(0.0, 1.0, 0.0)
301
- prop.thrust = thrust
302
- prop.power = power
303
- prop.diameter = diameter
304
- prop.height = height
305
- prop.max_rpm = max_rpm
306
- prop.max_thrust = thrust * air_density * rps_square * diameter**4
307
- prop.max_torque = power * air_density * rps_square * diameter**5 / wp.TAU
308
- prop.turning_direction = turning_direction
309
- prop.max_speed_square = max_speed**2
310
-
311
- return prop
312
-
313
-
314
- class Drone:
315
- def __init__(
316
- self,
317
- name: str,
318
- fps: float,
319
- trajectory_shape: Tuple[int, int],
320
- variation_count: int = 1,
321
- size: float = 1.0,
322
- requires_grad: bool = False,
323
- state_count: Optional[int] = None,
324
- ) -> None:
325
- self.variation_count = variation_count
326
- self.requires_grad = requires_grad
327
-
328
- # Current tick of the simulation, including substeps.
329
- self.sim_tick = 0
330
-
331
- # Initialize the helper to build a physics scene.
332
- builder = wp.sim.ModelBuilder()
333
- builder.rigid_contact_margin = 0.05
334
-
335
- # Initialize the rigid bodies, propellers, and colliders.
336
- props = []
337
- colliders = []
338
- crossbar_length = size
339
- crossbar_height = size * 0.05
340
- crossbar_width = size * 0.05
341
- carbon_fiber_density = 1750.0 # kg / m^3
342
- for i in range(variation_count):
343
- # Register the drone as a rigid body in the simulation model.
344
- body = builder.add_body(name=f"{name}_{i}")
345
-
346
- # Define the shapes making up the drone's rigid body.
347
- builder.add_shape_box(
348
- body,
349
- hx=crossbar_length,
350
- hy=crossbar_height,
351
- hz=crossbar_width,
352
- density=carbon_fiber_density,
353
- collision_group=i,
354
- )
355
- builder.add_shape_box(
356
- body,
357
- hx=crossbar_width,
358
- hy=crossbar_height,
359
- hz=crossbar_length,
360
- density=carbon_fiber_density,
361
- collision_group=i,
362
- )
363
-
364
- # Initialize the propellers.
365
- props.extend(
366
- (
367
- define_propeller(
368
- body,
369
- wp.vec3(crossbar_length, 0.0, 0.0),
370
- fps,
371
- turning_direction=-1.0,
372
- ),
373
- define_propeller(
374
- body,
375
- wp.vec3(-crossbar_length, 0.0, 0.0),
376
- fps,
377
- turning_direction=1.0,
378
- ),
379
- define_propeller(
380
- body,
381
- wp.vec3(0.0, 0.0, crossbar_length),
382
- fps,
383
- turning_direction=1.0,
384
- ),
385
- define_propeller(
386
- body,
387
- wp.vec3(0.0, 0.0, -crossbar_length),
388
- fps,
389
- turning_direction=-1.0,
390
- ),
391
- ),
392
- )
393
-
394
- # Initialize the colliders.
395
- colliders.append(
396
- (
397
- builder.add_shape_capsule(
398
- -1,
399
- pos=(0.5, 2.0, 0.5),
400
- radius=0.15,
401
- half_height=2.0,
402
- collision_group=i,
403
- ),
404
- ),
405
- )
406
- self.props = wp.array(props, dtype=Propeller)
407
- self.colliders = wp.array(colliders, dtype=int)
408
-
409
- # Build the model and set-up its properties.
410
- self.model = builder.finalize(requires_grad=requires_grad)
411
- self.model.ground = False
412
-
413
- # Initialize the required simulation states.
414
- if requires_grad:
415
- self.states = tuple(self.model.state() for _ in range(state_count + 1))
416
- self.controls = tuple(self.model.control() for _ in range(state_count))
417
- else:
418
- # When only running a forward simulation, we don't need to store
419
- # the history of the states at each step, instead we use double
420
- # buffering to represent the previous and next states.
421
- self.states = [self.model.state(), self.model.state()]
422
- self.controls = (self.model.control(),)
423
-
424
- # create array for the propeller controls
425
- for control in self.controls:
426
- control.prop_controls = wp.zeros(len(self.props), dtype=float, requires_grad=requires_grad)
427
-
428
- # Define the trajectories as arrays of control points.
429
- # The point data has an additional item to support linear interpolation.
430
- self.trajectories = wp.zeros(
431
- (variation_count, trajectory_shape[0], trajectory_shape[1]),
432
- dtype=float,
433
- requires_grad=requires_grad,
434
- )
435
-
436
- # Store some miscellaneous info.
437
- self.body_count = len(builder.body_q)
438
- self.collider_count = self.colliders.shape[1]
439
- self.collision_radius = crossbar_length * 2.0
440
-
441
- @property
442
- def state(self) -> wp.sim.State:
443
- return self.states[self.sim_tick if self.requires_grad else 0]
444
-
445
- @property
446
- def next_state(self) -> wp.sim.State:
447
- return self.states[self.sim_tick + 1 if self.requires_grad else 1]
448
-
449
- @property
450
- def control(self) -> wp.sim.Control:
451
- return self.controls[min(len(self.controls) - 1, self.sim_tick) if self.requires_grad else 0]
452
-
453
-
454
- class Example:
455
- def __init__(
456
- self,
457
- stage: Optional[str] = None,
458
- drone_path: Optional[str] = None,
459
- enable_rendering: bool = True,
460
- render_rollouts: bool = True,
461
- verbose: bool = False,
462
- ) -> None:
463
- # Duration of the simulation, in seconds.
464
- duration = 6.0
465
-
466
- # Number of frames per second.
467
- self.fps = 60.0
468
-
469
- # Duration of the simulation in number of frames.
470
- self.frame_count = int(duration * self.fps)
471
-
472
- # Number of simulation substeps to take per step.
473
- self.sim_substep_count = 1
474
-
475
- # Delta time between each simulation substep.
476
- self.frame_dt = 1.0 / self.fps
477
-
478
- # Delta time between each simulation substep.
479
- self.sim_dt = self.frame_dt / self.sim_substep_count
480
-
481
- # Frame number used for simulation and rendering.
482
- self.frame = 0
483
-
484
- # Targets positions that the drone will try to reach in turn.
485
- self.targets = (
486
- wp.vec3(0.0, 0.5, 1.0),
487
- wp.vec3(1.0, 0.5, 0.0),
488
- )
489
-
490
- # Define the index of the active target.
491
- # We start with -1 since it'll be incremented on the first frame.
492
- self.target_idx = -1
493
-
494
- # Number of steps to run at each frame for the optimisation pass.
495
- self.optim_step_count = 20
496
-
497
- # Time steps between control points.
498
- self.control_point_step = 10
499
-
500
- # Number of control horizon points to interpolate between.
501
- self.control_point_count = 3
502
-
503
- self.control_point_data_count = self.control_point_count + 1
504
- self.control_dofs = wp.array((0, 1, 2, 3), dtype=int)
505
- self.control_dim = len(self.control_dofs)
506
- self.control_gains = wp.array((0.8,) * self.control_dim, dtype=float)
507
- self.control_limits = wp.array(((0.1, 1.0),) * self.control_dim, dtype=float)
508
-
509
- drone_size = 0.2
510
-
511
- # Declare the reference drone.
512
- self.drone = Drone(
513
- "drone",
514
- self.fps,
515
- (self.control_point_data_count, self.control_dim),
516
- size=drone_size,
517
- )
518
-
519
- # Declare the drone's rollouts.
520
- # These allow to run parallel simulations in order to find the best
521
- # trajectory at each control point.
522
- self.rollout_count = 16
523
- self.rollout_step_count = self.control_point_step * self.control_point_count
524
- self.rollouts = Drone(
525
- "rollout",
526
- self.fps,
527
- (self.control_point_data_count, self.control_dim),
528
- variation_count=self.rollout_count,
529
- size=drone_size,
530
- requires_grad=True,
531
- state_count=self.rollout_step_count * self.sim_substep_count,
532
- )
533
-
534
- self.seed = wp.zeros(1, dtype=int)
535
- self.rollout_costs = wp.zeros(self.rollout_count, dtype=float, requires_grad=True)
536
-
537
- # Use the Euler integrator for stepping through the simulation.
538
- self.integrator = wp.sim.SemiImplicitIntegrator()
539
-
540
- self.optimizer = wp.optim.SGD(
541
- [self.rollouts.trajectories.flatten()],
542
- lr=1e-2,
543
- nesterov=False,
544
- momentum=0.0,
545
- )
546
-
547
- self.tape = None
548
-
549
- if enable_rendering:
550
- # Helper to render the physics scene as a USD file.
551
- self.renderer = wp.sim.render.SimRenderer(self.drone.model, stage, fps=self.fps)
552
-
553
- if isinstance(self.renderer, warp.sim.render.SimRendererUsd):
554
- from pxr import UsdGeom
555
-
556
- # Remove the default drone geometries.
557
- drone_root_prim = self.renderer.stage.GetPrimAtPath("/root/body_0_drone_0")
558
- for prim in drone_root_prim.GetChildren():
559
- self.renderer.stage.RemovePrim(prim.GetPath())
560
-
561
- # Add a reference to the drone geometry.
562
- drone_prim = self.renderer.stage.OverridePrim(f"{drone_root_prim.GetPath()}/crazyflie")
563
- drone_prim.GetReferences().AddReference(drone_path)
564
- drone_xform = UsdGeom.Xform(drone_prim)
565
- drone_xform.AddTranslateOp().Set((0.0, -0.05, 0.0))
566
- drone_xform.AddRotateYOp().Set(45.0)
567
- drone_xform.AddScaleOp().Set((drone_size * 0.2,) * 3)
568
-
569
- # Get the propellers to spin
570
- for turning_direction in ("CW", "CCW"):
571
- spin = 100.0 * 360.0 * self.frame_count / self.fps
572
- spin = spin if turning_direction == "CCW" else -spin
573
- for side in ("Back", "Front"):
574
- prop_prim = self.renderer.stage.OverridePrim(
575
- f"{drone_prim.GetPath()}/Propeller{turning_direction}{side}"
576
- )
577
- prop_xform = UsdGeom.Xform(prop_prim)
578
- rot = prop_xform.AddRotateYOp()
579
- rot.Set(0.0, 0.0)
580
- rot.Set(spin, self.frame_count)
581
- else:
582
- self.renderer = None
583
-
584
- self.use_cuda_graph = True
585
- self.optim_graph = None
586
-
587
- self.render_rollouts = render_rollouts
588
- self.verbose = verbose
589
-
590
- def update_drone(self, drone: Drone) -> None:
591
- drone.state.clear_forces()
592
-
593
- wp.launch(
594
- interpolate_control_linear,
595
- dim=(
596
- drone.variation_count,
597
- self.control_dim,
598
- ),
599
- inputs=(
600
- drone.trajectories,
601
- self.control_dofs,
602
- self.control_gains,
603
- drone.sim_tick / (self.sim_substep_count * self.control_point_step),
604
- self.control_dim,
605
- ),
606
- outputs=(drone.control.prop_controls,),
607
- )
608
-
609
- wp.sim.collide(drone.model, drone.state)
610
-
611
- wp.launch(
612
- compute_prop_wrenches,
613
- dim=len(drone.props),
614
- inputs=(
615
- drone.props,
616
- drone.control.prop_controls,
617
- drone.state.body_q,
618
- drone.model.body_com,
619
- ),
620
- outputs=(drone.state.body_f,),
621
- )
622
-
623
- self.integrator.simulate(
624
- drone.model,
625
- drone.state,
626
- drone.next_state,
627
- self.sim_dt,
628
- drone.control,
629
- )
630
-
631
- drone.sim_tick += 1
632
-
633
- def forward(self):
634
- # Evaluate the rollouts with their costs.
635
- self.rollouts.sim_tick = 0
636
- self.rollout_costs.zero_()
637
- wp.launch(
638
- replicate_states,
639
- dim=self.rollout_count,
640
- inputs=(
641
- self.drone.state.body_q,
642
- self.drone.state.body_qd,
643
- self.drone.body_count,
644
- ),
645
- outputs=(
646
- self.rollouts.state.body_q,
647
- self.rollouts.state.body_qd,
648
- ),
649
- )
650
-
651
- for i in range(self.rollout_step_count):
652
- for _ in range(self.sim_substep_count):
653
- self.update_drone(self.rollouts)
654
-
655
- wp.launch(
656
- drone_cost,
657
- dim=self.rollout_count,
658
- inputs=(
659
- self.rollouts.state.body_q,
660
- self.rollouts.state.body_qd,
661
- self.targets[self.target_idx],
662
- self.rollouts.control.prop_controls,
663
- i,
664
- self.rollout_step_count,
665
- 1e3,
666
- ),
667
- outputs=(self.rollout_costs,),
668
- )
669
- wp.launch(
670
- collision_cost,
671
- dim=(
672
- self.rollout_count,
673
- self.rollouts.collider_count,
674
- ),
675
- inputs=(
676
- self.rollouts.state.body_q,
677
- self.rollouts.colliders,
678
- self.rollouts.model.shape_transform,
679
- self.rollouts.model.shape_geo,
680
- self.rollouts.collision_radius,
681
- 1e4,
682
- ),
683
- outputs=(self.rollout_costs,),
684
- )
685
-
686
- def step_optimizer(self):
687
- if self.optim_graph is None:
688
- self.tape = wp.Tape()
689
- with self.tape:
690
- self.forward()
691
- self.rollout_costs.grad.fill_(1.0)
692
- self.tape.backward()
693
- else:
694
- wp.capture_launch(self.optim_graph)
695
-
696
- self.optimizer.step([self.rollouts.trajectories.grad.flatten()])
697
-
698
- # Enforce limits on the control points.
699
- wp.launch(
700
- enforce_control_limits,
701
- dim=self.rollouts.trajectories.shape,
702
- inputs=(self.control_limits,),
703
- outputs=(self.rollouts.trajectories,),
704
- )
705
- self.tape.zero()
706
-
707
- def step(self):
708
- if self.frame % int((self.frame_count / len(self.targets))) == 0:
709
- if self.verbose:
710
- print(f"Choosing new flight target: {self.target_idx+1}")
711
-
712
- self.target_idx += 1
713
-
714
- # Force recapturing the CUDA graph for the optimization pass
715
- # by invalidating it.
716
- self.optim_graph = None
717
-
718
- if self.use_cuda_graph and self.optim_graph is None:
719
- with wp.ScopedCapture() as capture:
720
- self.tape = wp.Tape()
721
- with self.tape:
722
- self.forward()
723
- self.rollout_costs.grad.fill_(1.0)
724
- self.tape.backward()
725
- self.optim_graph = capture.graph
726
-
727
- # Sample control waypoints around the nominal trajectory.
728
- self.seed.zero_()
729
- noise_scale = 0.15
730
- wp.launch(
731
- sample_gaussian,
732
- dim=(
733
- self.rollouts.trajectories.shape[0] - 1,
734
- self.rollouts.trajectories.shape[1],
735
- self.rollouts.trajectories.shape[2],
736
- ),
737
- inputs=(
738
- self.drone.trajectories,
739
- noise_scale,
740
- self.control_point_data_count,
741
- self.control_dim,
742
- self.control_limits,
743
- self.seed,
744
- ),
745
- outputs=(self.rollouts.trajectories,),
746
- )
747
-
748
- wp.launch(
749
- increment_seed,
750
- dim=1,
751
- inputs=(),
752
- outputs=(self.seed,),
753
- )
754
-
755
- for _ in range(self.optim_step_count):
756
- self.step_optimizer()
757
-
758
- # Pick the best trajectory.
759
- wp.synchronize()
760
- lowest_cost_id = np.argmin(self.rollout_costs.numpy())
761
- wp.launch(
762
- pick_best_trajectory,
763
- dim=(
764
- self.control_point_data_count,
765
- self.control_dim,
766
- ),
767
- inputs=(
768
- self.rollouts.trajectories,
769
- lowest_cost_id,
770
- ),
771
- outputs=(self.drone.trajectories,),
772
- )
773
- self.rollouts.trajectories[-1].assign(self.drone.trajectories[0])
774
-
775
- # Simulate the drone.
776
- self.drone.sim_tick = 0
777
- for _ in range(self.sim_substep_count):
778
- self.update_drone(self.drone)
779
-
780
- # Swap the drone's states.
781
- (self.drone.states[0], self.drone.states[1]) = (self.drone.states[1], self.drone.states[0])
782
-
783
- def render(self):
784
- if self.renderer is None:
785
- return
786
-
787
- self.renderer.begin_frame(self.frame / self.fps)
788
- self.renderer.render(self.drone.state)
789
-
790
- # Render a sphere as the current target.
791
- self.renderer.render_sphere(
792
- "target",
793
- self.targets[self.target_idx],
794
- wp.quat_identity(),
795
- 0.05,
796
- color=(1.0, 0.0, 0.0),
797
- )
798
-
799
- # Render the rollout trajectories.
800
- if self.render_rollouts:
801
- costs = self.rollout_costs.numpy()
802
-
803
- positions = np.array([x.body_q.numpy()[:, :3] for x in self.rollouts.states])
804
-
805
- min_cost = np.min(costs)
806
- max_cost = np.max(costs)
807
- for i in range(self.rollout_count):
808
- # Flip colors, so red means best trajectory, blue worst.
809
- color = wp.render.bourke_color_map(-max_cost, -min_cost, -costs[i])
810
- self.renderer.render_line_strip(
811
- name=f"rollout_{i}",
812
- vertices=positions[:, i],
813
- color=color,
814
- radius=0.001,
815
- )
816
-
817
- self.renderer.end_frame()
818
-
819
-
820
- if __name__ == "__main__":
821
- drone_path = os.path.join(warp.examples.get_asset_directory(), "crazyflie.usd")
822
- stage_path = "example_drone.usd"
823
-
824
- example = Example(stage_path, drone_path, verbose=True)
825
- for i in range(example.frame_count):
826
- example.step()
827
- example.render()
828
- example.frame += 1
829
-
830
- if example.verbose:
831
- loss = np.min(example.rollout_costs.numpy())
832
- print(f"[{example.frame:3d}/{example.frame_count}] loss={loss:.8f}")
833
-
834
- if example.renderer is not None:
835
- example.renderer.save()
1
+ # Copyright (c) 2024 NVIDIA CORPORATION. All rights reserved.
2
+ # NVIDIA CORPORATION and its licensors retain all intellectual property
3
+ # and proprietary rights in and to this software, related documentation
4
+ # and any modifications thereto. Any use, reproduction, disclosure or
5
+ # distribution of this software and related documentation without an express
6
+ # license agreement from NVIDIA CORPORATION is strictly prohibited.
7
+
8
+ ###########################################################################
9
+ # Example Drone
10
+ #
11
+ # A drone and its 4 propellers is simulated with the goal of reaching
12
+ # different targets via model-predictive control (MPC) that continuously
13
+ # optimizes the control trajectory.
14
+ #
15
+ ###########################################################################
16
+
17
+ import os
18
+ from typing import Optional, Tuple
19
+
20
+ import numpy as np
21
+
22
+ import warp as wp
23
+ import warp.examples
24
+ import warp.optim
25
+ import warp.sim
26
+ import warp.sim.render
27
+ from warp.sim.collide import box_sdf, capsule_sdf, cone_sdf, cylinder_sdf, mesh_sdf, plane_sdf, sphere_sdf
28
+
29
+ DEFAULT_DRONE_PATH = os.path.join(warp.examples.get_asset_directory(), "crazyflie.usd") # Path to input drone asset
30
+
31
+
32
+ @wp.struct
33
+ class Propeller:
34
+ body: int
35
+ pos: wp.vec3
36
+ dir: wp.vec3
37
+ thrust: float
38
+ power: float
39
+ diameter: float
40
+ height: float
41
+ max_rpm: float
42
+ max_thrust: float
43
+ max_torque: float
44
+ turning_direction: float
45
+ max_speed_square: float
46
+
47
+
48
+ @wp.kernel
49
+ def increment_seed(
50
+ seed: wp.array(dtype=int),
51
+ ):
52
+ seed[0] += 1
53
+
54
+
55
+ @wp.kernel
56
+ def sample_gaussian(
57
+ mean_trajectory: wp.array(dtype=float, ndim=3),
58
+ noise_scale: float,
59
+ num_control_points: int,
60
+ control_dim: int,
61
+ control_limits: wp.array(dtype=float, ndim=2),
62
+ seed: wp.array(dtype=int),
63
+ rollout_trajectories: wp.array(dtype=float, ndim=3),
64
+ ):
65
+ env_id, point_id, control_id = wp.tid()
66
+ unique_id = (env_id * num_control_points + point_id) * control_dim + control_id
67
+ r = wp.rand_init(seed[0], unique_id)
68
+ mean = mean_trajectory[0, point_id, control_id]
69
+ lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
70
+ sample = mean + noise_scale * wp.randn(r)
71
+ for _i in range(10):
72
+ if sample < lo or sample > hi:
73
+ sample = mean + noise_scale * wp.randn(r)
74
+ else:
75
+ break
76
+ rollout_trajectories[env_id, point_id, control_id] = wp.clamp(sample, lo, hi)
77
+
78
+
79
+ @wp.kernel
80
+ def replicate_states(
81
+ body_q_in: wp.array(dtype=wp.transform),
82
+ body_qd_in: wp.array(dtype=wp.spatial_vector),
83
+ bodies_per_env: int,
84
+ body_q_out: wp.array(dtype=wp.transform),
85
+ body_qd_out: wp.array(dtype=wp.spatial_vector),
86
+ ):
87
+ tid = wp.tid()
88
+ env_offset = tid * bodies_per_env
89
+ for i in range(bodies_per_env):
90
+ body_q_out[env_offset + i] = body_q_in[i]
91
+ body_qd_out[env_offset + i] = body_qd_in[i]
92
+
93
+
94
+ @wp.kernel
95
+ def drone_cost(
96
+ body_q: wp.array(dtype=wp.transform),
97
+ body_qd: wp.array(dtype=wp.spatial_vector),
98
+ targets: wp.array(dtype=wp.vec3),
99
+ prop_control: wp.array(dtype=float),
100
+ step: int,
101
+ horizon_length: int,
102
+ weighting: float,
103
+ cost: wp.array(dtype=wp.float32),
104
+ ):
105
+ env_id = wp.tid()
106
+ tf = body_q[env_id]
107
+ target = targets[0]
108
+
109
+ pos_drone = wp.transform_get_translation(tf)
110
+ pos_cost = wp.length_sq(pos_drone - target)
111
+ altitude_cost = wp.max(pos_drone[1] - 0.75, 0.0) + wp.max(0.25 - pos_drone[1], 0.0)
112
+ upvector = wp.vec3(0.0, 1.0, 0.0)
113
+ drone_up = wp.transform_vector(tf, upvector)
114
+ upright_cost = 1.0 - wp.dot(drone_up, upvector)
115
+
116
+ vel_drone = body_qd[env_id]
117
+
118
+ # Encourage zero velocity.
119
+ vel_cost = wp.length_sq(vel_drone)
120
+
121
+ control = wp.vec4(
122
+ prop_control[env_id * 4 + 0],
123
+ prop_control[env_id * 4 + 1],
124
+ prop_control[env_id * 4 + 2],
125
+ prop_control[env_id * 4 + 3],
126
+ )
127
+ control_cost = wp.dot(control, control)
128
+
129
+ discount = 0.8 ** wp.float(horizon_length - step - 1) / wp.float(horizon_length) ** 2.0
130
+
131
+ pos_weight = 1000.0
132
+ altitude_weight = 100.0
133
+ control_weight = 0.05
134
+ vel_weight = 0.1
135
+ upright_weight = 10.0
136
+ total_weight = pos_weight + altitude_weight + control_weight + vel_weight + upright_weight
137
+
138
+ wp.atomic_add(
139
+ cost,
140
+ env_id,
141
+ (
142
+ pos_cost * pos_weight
143
+ + altitude_cost * altitude_weight
144
+ + control_cost * control_weight
145
+ + vel_cost * vel_weight
146
+ + upright_cost * upright_weight
147
+ )
148
+ * (weighting / total_weight)
149
+ * discount,
150
+ )
151
+
152
+
153
+ @wp.kernel
154
+ def collision_cost(
155
+ body_q: wp.array(dtype=wp.transform),
156
+ obstacle_ids: wp.array(dtype=int, ndim=2),
157
+ shape_X_bs: wp.array(dtype=wp.transform),
158
+ geo: wp.sim.ModelShapeGeometry,
159
+ margin: float,
160
+ weighting: float,
161
+ cost: wp.array(dtype=wp.float32),
162
+ ):
163
+ env_id, obs_id = wp.tid()
164
+ shape_index = obstacle_ids[env_id, obs_id]
165
+
166
+ px = wp.transform_get_translation(body_q[env_id])
167
+
168
+ X_bs = shape_X_bs[shape_index]
169
+
170
+ # transform particle position to shape local space
171
+ x_local = wp.transform_point(wp.transform_inverse(X_bs), px)
172
+
173
+ # geo description
174
+ geo_type = geo.type[shape_index]
175
+ geo_scale = geo.scale[shape_index]
176
+
177
+ # evaluate shape sdf
178
+ d = 1e6
179
+
180
+ if geo_type == wp.sim.GEO_SPHERE:
181
+ d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
182
+ elif geo_type == wp.sim.GEO_BOX:
183
+ d = box_sdf(geo_scale, x_local)
184
+ elif geo_type == wp.sim.GEO_CAPSULE:
185
+ d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
186
+ elif geo_type == wp.sim.GEO_CYLINDER:
187
+ d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
188
+ elif geo_type == wp.sim.GEO_CONE:
189
+ d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
190
+ elif geo_type == wp.sim.GEO_MESH:
191
+ mesh = geo.source[shape_index]
192
+ min_scale = wp.min(geo_scale)
193
+ max_dist = margin / min_scale
194
+ d = mesh_sdf(mesh, wp.cw_div(x_local, geo_scale), max_dist)
195
+ d *= min_scale # TODO fix this, mesh scaling needs to be handled properly
196
+ elif geo_type == wp.sim.GEO_SDF:
197
+ volume = geo.source[shape_index]
198
+ xpred_local = wp.volume_world_to_index(volume, wp.cw_div(x_local, geo_scale))
199
+ nn = wp.vec3(0.0, 0.0, 0.0)
200
+ d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, nn)
201
+ elif geo_type == wp.sim.GEO_PLANE:
202
+ d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
203
+
204
+ d = wp.max(d, 0.0)
205
+ if d < margin:
206
+ c = margin - d
207
+ wp.atomic_add(cost, env_id, weighting * c)
208
+
209
+
210
+ @wp.kernel
211
+ def enforce_control_limits(
212
+ control_limits: wp.array(dtype=float, ndim=2),
213
+ control_points: wp.array(dtype=float, ndim=3),
214
+ ):
215
+ env_id, t_id, control_id = wp.tid()
216
+ lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
217
+ control_points[env_id, t_id, control_id] = wp.clamp(control_points[env_id, t_id, control_id], lo, hi)
218
+
219
+
220
+ @wp.kernel
221
+ def pick_best_trajectory(
222
+ rollout_trajectories: wp.array(dtype=float, ndim=3),
223
+ lowest_cost_id: int,
224
+ best_traj: wp.array(dtype=float, ndim=3),
225
+ ):
226
+ t_id, control_id = wp.tid()
227
+ best_traj[0, t_id, control_id] = rollout_trajectories[lowest_cost_id, t_id, control_id]
228
+
229
+
230
+ @wp.kernel
231
+ def interpolate_control_linear(
232
+ control_points: wp.array(dtype=float, ndim=3),
233
+ control_dofs: wp.array(dtype=int),
234
+ control_gains: wp.array(dtype=float),
235
+ t: float,
236
+ torque_dim: int,
237
+ torques: wp.array(dtype=float),
238
+ ):
239
+ env_id, control_id = wp.tid()
240
+ t_id = int(t)
241
+ frac = t - wp.floor(t)
242
+ control_left = control_points[env_id, t_id, control_id]
243
+ control_right = control_points[env_id, t_id + 1, control_id]
244
+ torque_id = env_id * torque_dim + control_dofs[control_id]
245
+ action = control_left * (1.0 - frac) + control_right * frac
246
+ torques[torque_id] = action * control_gains[control_id]
247
+
248
+
249
+ @wp.kernel
250
+ def compute_prop_wrenches(
251
+ props: wp.array(dtype=Propeller),
252
+ controls: wp.array(dtype=float),
253
+ body_q: wp.array(dtype=wp.transform),
254
+ body_com: wp.array(dtype=wp.vec3),
255
+ body_f: wp.array(dtype=wp.spatial_vector),
256
+ ):
257
+ tid = wp.tid()
258
+ prop = props[tid]
259
+ control = controls[tid]
260
+ tf = body_q[prop.body]
261
+ dir = wp.transform_vector(tf, prop.dir)
262
+ force = dir * prop.max_thrust * control
263
+ torque = dir * prop.max_torque * control * prop.turning_direction
264
+ moment_arm = wp.transform_point(tf, prop.pos) - wp.transform_point(tf, body_com[prop.body])
265
+ torque += wp.cross(moment_arm, force)
266
+ # Apply angular damping.
267
+ torque *= 0.8
268
+ wp.atomic_add(body_f, prop.body, wp.spatial_vector(torque, force))
269
+
270
+
271
+ def define_propeller(
272
+ drone: int,
273
+ pos: wp.vec3,
274
+ fps: float,
275
+ thrust: float = 0.109919,
276
+ power: float = 0.040164,
277
+ diameter: float = 0.2286,
278
+ height: float = 0.01,
279
+ max_rpm: float = 6396.667,
280
+ turning_direction: float = 1.0,
281
+ ):
282
+ # Air density at sea level.
283
+ air_density = 1.225 # kg / m^3
284
+
285
+ rps = max_rpm / fps
286
+ max_speed = rps * wp.TAU # radians / sec
287
+ rps_square = rps**2
288
+
289
+ prop = Propeller()
290
+ prop.body = drone
291
+ prop.pos = pos
292
+ prop.dir = wp.vec3(0.0, 1.0, 0.0)
293
+ prop.thrust = thrust
294
+ prop.power = power
295
+ prop.diameter = diameter
296
+ prop.height = height
297
+ prop.max_rpm = max_rpm
298
+ prop.max_thrust = thrust * air_density * rps_square * diameter**4
299
+ prop.max_torque = power * air_density * rps_square * diameter**5 / wp.TAU
300
+ prop.turning_direction = turning_direction
301
+ prop.max_speed_square = max_speed**2
302
+
303
+ return prop
304
+
305
+
306
+ class Drone:
307
+ def __init__(
308
+ self,
309
+ name: str,
310
+ fps: float,
311
+ trajectory_shape: Tuple[int, int],
312
+ variation_count: int = 1,
313
+ size: float = 1.0,
314
+ requires_grad: bool = False,
315
+ state_count: Optional[int] = None,
316
+ ) -> None:
317
+ self.variation_count = variation_count
318
+ self.requires_grad = requires_grad
319
+
320
+ # Current tick of the simulation, including substeps.
321
+ self.sim_tick = 0
322
+
323
+ # Initialize the helper to build a physics scene.
324
+ builder = wp.sim.ModelBuilder()
325
+ builder.rigid_contact_margin = 0.05
326
+
327
+ # Initialize the rigid bodies, propellers, and colliders.
328
+ props = []
329
+ colliders = []
330
+ crossbar_length = size
331
+ crossbar_height = size * 0.05
332
+ crossbar_width = size * 0.05
333
+ carbon_fiber_density = 1750.0 # kg / m^3
334
+ for i in range(variation_count):
335
+ # Register the drone as a rigid body in the simulation model.
336
+ body = builder.add_body(name=f"{name}_{i}")
337
+
338
+ # Define the shapes making up the drone's rigid body.
339
+ builder.add_shape_box(
340
+ body,
341
+ hx=crossbar_length,
342
+ hy=crossbar_height,
343
+ hz=crossbar_width,
344
+ density=carbon_fiber_density,
345
+ collision_group=i,
346
+ )
347
+ builder.add_shape_box(
348
+ body,
349
+ hx=crossbar_width,
350
+ hy=crossbar_height,
351
+ hz=crossbar_length,
352
+ density=carbon_fiber_density,
353
+ collision_group=i,
354
+ )
355
+
356
+ # Initialize the propellers.
357
+ props.extend(
358
+ (
359
+ define_propeller(
360
+ body,
361
+ wp.vec3(crossbar_length, 0.0, 0.0),
362
+ fps,
363
+ turning_direction=-1.0,
364
+ ),
365
+ define_propeller(
366
+ body,
367
+ wp.vec3(-crossbar_length, 0.0, 0.0),
368
+ fps,
369
+ turning_direction=1.0,
370
+ ),
371
+ define_propeller(
372
+ body,
373
+ wp.vec3(0.0, 0.0, crossbar_length),
374
+ fps,
375
+ turning_direction=1.0,
376
+ ),
377
+ define_propeller(
378
+ body,
379
+ wp.vec3(0.0, 0.0, -crossbar_length),
380
+ fps,
381
+ turning_direction=-1.0,
382
+ ),
383
+ ),
384
+ )
385
+
386
+ # Initialize the colliders.
387
+ colliders.append(
388
+ (
389
+ builder.add_shape_capsule(
390
+ -1,
391
+ pos=(0.5, 2.0, 0.5),
392
+ radius=0.15,
393
+ half_height=2.0,
394
+ collision_group=i,
395
+ ),
396
+ ),
397
+ )
398
+ self.props = wp.array(props, dtype=Propeller)
399
+ self.colliders = wp.array(colliders, dtype=int)
400
+
401
+ # Build the model and set-up its properties.
402
+ self.model = builder.finalize(requires_grad=requires_grad)
403
+ self.model.ground = False
404
+
405
+ # Initialize the required simulation states.
406
+ if requires_grad:
407
+ self.states = tuple(self.model.state() for _ in range(state_count + 1))
408
+ self.controls = tuple(self.model.control() for _ in range(state_count))
409
+ else:
410
+ # When only running a forward simulation, we don't need to store
411
+ # the history of the states at each step, instead we use double
412
+ # buffering to represent the previous and next states.
413
+ self.states = [self.model.state(), self.model.state()]
414
+ self.controls = (self.model.control(),)
415
+
416
+ # create array for the propeller controls
417
+ for control in self.controls:
418
+ control.prop_controls = wp.zeros(len(self.props), dtype=float, requires_grad=requires_grad)
419
+
420
+ # Define the trajectories as arrays of control points.
421
+ # The point data has an additional item to support linear interpolation.
422
+ self.trajectories = wp.zeros(
423
+ (variation_count, trajectory_shape[0], trajectory_shape[1]),
424
+ dtype=float,
425
+ requires_grad=requires_grad,
426
+ )
427
+
428
+ # Store some miscellaneous info.
429
+ self.body_count = len(builder.body_q)
430
+ self.collider_count = self.colliders.shape[1]
431
+ self.collision_radius = crossbar_length
432
+
433
+ @property
434
+ def state(self) -> wp.sim.State:
435
+ return self.states[self.sim_tick if self.requires_grad else 0]
436
+
437
+ @property
438
+ def next_state(self) -> wp.sim.State:
439
+ return self.states[self.sim_tick + 1 if self.requires_grad else 1]
440
+
441
+ @property
442
+ def control(self) -> wp.sim.Control:
443
+ return self.controls[min(len(self.controls) - 1, self.sim_tick) if self.requires_grad else 0]
444
+
445
+
446
+ class Example:
447
+ def __init__(
448
+ self,
449
+ stage_path="example_drone.usd",
450
+ verbose=False,
451
+ render_rollouts=False,
452
+ drone_path=DEFAULT_DRONE_PATH,
453
+ num_frames=360,
454
+ num_rollouts=16,
455
+ headless=True,
456
+ ) -> None:
457
+ # Number of frames per second.
458
+ self.fps = 60
459
+
460
+ # Duration of the simulation in number of frames.
461
+ self.num_frames = num_frames
462
+
463
+ # Number of simulation substeps to take per step.
464
+ self.sim_substep_count = 1
465
+
466
+ # Delta time between each simulation substep.
467
+ self.frame_dt = 1.0 / self.fps
468
+
469
+ # Delta time between each simulation substep.
470
+ self.sim_dt = self.frame_dt / self.sim_substep_count
471
+
472
+ # Frame number used for simulation and rendering.
473
+ self.frame = 0
474
+
475
+ # Targets positions that the drone will try to reach in turn.
476
+ self.targets = (
477
+ wp.vec3(0.0, 0.5, 1.0),
478
+ wp.vec3(1.0, 0.5, 0.0),
479
+ )
480
+
481
+ # Define the index of the active target.
482
+ # We start with -1 since it'll be incremented on the first frame.
483
+ self.target_idx = -1
484
+ # use a Warp array to store the current target so that we can assign
485
+ # a new target to it while retaining the original CUDA graph.
486
+ self.current_target = wp.array([self.targets[self.target_idx + 1]], dtype=wp.vec3)
487
+
488
+ # Number of steps to run at each frame for the optimisation pass.
489
+ self.optim_step_count = 20
490
+
491
+ # Time steps between control points.
492
+ self.control_point_step = 10
493
+
494
+ # Number of control horizon points to interpolate between.
495
+ self.control_point_count = 3
496
+
497
+ self.control_point_data_count = self.control_point_count + 1
498
+ self.control_dofs = wp.array((0, 1, 2, 3), dtype=int)
499
+ self.control_dim = len(self.control_dofs)
500
+ self.control_gains = wp.array((0.8,) * self.control_dim, dtype=float)
501
+ self.control_limits = wp.array(((0.1, 1.0),) * self.control_dim, dtype=float)
502
+
503
+ drone_size = 0.2
504
+
505
+ # Declare the reference drone.
506
+ self.drone = Drone(
507
+ "drone",
508
+ self.fps,
509
+ (self.control_point_data_count, self.control_dim),
510
+ size=drone_size,
511
+ )
512
+
513
+ # Declare the drone's rollouts.
514
+ # These allow to run parallel simulations in order to find the best
515
+ # trajectory at each control point.
516
+ self.rollout_count = num_rollouts
517
+ self.rollout_step_count = self.control_point_step * self.control_point_count
518
+ self.rollouts = Drone(
519
+ "rollout",
520
+ self.fps,
521
+ (self.control_point_data_count, self.control_dim),
522
+ variation_count=self.rollout_count,
523
+ size=drone_size,
524
+ requires_grad=True,
525
+ state_count=self.rollout_step_count * self.sim_substep_count,
526
+ )
527
+
528
+ self.seed = wp.zeros(1, dtype=int)
529
+ self.rollout_costs = wp.zeros(self.rollout_count, dtype=float, requires_grad=True)
530
+
531
+ # Use the Euler integrator for stepping through the simulation.
532
+ self.integrator = wp.sim.SemiImplicitIntegrator()
533
+
534
+ self.optimizer = wp.optim.SGD(
535
+ [self.rollouts.trajectories.flatten()],
536
+ lr=1e-2,
537
+ nesterov=False,
538
+ momentum=0.0,
539
+ )
540
+
541
+ self.tape = None
542
+
543
+ if stage_path:
544
+ if not headless:
545
+ self.renderer = wp.sim.render.SimRendererOpenGL(self.drone.model, stage_path, fps=self.fps)
546
+ else:
547
+ # Helper to render the physics scene as a USD file.
548
+ self.renderer = wp.sim.render.SimRenderer(self.drone.model, stage_path, fps=self.fps)
549
+
550
+ if isinstance(self.renderer, warp.sim.render.SimRendererUsd):
551
+ from pxr import UsdGeom
552
+
553
+ # Remove the default drone geometries.
554
+ drone_root_prim = self.renderer.stage.GetPrimAtPath("/root/body_0_drone_0")
555
+ for prim in drone_root_prim.GetChildren():
556
+ self.renderer.stage.RemovePrim(prim.GetPath())
557
+
558
+ # Add a reference to the drone geometry.
559
+ drone_prim = self.renderer.stage.OverridePrim(f"{drone_root_prim.GetPath()}/crazyflie")
560
+ drone_prim.GetReferences().AddReference(drone_path)
561
+ drone_xform = UsdGeom.Xform(drone_prim)
562
+ drone_xform.AddTranslateOp().Set((0.0, -0.05, 0.0))
563
+ drone_xform.AddRotateYOp().Set(45.0)
564
+ drone_xform.AddScaleOp().Set((drone_size * 20.0,) * 3)
565
+
566
+ # Get the propellers to spin
567
+ for turning_direction in ("cw", "ccw"):
568
+ spin = 100.0 * 360.0 * self.num_frames / self.fps
569
+ spin = spin if turning_direction == "ccw" else -spin
570
+ for side in ("back", "front"):
571
+ prop_prim = self.renderer.stage.OverridePrim(
572
+ f"{drone_prim.GetPath()}/propeller_{turning_direction}_{side}"
573
+ )
574
+ prop_xform = UsdGeom.Xform(prop_prim)
575
+ rot = prop_xform.AddRotateYOp()
576
+ rot.Set(0.0, 0.0)
577
+ rot.Set(spin, self.num_frames)
578
+ else:
579
+ self.renderer = None
580
+
581
+ self.use_cuda_graph = wp.get_device().is_cuda
582
+ self.optim_graph = None
583
+
584
+ self.render_rollouts = render_rollouts
585
+ self.verbose = verbose
586
+
587
+ def update_drone(self, drone: Drone) -> None:
588
+ drone.state.clear_forces()
589
+
590
+ wp.launch(
591
+ interpolate_control_linear,
592
+ dim=(
593
+ drone.variation_count,
594
+ self.control_dim,
595
+ ),
596
+ inputs=(
597
+ drone.trajectories,
598
+ self.control_dofs,
599
+ self.control_gains,
600
+ drone.sim_tick / (self.sim_substep_count * self.control_point_step),
601
+ self.control_dim,
602
+ ),
603
+ outputs=(drone.control.prop_controls,),
604
+ )
605
+
606
+ wp.launch(
607
+ compute_prop_wrenches,
608
+ dim=len(drone.props),
609
+ inputs=(
610
+ drone.props,
611
+ drone.control.prop_controls,
612
+ drone.state.body_q,
613
+ drone.model.body_com,
614
+ ),
615
+ outputs=(drone.state.body_f,),
616
+ )
617
+
618
+ self.integrator.simulate(
619
+ drone.model,
620
+ drone.state,
621
+ drone.next_state,
622
+ self.sim_dt,
623
+ drone.control,
624
+ )
625
+
626
+ drone.sim_tick += 1
627
+
628
+ def forward(self):
629
+ # Evaluate the rollouts with their costs.
630
+ self.rollouts.sim_tick = 0
631
+ self.rollout_costs.zero_()
632
+ wp.launch(
633
+ replicate_states,
634
+ dim=self.rollout_count,
635
+ inputs=(
636
+ self.drone.state.body_q,
637
+ self.drone.state.body_qd,
638
+ self.drone.body_count,
639
+ ),
640
+ outputs=(
641
+ self.rollouts.state.body_q,
642
+ self.rollouts.state.body_qd,
643
+ ),
644
+ )
645
+
646
+ for i in range(self.rollout_step_count):
647
+ for _ in range(self.sim_substep_count):
648
+ self.update_drone(self.rollouts)
649
+
650
+ wp.launch(
651
+ drone_cost,
652
+ dim=self.rollout_count,
653
+ inputs=(
654
+ self.rollouts.state.body_q,
655
+ self.rollouts.state.body_qd,
656
+ self.current_target,
657
+ self.rollouts.control.prop_controls,
658
+ i,
659
+ self.rollout_step_count,
660
+ 1e3,
661
+ ),
662
+ outputs=(self.rollout_costs,),
663
+ )
664
+ wp.launch(
665
+ collision_cost,
666
+ dim=(
667
+ self.rollout_count,
668
+ self.rollouts.collider_count,
669
+ ),
670
+ inputs=(
671
+ self.rollouts.state.body_q,
672
+ self.rollouts.colliders,
673
+ self.rollouts.model.shape_transform,
674
+ self.rollouts.model.shape_geo,
675
+ self.rollouts.collision_radius,
676
+ 1e4,
677
+ ),
678
+ outputs=(self.rollout_costs,),
679
+ )
680
+
681
+ def step_optimizer(self):
682
+ if self.optim_graph is None:
683
+ self.tape = wp.Tape()
684
+ with self.tape:
685
+ self.forward()
686
+ self.rollout_costs.grad.fill_(1.0)
687
+ self.tape.backward()
688
+ else:
689
+ wp.capture_launch(self.optim_graph)
690
+
691
+ self.optimizer.step([self.rollouts.trajectories.grad.flatten()])
692
+
693
+ # Enforce limits on the control points.
694
+ wp.launch(
695
+ enforce_control_limits,
696
+ dim=self.rollouts.trajectories.shape,
697
+ inputs=(self.control_limits,),
698
+ outputs=(self.rollouts.trajectories,),
699
+ )
700
+ self.tape.zero()
701
+
702
+ def step(self):
703
+ if self.frame % int((self.num_frames / len(self.targets))) == 0:
704
+ if self.verbose:
705
+ print(f"Choosing new flight target: {self.target_idx+1}")
706
+
707
+ self.target_idx += 1
708
+ self.target_idx %= len(self.targets)
709
+
710
+ # Assign the new target to the current target array.
711
+ self.current_target.assign([self.targets[self.target_idx]])
712
+
713
+ if self.use_cuda_graph and self.optim_graph is None:
714
+ with wp.ScopedCapture() as capture:
715
+ self.tape = wp.Tape()
716
+ with self.tape:
717
+ self.forward()
718
+ self.rollout_costs.grad.fill_(1.0)
719
+ self.tape.backward()
720
+ self.optim_graph = capture.graph
721
+
722
+ # Sample control waypoints around the nominal trajectory.
723
+ noise_scale = 0.15
724
+ wp.launch(
725
+ sample_gaussian,
726
+ dim=(
727
+ self.rollouts.trajectories.shape[0] - 1,
728
+ self.rollouts.trajectories.shape[1],
729
+ self.rollouts.trajectories.shape[2],
730
+ ),
731
+ inputs=(
732
+ self.drone.trajectories,
733
+ noise_scale,
734
+ self.control_point_data_count,
735
+ self.control_dim,
736
+ self.control_limits,
737
+ self.seed,
738
+ ),
739
+ outputs=(self.rollouts.trajectories,),
740
+ )
741
+
742
+ wp.launch(
743
+ increment_seed,
744
+ dim=1,
745
+ inputs=(),
746
+ outputs=(self.seed,),
747
+ )
748
+
749
+ for _ in range(self.optim_step_count):
750
+ self.step_optimizer()
751
+
752
+ # Pick the best trajectory.
753
+ wp.synchronize()
754
+ lowest_cost_id = np.argmin(self.rollout_costs.numpy())
755
+ wp.launch(
756
+ pick_best_trajectory,
757
+ dim=(
758
+ self.control_point_data_count,
759
+ self.control_dim,
760
+ ),
761
+ inputs=(
762
+ self.rollouts.trajectories,
763
+ lowest_cost_id,
764
+ ),
765
+ outputs=(self.drone.trajectories,),
766
+ )
767
+ self.rollouts.trajectories[-1].assign(self.drone.trajectories[0])
768
+
769
+ # Simulate the drone.
770
+ self.drone.sim_tick = 0
771
+ for _ in range(self.sim_substep_count):
772
+ self.update_drone(self.drone)
773
+
774
+ # Swap the drone's states.
775
+ (self.drone.states[0], self.drone.states[1]) = (self.drone.states[1], self.drone.states[0])
776
+
777
+ def render(self):
778
+ if self.renderer is None:
779
+ return
780
+
781
+ self.renderer.begin_frame(self.frame / self.fps)
782
+ self.renderer.render(self.drone.state)
783
+
784
+ # Render a sphere as the current target.
785
+ self.renderer.render_sphere(
786
+ "target",
787
+ self.targets[self.target_idx],
788
+ wp.quat_identity(),
789
+ 0.05,
790
+ color=(1.0, 0.0, 0.0),
791
+ )
792
+
793
+ # Render the rollout trajectories.
794
+ if self.render_rollouts:
795
+ costs = self.rollout_costs.numpy()
796
+
797
+ positions = np.array([x.body_q.numpy()[:, :3] for x in self.rollouts.states])
798
+
799
+ min_cost = np.min(costs)
800
+ max_cost = np.max(costs)
801
+ for i in range(self.rollout_count):
802
+ # Flip colors, so red means best trajectory, blue worst.
803
+ color = wp.render.bourke_color_map(-max_cost, -min_cost, -costs[i])
804
+ self.renderer.render_line_strip(
805
+ name=f"rollout_{i}",
806
+ vertices=positions[:, i],
807
+ color=color,
808
+ radius=0.001,
809
+ )
810
+
811
+ self.renderer.end_frame()
812
+
813
+
814
+ if __name__ == "__main__":
815
+ import argparse
816
+
817
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
818
+ parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
819
+ parser.add_argument(
820
+ "--stage_path",
821
+ type=lambda x: None if x == "None" else str(x),
822
+ default="example_drone.usd",
823
+ help="Path to the output USD file.",
824
+ )
825
+ parser.add_argument("--num_frames", type=int, default=360, help="Total number of frames.")
826
+ parser.add_argument("--num_rollouts", type=int, default=16, help="Number of drone rollouts.")
827
+ parser.add_argument(
828
+ "--drone_path",
829
+ type=str,
830
+ default=os.path.join(warp.examples.get_asset_directory(), "crazyflie.usd"),
831
+ help="Path to the USD file to use as the reference for the drone prim in the output stage.",
832
+ )
833
+ parser.add_argument("--render_rollouts", action="store_true", help="Add rollout trajectories to the output stage.")
834
+ parser.add_argument(
835
+ "--headless",
836
+ action="store_true",
837
+ help="Run in headless mode, suppressing the opening of any graphical windows.",
838
+ )
839
+ parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
840
+
841
+ args = parser.parse_known_args()[0]
842
+
843
+ with wp.ScopedDevice(args.device):
844
+ example = Example(
845
+ stage_path=args.stage_path,
846
+ verbose=args.verbose,
847
+ render_rollouts=args.render_rollouts,
848
+ drone_path=args.drone_path,
849
+ num_frames=args.num_frames,
850
+ num_rollouts=args.num_rollouts,
851
+ headless=args.headless,
852
+ )
853
+ for _i in range(args.num_frames):
854
+ example.step()
855
+ example.render()
856
+ example.frame += 1
857
+
858
+ loss = np.min(example.rollout_costs.numpy())
859
+ print(f"[{example.frame:3d}/{example.num_frames}] loss={loss:.8f}")
860
+
861
+ if example.renderer is not None:
862
+ example.renderer.save()