warp-lang 1.0.1__py3-none-manylinux2014_aarch64.whl → 1.1.0__py3-none-manylinux2014_aarch64.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 (346) 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 +115 -113
  6. warp/build_dll.py +383 -375
  7. warp/builtins.py +3425 -3354
  8. warp/codegen.py +2878 -2792
  9. warp/config.py +40 -36
  10. warp/constants.py +45 -45
  11. warp/context.py +5194 -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 +383 -383
  26. warp/examples/benchmarks/benchmark_cloth.py +278 -279
  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 +146 -146
  34. warp/examples/benchmarks/benchmark_launches.py +295 -295
  35. warp/examples/browse.py +29 -28
  36. warp/examples/core/example_dem.py +234 -221
  37. warp/examples/core/example_fluid.py +293 -267
  38. warp/examples/core/example_graph_capture.py +144 -129
  39. warp/examples/core/example_marching_cubes.py +188 -176
  40. warp/examples/core/example_mesh.py +174 -154
  41. warp/examples/core/example_mesh_intersect.py +205 -193
  42. warp/examples/core/example_nvdb.py +176 -169
  43. warp/examples/core/example_raycast.py +105 -89
  44. warp/examples/core/example_raymarch.py +199 -178
  45. warp/examples/core/example_render_opengl.py +185 -141
  46. warp/examples/core/example_sph.py +405 -389
  47. warp/examples/core/example_torch.py +222 -181
  48. warp/examples/core/example_wave.py +263 -249
  49. warp/examples/fem/bsr_utils.py +378 -380
  50. warp/examples/fem/example_apic_fluid.py +407 -391
  51. warp/examples/fem/example_convection_diffusion.py +182 -168
  52. warp/examples/fem/example_convection_diffusion_dg.py +219 -209
  53. warp/examples/fem/example_convection_diffusion_dg0.py +204 -194
  54. warp/examples/fem/example_deformed_geometry.py +177 -159
  55. warp/examples/fem/example_diffusion.py +201 -173
  56. warp/examples/fem/example_diffusion_3d.py +177 -152
  57. warp/examples/fem/example_diffusion_mgpu.py +221 -214
  58. warp/examples/fem/example_mixed_elasticity.py +244 -222
  59. warp/examples/fem/example_navier_stokes.py +259 -243
  60. warp/examples/fem/example_stokes.py +220 -192
  61. warp/examples/fem/example_stokes_transfer.py +265 -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 +260 -248
  65. warp/examples/optim/example_cloth_throw.py +222 -210
  66. warp/examples/optim/example_diffray.py +566 -535
  67. warp/examples/optim/example_drone.py +864 -835
  68. warp/examples/optim/example_inverse_kinematics.py +176 -169
  69. warp/examples/optim/example_inverse_kinematics_torch.py +185 -170
  70. warp/examples/optim/example_spring_cage.py +239 -234
  71. warp/examples/optim/example_trajectory.py +223 -201
  72. warp/examples/optim/example_walker.py +306 -292
  73. warp/examples/sim/example_cartpole.py +139 -128
  74. warp/examples/sim/example_cloth.py +196 -184
  75. warp/examples/sim/example_granular.py +124 -113
  76. warp/examples/sim/example_granular_collision_sdf.py +197 -185
  77. warp/examples/sim/example_jacobian_ik.py +236 -213
  78. warp/examples/sim/example_particle_chain.py +118 -106
  79. warp/examples/sim/example_quadruped.py +193 -179
  80. warp/examples/sim/example_rigid_chain.py +197 -189
  81. warp/examples/sim/example_rigid_contact.py +189 -176
  82. warp/examples/sim/example_rigid_force.py +127 -126
  83. warp/examples/sim/example_rigid_gyroscopic.py +109 -97
  84. warp/examples/sim/example_rigid_soft_contact.py +134 -124
  85. warp/examples/sim/example_soft_body.py +190 -178
  86. warp/fabric.py +337 -335
  87. warp/fem/__init__.py +60 -27
  88. warp/fem/cache.py +401 -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 +15 -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 +744 -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 +441 -435
  104. warp/fem/geometry/hexmesh.py +953 -953
  105. warp/fem/geometry/partition.py +374 -376
  106. warp/fem/geometry/quadmesh_2d.py +532 -532
  107. warp/fem/geometry/tetmesh.py +840 -840
  108. warp/fem/geometry/trimesh_2d.py +577 -577
  109. warp/fem/integrate.py +1630 -1615
  110. warp/fem/operator.py +190 -191
  111. warp/fem/polynomial.py +214 -213
  112. warp/fem/quadrature/__init__.py +2 -2
  113. warp/fem/quadrature/pic_quadrature.py +243 -245
  114. warp/fem/quadrature/quadrature.py +295 -294
  115. warp/fem/space/__init__.py +294 -292
  116. warp/fem/space/basis_space.py +488 -489
  117. warp/fem/space/collocated_function_space.py +100 -105
  118. warp/fem/space/dof_mapper.py +236 -236
  119. warp/fem/space/function_space.py +148 -145
  120. warp/fem/space/grid_2d_function_space.py +267 -267
  121. warp/fem/space/grid_3d_function_space.py +305 -306
  122. warp/fem/space/hexmesh_function_space.py +350 -352
  123. warp/fem/space/partition.py +350 -350
  124. warp/fem/space/quadmesh_2d_function_space.py +368 -369
  125. warp/fem/space/restriction.py +158 -160
  126. warp/fem/space/shape/__init__.py +13 -15
  127. warp/fem/space/shape/cube_shape_function.py +738 -738
  128. warp/fem/space/shape/shape_function.py +102 -103
  129. warp/fem/space/shape/square_shape_function.py +611 -611
  130. warp/fem/space/shape/tet_shape_function.py +565 -567
  131. warp/fem/space/shape/triangle_shape_function.py +429 -429
  132. warp/fem/space/tetmesh_function_space.py +294 -292
  133. warp/fem/space/topology.py +297 -295
  134. warp/fem/space/trimesh_2d_function_space.py +223 -221
  135. warp/fem/types.py +77 -77
  136. warp/fem/utils.py +495 -495
  137. warp/jax.py +166 -141
  138. warp/jax_experimental.py +341 -339
  139. warp/native/array.h +1072 -1025
  140. warp/native/builtin.h +1560 -1560
  141. warp/native/bvh.cpp +398 -398
  142. warp/native/bvh.cu +525 -525
  143. warp/native/bvh.h +429 -429
  144. warp/native/clang/clang.cpp +495 -464
  145. warp/native/crt.cpp +31 -31
  146. warp/native/crt.h +334 -334
  147. warp/native/cuda_crt.h +1049 -1049
  148. warp/native/cuda_util.cpp +549 -540
  149. warp/native/cuda_util.h +288 -203
  150. warp/native/cutlass_gemm.cpp +34 -34
  151. warp/native/cutlass_gemm.cu +372 -372
  152. warp/native/error.cpp +66 -66
  153. warp/native/error.h +27 -27
  154. warp/native/fabric.h +228 -228
  155. warp/native/hashgrid.cpp +301 -278
  156. warp/native/hashgrid.cu +78 -77
  157. warp/native/hashgrid.h +227 -227
  158. warp/native/initializer_array.h +32 -32
  159. warp/native/intersect.h +1204 -1204
  160. warp/native/intersect_adj.h +365 -365
  161. warp/native/intersect_tri.h +322 -322
  162. warp/native/marching.cpp +2 -2
  163. warp/native/marching.cu +497 -497
  164. warp/native/marching.h +2 -2
  165. warp/native/mat.h +1498 -1498
  166. warp/native/matnn.h +333 -333
  167. warp/native/mesh.cpp +203 -203
  168. warp/native/mesh.cu +293 -293
  169. warp/native/mesh.h +1887 -1887
  170. warp/native/nanovdb/NanoVDB.h +4782 -4782
  171. warp/native/nanovdb/PNanoVDB.h +2553 -2553
  172. warp/native/nanovdb/PNanoVDBWrite.h +294 -294
  173. warp/native/noise.h +850 -850
  174. warp/native/quat.h +1084 -1084
  175. warp/native/rand.h +299 -299
  176. warp/native/range.h +108 -108
  177. warp/native/reduce.cpp +156 -156
  178. warp/native/reduce.cu +348 -348
  179. warp/native/runlength_encode.cpp +61 -61
  180. warp/native/runlength_encode.cu +46 -46
  181. warp/native/scan.cpp +30 -30
  182. warp/native/scan.cu +36 -36
  183. warp/native/scan.h +7 -7
  184. warp/native/solid_angle.h +442 -442
  185. warp/native/sort.cpp +94 -94
  186. warp/native/sort.cu +97 -97
  187. warp/native/sort.h +14 -14
  188. warp/native/sparse.cpp +337 -337
  189. warp/native/sparse.cu +544 -544
  190. warp/native/spatial.h +630 -630
  191. warp/native/svd.h +562 -562
  192. warp/native/temp_buffer.h +30 -30
  193. warp/native/vec.h +1132 -1132
  194. warp/native/volume.cpp +297 -297
  195. warp/native/volume.cu +32 -32
  196. warp/native/volume.h +538 -538
  197. warp/native/volume_builder.cu +425 -425
  198. warp/native/volume_builder.h +19 -19
  199. warp/native/warp.cpp +1057 -1052
  200. warp/native/warp.cu +2943 -2828
  201. warp/native/warp.h +313 -305
  202. warp/optim/__init__.py +9 -9
  203. warp/optim/adam.py +120 -120
  204. warp/optim/linear.py +1104 -939
  205. warp/optim/sgd.py +104 -92
  206. warp/render/__init__.py +10 -10
  207. warp/render/render_opengl.py +3217 -3204
  208. warp/render/render_usd.py +768 -749
  209. warp/render/utils.py +152 -150
  210. warp/sim/__init__.py +52 -59
  211. warp/sim/articulation.py +685 -685
  212. warp/sim/collide.py +1594 -1590
  213. warp/sim/import_mjcf.py +489 -481
  214. warp/sim/import_snu.py +220 -221
  215. warp/sim/import_urdf.py +536 -516
  216. warp/sim/import_usd.py +887 -881
  217. warp/sim/inertia.py +316 -317
  218. warp/sim/integrator.py +234 -233
  219. warp/sim/integrator_euler.py +1956 -1956
  220. warp/sim/integrator_featherstone.py +1910 -1991
  221. warp/sim/integrator_xpbd.py +3294 -3312
  222. warp/sim/model.py +4473 -4314
  223. warp/sim/particles.py +113 -112
  224. warp/sim/render.py +417 -403
  225. warp/sim/utils.py +413 -410
  226. warp/sparse.py +1227 -1227
  227. warp/stubs.py +2109 -2469
  228. warp/tape.py +1162 -225
  229. warp/tests/__init__.py +1 -1
  230. warp/tests/__main__.py +4 -4
  231. warp/tests/assets/torus.usda +105 -105
  232. warp/tests/aux_test_class_kernel.py +26 -26
  233. warp/tests/aux_test_compile_consts_dummy.py +10 -10
  234. warp/tests/aux_test_conditional_unequal_types_kernels.py +21 -21
  235. warp/tests/aux_test_dependent.py +22 -22
  236. warp/tests/aux_test_grad_customs.py +23 -23
  237. warp/tests/aux_test_reference.py +11 -11
  238. warp/tests/aux_test_reference_reference.py +10 -10
  239. warp/tests/aux_test_square.py +17 -17
  240. warp/tests/aux_test_unresolved_func.py +14 -14
  241. warp/tests/aux_test_unresolved_symbol.py +14 -14
  242. warp/tests/disabled_kinematics.py +239 -239
  243. warp/tests/run_coverage_serial.py +31 -31
  244. warp/tests/test_adam.py +157 -157
  245. warp/tests/test_arithmetic.py +1124 -1124
  246. warp/tests/test_array.py +2417 -2326
  247. warp/tests/test_array_reduce.py +150 -150
  248. warp/tests/test_async.py +668 -656
  249. warp/tests/test_atomic.py +141 -141
  250. warp/tests/test_bool.py +204 -149
  251. warp/tests/test_builtins_resolution.py +1292 -1292
  252. warp/tests/test_bvh.py +164 -171
  253. warp/tests/test_closest_point_edge_edge.py +228 -228
  254. warp/tests/test_codegen.py +566 -553
  255. warp/tests/test_compile_consts.py +97 -101
  256. warp/tests/test_conditional.py +246 -246
  257. warp/tests/test_copy.py +232 -215
  258. warp/tests/test_ctypes.py +632 -632
  259. warp/tests/test_dense.py +67 -67
  260. warp/tests/test_devices.py +91 -98
  261. warp/tests/test_dlpack.py +530 -529
  262. warp/tests/test_examples.py +400 -378
  263. warp/tests/test_fabricarray.py +955 -955
  264. warp/tests/test_fast_math.py +62 -54
  265. warp/tests/test_fem.py +1277 -1278
  266. warp/tests/test_fp16.py +130 -130
  267. warp/tests/test_func.py +338 -337
  268. warp/tests/test_generics.py +571 -571
  269. warp/tests/test_grad.py +746 -640
  270. warp/tests/test_grad_customs.py +333 -336
  271. warp/tests/test_hash_grid.py +210 -164
  272. warp/tests/test_import.py +39 -39
  273. warp/tests/test_indexedarray.py +1134 -1134
  274. warp/tests/test_intersect.py +67 -67
  275. warp/tests/test_jax.py +307 -307
  276. warp/tests/test_large.py +167 -164
  277. warp/tests/test_launch.py +354 -354
  278. warp/tests/test_lerp.py +261 -261
  279. warp/tests/test_linear_solvers.py +191 -171
  280. warp/tests/test_lvalue.py +421 -493
  281. warp/tests/test_marching_cubes.py +65 -65
  282. warp/tests/test_mat.py +1801 -1827
  283. warp/tests/test_mat_lite.py +115 -115
  284. warp/tests/test_mat_scalar_ops.py +2907 -2889
  285. warp/tests/test_math.py +126 -193
  286. warp/tests/test_matmul.py +500 -499
  287. warp/tests/test_matmul_lite.py +410 -410
  288. warp/tests/test_mempool.py +188 -190
  289. warp/tests/test_mesh.py +284 -324
  290. warp/tests/test_mesh_query_aabb.py +228 -241
  291. warp/tests/test_mesh_query_point.py +692 -702
  292. warp/tests/test_mesh_query_ray.py +292 -303
  293. warp/tests/test_mlp.py +276 -276
  294. warp/tests/test_model.py +110 -110
  295. warp/tests/test_modules_lite.py +39 -39
  296. warp/tests/test_multigpu.py +163 -163
  297. warp/tests/test_noise.py +248 -248
  298. warp/tests/test_operators.py +250 -250
  299. warp/tests/test_options.py +123 -125
  300. warp/tests/test_peer.py +133 -137
  301. warp/tests/test_pinned.py +78 -78
  302. warp/tests/test_print.py +54 -54
  303. warp/tests/test_quat.py +2086 -2086
  304. warp/tests/test_rand.py +288 -288
  305. warp/tests/test_reload.py +217 -217
  306. warp/tests/test_rounding.py +179 -179
  307. warp/tests/test_runlength_encode.py +190 -190
  308. warp/tests/test_sim_grad.py +243 -0
  309. warp/tests/test_sim_kinematics.py +91 -97
  310. warp/tests/test_smoothstep.py +168 -168
  311. warp/tests/test_snippet.py +305 -266
  312. warp/tests/test_sparse.py +468 -460
  313. warp/tests/test_spatial.py +2148 -2148
  314. warp/tests/test_streams.py +486 -473
  315. warp/tests/test_struct.py +710 -675
  316. warp/tests/test_tape.py +173 -148
  317. warp/tests/test_torch.py +743 -743
  318. warp/tests/test_transient_module.py +87 -87
  319. warp/tests/test_types.py +556 -659
  320. warp/tests/test_utils.py +490 -499
  321. warp/tests/test_vec.py +1264 -1268
  322. warp/tests/test_vec_lite.py +73 -73
  323. warp/tests/test_vec_scalar_ops.py +2099 -2099
  324. warp/tests/test_verify_fp.py +94 -94
  325. warp/tests/test_volume.py +737 -736
  326. warp/tests/test_volume_write.py +255 -265
  327. warp/tests/unittest_serial.py +37 -37
  328. warp/tests/unittest_suites.py +363 -359
  329. warp/tests/unittest_utils.py +603 -578
  330. warp/tests/unused_test_misc.py +71 -71
  331. warp/tests/walkthrough_debug.py +85 -85
  332. warp/thirdparty/appdirs.py +598 -598
  333. warp/thirdparty/dlpack.py +143 -143
  334. warp/thirdparty/unittest_parallel.py +566 -561
  335. warp/torch.py +321 -295
  336. warp/types.py +4504 -4450
  337. warp/utils.py +1008 -821
  338. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/LICENSE.md +126 -126
  339. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/METADATA +338 -400
  340. warp_lang-1.1.0.dist-info/RECORD +352 -0
  341. warp/examples/assets/cube.usda +0 -42
  342. warp/examples/assets/sphere.usda +0 -56
  343. warp/examples/assets/torus.usda +0 -105
  344. warp_lang-1.0.1.dist-info/RECORD +0 -352
  345. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/WHEEL +0 -0
  346. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/top_level.txt +0 -0
@@ -1,835 +1,864 @@
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.optim
25
- import warp.sim
26
- import warp.sim.render
27
- from warp.sim.collide import (
28
- box_sdf,
29
- capsule_sdf,
30
- cone_sdf,
31
- cylinder_sdf,
32
- mesh_sdf,
33
- plane_sdf,
34
- sphere_sdf,
35
- )
36
-
37
- wp.init()
38
-
39
-
40
- @wp.struct
41
- class Propeller:
42
- body: int
43
- pos: wp.vec3
44
- dir: wp.vec3
45
- thrust: float
46
- power: float
47
- diameter: float
48
- height: float
49
- max_rpm: float
50
- max_thrust: float
51
- max_torque: float
52
- turning_direction: float
53
- max_speed_square: float
54
-
55
-
56
- @wp.kernel
57
- def increment_seed(
58
- seed: wp.array(dtype=int),
59
- ):
60
- seed[0] += 1
61
-
62
-
63
- @wp.kernel
64
- def sample_gaussian(
65
- mean_trajectory: wp.array(dtype=float, ndim=3),
66
- noise_scale: float,
67
- num_control_points: int,
68
- control_dim: int,
69
- control_limits: wp.array(dtype=float, ndim=2),
70
- seed: wp.array(dtype=int),
71
- rollout_trajectories: wp.array(dtype=float, ndim=3),
72
- ):
73
- env_id, point_id, control_id = wp.tid()
74
- unique_id = (env_id * num_control_points + point_id) * control_dim + control_id
75
- r = wp.rand_init(seed[0], unique_id)
76
- mean = mean_trajectory[0, point_id, control_id]
77
- lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
78
- sample = mean + noise_scale * wp.randn(r)
79
- for i in range(10):
80
- if sample < lo or sample > hi:
81
- sample = mean + noise_scale * wp.randn(r)
82
- else:
83
- break
84
- rollout_trajectories[env_id, point_id, control_id] = wp.clamp(sample, lo, hi)
85
-
86
-
87
- @wp.kernel
88
- def replicate_states(
89
- body_q_in: wp.array(dtype=wp.transform),
90
- body_qd_in: wp.array(dtype=wp.spatial_vector),
91
- bodies_per_env: int,
92
- body_q_out: wp.array(dtype=wp.transform),
93
- body_qd_out: wp.array(dtype=wp.spatial_vector),
94
- ):
95
- tid = wp.tid()
96
- env_offset = tid * bodies_per_env
97
- for i in range(bodies_per_env):
98
- body_q_out[env_offset + i] = body_q_in[i]
99
- body_qd_out[env_offset + i] = body_qd_in[i]
100
-
101
-
102
- @wp.kernel
103
- def drone_cost(
104
- body_q: wp.array(dtype=wp.transform),
105
- body_qd: wp.array(dtype=wp.spatial_vector),
106
- target: wp.vec3,
107
- prop_control: wp.array(dtype=float),
108
- step: int,
109
- horizon_length: int,
110
- weighting: float,
111
- cost: wp.array(dtype=wp.float32),
112
- ):
113
- env_id = wp.tid()
114
- tf = body_q[env_id]
115
-
116
- pos_drone = wp.transform_get_translation(tf)
117
- pos_cost = wp.length_sq(pos_drone - target)
118
- altitude_cost = wp.max(pos_drone[1] - 0.75, 0.0) + wp.max(0.25 - pos_drone[1], 0.0)
119
- upvector = wp.vec3(0.0, 1.0, 0.0)
120
- drone_up = wp.transform_vector(tf, upvector)
121
- upright_cost = 1.0 - wp.dot(drone_up, upvector)
122
-
123
- vel_drone = body_qd[env_id]
124
-
125
- # Encourage zero velocity.
126
- vel_cost = wp.length_sq(vel_drone)
127
-
128
- control = wp.vec4(
129
- prop_control[env_id * 4 + 0],
130
- prop_control[env_id * 4 + 1],
131
- prop_control[env_id * 4 + 2],
132
- prop_control[env_id * 4 + 3],
133
- )
134
- control_cost = wp.dot(control, control)
135
-
136
- discount = 0.8 ** wp.float(horizon_length - step - 1) / wp.float(horizon_length) ** 2.0
137
-
138
- pos_weight = 1000.0
139
- altitude_weight = 100.0
140
- control_weight = 0.05
141
- vel_weight = 0.1
142
- upright_weight = 10.0
143
- total_weight = pos_weight + altitude_weight + control_weight + vel_weight + upright_weight
144
-
145
- wp.atomic_add(
146
- cost,
147
- env_id,
148
- (
149
- pos_cost * pos_weight
150
- + altitude_cost * altitude_weight
151
- + control_cost * control_weight
152
- + vel_cost * vel_weight
153
- + upright_cost * upright_weight
154
- )
155
- * (weighting / total_weight)
156
- * discount,
157
- )
158
-
159
-
160
- @wp.kernel
161
- def collision_cost(
162
- body_q: wp.array(dtype=wp.transform),
163
- obstacle_ids: wp.array(dtype=int, ndim=2),
164
- shape_X_bs: wp.array(dtype=wp.transform),
165
- geo: wp.sim.ModelShapeGeometry,
166
- margin: float,
167
- weighting: float,
168
- cost: wp.array(dtype=wp.float32),
169
- ):
170
- env_id, obs_id = wp.tid()
171
- shape_index = obstacle_ids[env_id, obs_id]
172
-
173
- px = wp.transform_get_translation(body_q[env_id])
174
-
175
- X_bs = shape_X_bs[shape_index]
176
-
177
- # transform particle position to shape local space
178
- x_local = wp.transform_point(X_bs, px)
179
-
180
- # geo description
181
- geo_type = geo.type[shape_index]
182
- geo_scale = geo.scale[shape_index]
183
-
184
- # evaluate shape sdf
185
- d = 1e6
186
-
187
- if geo_type == wp.sim.GEO_SPHERE:
188
- d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
189
- elif geo_type == wp.sim.GEO_BOX:
190
- d = box_sdf(geo_scale, x_local)
191
- elif geo_type == wp.sim.GEO_CAPSULE:
192
- d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
193
- elif geo_type == wp.sim.GEO_CYLINDER:
194
- d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
195
- elif geo_type == wp.sim.GEO_CONE:
196
- d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
197
- elif geo_type == wp.sim.GEO_MESH:
198
- mesh = geo.source[shape_index]
199
- min_scale = wp.min(geo_scale)
200
- max_dist = margin / min_scale
201
- d = mesh_sdf(mesh, wp.cw_div(x_local, geo_scale), max_dist)
202
- d *= min_scale # TODO fix this, mesh scaling needs to be handled properly
203
- elif geo_type == wp.sim.GEO_SDF:
204
- volume = geo.source[shape_index]
205
- xpred_local = wp.volume_world_to_index(volume, wp.cw_div(x_local, geo_scale))
206
- nn = wp.vec3(0.0, 0.0, 0.0)
207
- d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, nn)
208
- elif geo_type == wp.sim.GEO_PLANE:
209
- d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
210
-
211
- d = wp.max(d, 0.0)
212
- if d < margin:
213
- c = margin - d
214
- wp.atomic_add(cost, env_id, weighting * c)
215
-
216
-
217
- @wp.kernel
218
- def enforce_control_limits(
219
- control_limits: wp.array(dtype=float, ndim=2),
220
- control_points: wp.array(dtype=float, ndim=3),
221
- ):
222
- env_id, t_id, control_id = wp.tid()
223
- lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
224
- control_points[env_id, t_id, control_id] = wp.clamp(control_points[env_id, t_id, control_id], lo, hi)
225
-
226
-
227
- @wp.kernel
228
- def pick_best_trajectory(
229
- rollout_trajectories: wp.array(dtype=float, ndim=3),
230
- lowest_cost_id: int,
231
- best_traj: wp.array(dtype=float, ndim=3),
232
- ):
233
- t_id, control_id = wp.tid()
234
- best_traj[0, t_id, control_id] = rollout_trajectories[lowest_cost_id, t_id, control_id]
235
-
236
-
237
- @wp.kernel
238
- def interpolate_control_linear(
239
- control_points: wp.array(dtype=float, ndim=3),
240
- control_dofs: wp.array(dtype=int),
241
- control_gains: wp.array(dtype=float),
242
- t: float,
243
- torque_dim: int,
244
- torques: wp.array(dtype=float),
245
- ):
246
- env_id, control_id = wp.tid()
247
- t_id = int(t)
248
- frac = t - wp.floor(t)
249
- control_left = control_points[env_id, t_id, control_id]
250
- control_right = control_points[env_id, t_id + 1, control_id]
251
- torque_id = env_id * torque_dim + control_dofs[control_id]
252
- action = control_left * (1.0 - frac) + control_right * frac
253
- torques[torque_id] = action * control_gains[control_id]
254
-
255
-
256
- @wp.kernel
257
- def compute_prop_wrenches(
258
- props: wp.array(dtype=Propeller),
259
- controls: wp.array(dtype=float),
260
- body_q: wp.array(dtype=wp.transform),
261
- body_com: wp.array(dtype=wp.vec3),
262
- body_f: wp.array(dtype=wp.spatial_vector),
263
- ):
264
- tid = wp.tid()
265
- prop = props[tid]
266
- control = controls[tid]
267
- tf = body_q[prop.body]
268
- dir = wp.transform_vector(tf, prop.dir)
269
- force = dir * prop.max_thrust * control
270
- torque = dir * prop.max_torque * control * prop.turning_direction
271
- moment_arm = wp.transform_point(tf, prop.pos) - wp.transform_point(tf, body_com[prop.body])
272
- torque += wp.cross(moment_arm, force)
273
- # Apply angular damping.
274
- torque *= 0.8
275
- wp.atomic_add(body_f, prop.body, wp.spatial_vector(torque, force))
276
-
277
-
278
- def define_propeller(
279
- drone: int,
280
- pos: wp.vec3,
281
- fps: float,
282
- thrust: float = 0.109919,
283
- power: float = 0.040164,
284
- diameter: float = 0.2286,
285
- height: float = 0.01,
286
- max_rpm: float = 6396.667,
287
- turning_direction: float = 1.0,
288
- ):
289
- # Air density at sea level.
290
- air_density = 1.225 # kg / m^3
291
-
292
- rps = max_rpm / fps
293
- max_speed = rps * wp.TAU # radians / sec
294
- rps_square = rps**2
295
-
296
- prop = Propeller()
297
- prop.body = drone
298
- prop.pos = pos
299
- prop.dir = wp.vec3(0.0, 1.0, 0.0)
300
- prop.thrust = thrust
301
- prop.power = power
302
- prop.diameter = diameter
303
- prop.height = height
304
- prop.max_rpm = max_rpm
305
- prop.max_thrust = thrust * air_density * rps_square * diameter**4
306
- prop.max_torque = power * air_density * rps_square * diameter**5 / wp.TAU
307
- prop.turning_direction = turning_direction
308
- prop.max_speed_square = max_speed**2
309
-
310
- return prop
311
-
312
-
313
- class Drone:
314
- def __init__(
315
- self,
316
- name: str,
317
- fps: float,
318
- trajectory_shape: Tuple[int, int],
319
- variation_count: int = 1,
320
- size: float = 1.0,
321
- requires_grad: bool = False,
322
- state_count: Optional[int] = None,
323
- ) -> None:
324
- self.variation_count = variation_count
325
- self.requires_grad = requires_grad
326
-
327
- # Current tick of the simulation, including substeps.
328
- self.sim_tick = 0
329
-
330
- # Initialize the helper to build a physics scene.
331
- builder = wp.sim.ModelBuilder()
332
- builder.rigid_contact_margin = 0.05
333
-
334
- # Initialize the rigid bodies, propellers, and colliders.
335
- props = []
336
- colliders = []
337
- crossbar_length = size
338
- crossbar_height = size * 0.05
339
- crossbar_width = size * 0.05
340
- carbon_fiber_density = 1750.0 # kg / m^3
341
- for i in range(variation_count):
342
- # Register the drone as a rigid body in the simulation model.
343
- body = builder.add_body(name=f"{name}_{i}")
344
-
345
- # Define the shapes making up the drone's rigid body.
346
- builder.add_shape_box(
347
- body,
348
- hx=crossbar_length,
349
- hy=crossbar_height,
350
- hz=crossbar_width,
351
- density=carbon_fiber_density,
352
- collision_group=i,
353
- )
354
- builder.add_shape_box(
355
- body,
356
- hx=crossbar_width,
357
- hy=crossbar_height,
358
- hz=crossbar_length,
359
- density=carbon_fiber_density,
360
- collision_group=i,
361
- )
362
-
363
- # Initialize the propellers.
364
- props.extend(
365
- (
366
- define_propeller(
367
- body,
368
- wp.vec3(crossbar_length, 0.0, 0.0),
369
- fps,
370
- turning_direction=-1.0,
371
- ),
372
- define_propeller(
373
- body,
374
- wp.vec3(-crossbar_length, 0.0, 0.0),
375
- fps,
376
- turning_direction=1.0,
377
- ),
378
- define_propeller(
379
- body,
380
- wp.vec3(0.0, 0.0, crossbar_length),
381
- fps,
382
- turning_direction=1.0,
383
- ),
384
- define_propeller(
385
- body,
386
- wp.vec3(0.0, 0.0, -crossbar_length),
387
- fps,
388
- turning_direction=-1.0,
389
- ),
390
- ),
391
- )
392
-
393
- # Initialize the colliders.
394
- colliders.append(
395
- (
396
- builder.add_shape_capsule(
397
- -1,
398
- pos=(0.5, 2.0, 0.5),
399
- radius=0.15,
400
- half_height=2.0,
401
- collision_group=i,
402
- ),
403
- ),
404
- )
405
- self.props = wp.array(props, dtype=Propeller)
406
- self.colliders = wp.array(colliders, dtype=int)
407
-
408
- # Build the model and set-up its properties.
409
- self.model = builder.finalize(requires_grad=requires_grad)
410
- self.model.ground = False
411
-
412
- # Initialize the required simulation states.
413
- if requires_grad:
414
- self.states = tuple(self.model.state() for _ in range(state_count + 1))
415
- self.controls = tuple(self.model.control() for _ in range(state_count))
416
- else:
417
- # When only running a forward simulation, we don't need to store
418
- # the history of the states at each step, instead we use double
419
- # buffering to represent the previous and next states.
420
- self.states = [self.model.state(), self.model.state()]
421
- self.controls = (self.model.control(),)
422
-
423
- # create array for the propeller controls
424
- for control in self.controls:
425
- control.prop_controls = wp.zeros(len(self.props), dtype=float, requires_grad=requires_grad)
426
-
427
- # Define the trajectories as arrays of control points.
428
- # The point data has an additional item to support linear interpolation.
429
- self.trajectories = wp.zeros(
430
- (variation_count, trajectory_shape[0], trajectory_shape[1]),
431
- dtype=float,
432
- requires_grad=requires_grad,
433
- )
434
-
435
- # Store some miscellaneous info.
436
- self.body_count = len(builder.body_q)
437
- self.collider_count = self.colliders.shape[1]
438
- self.collision_radius = crossbar_length * 2.0
439
-
440
- @property
441
- def state(self) -> wp.sim.State:
442
- return self.states[self.sim_tick if self.requires_grad else 0]
443
-
444
- @property
445
- def next_state(self) -> wp.sim.State:
446
- return self.states[self.sim_tick + 1 if self.requires_grad else 1]
447
-
448
- @property
449
- def control(self) -> wp.sim.Control:
450
- return self.controls[min(len(self.controls) - 1, self.sim_tick) if self.requires_grad else 0]
451
-
452
-
453
- class Example:
454
- def __init__(
455
- self,
456
- stage: Optional[str] = None,
457
- drone_path: Optional[str] = None,
458
- enable_rendering: bool = True,
459
- render_rollouts: bool = True,
460
- verbose: bool = False,
461
- ) -> None:
462
- # Duration of the simulation, in seconds.
463
- duration = 6.0
464
-
465
- # Number of frames per second.
466
- self.fps = 60.0
467
-
468
- # Duration of the simulation in number of frames.
469
- self.frame_count = int(duration * self.fps)
470
-
471
- # Number of simulation substeps to take per step.
472
- self.sim_substep_count = 1
473
-
474
- # Delta time between each simulation substep.
475
- self.frame_dt = 1.0 / self.fps
476
-
477
- # Delta time between each simulation substep.
478
- self.sim_dt = self.frame_dt / self.sim_substep_count
479
-
480
- # Frame number used for simulation and rendering.
481
- self.frame = 0
482
-
483
- # Targets positions that the drone will try to reach in turn.
484
- self.targets = (
485
- wp.vec3(0.0, 0.5, 1.0),
486
- wp.vec3(1.0, 0.5, 0.0),
487
- )
488
-
489
- # Define the index of the active target.
490
- # We start with -1 since it'll be incremented on the first frame.
491
- self.target_idx = -1
492
-
493
- # Number of steps to run at each frame for the optimisation pass.
494
- self.optim_step_count = 20
495
-
496
- # Time steps between control points.
497
- self.control_point_step = 10
498
-
499
- # Number of control horizon points to interpolate between.
500
- self.control_point_count = 3
501
-
502
- self.control_point_data_count = self.control_point_count + 1
503
- self.control_dofs = wp.array((0, 1, 2, 3), dtype=int)
504
- self.control_dim = len(self.control_dofs)
505
- self.control_gains = wp.array((0.8,) * self.control_dim, dtype=float)
506
- self.control_limits = wp.array(((0.1, 1.0),) * self.control_dim, dtype=float)
507
-
508
- drone_size = 0.2
509
-
510
- # Declare the reference drone.
511
- self.drone = Drone(
512
- "drone",
513
- self.fps,
514
- (self.control_point_data_count, self.control_dim),
515
- size=drone_size,
516
- )
517
-
518
- # Declare the drone's rollouts.
519
- # These allow to run parallel simulations in order to find the best
520
- # trajectory at each control point.
521
- self.rollout_count = 16
522
- self.rollout_step_count = self.control_point_step * self.control_point_count
523
- self.rollouts = Drone(
524
- "rollout",
525
- self.fps,
526
- (self.control_point_data_count, self.control_dim),
527
- variation_count=self.rollout_count,
528
- size=drone_size,
529
- requires_grad=True,
530
- state_count=self.rollout_step_count * self.sim_substep_count,
531
- )
532
-
533
- self.seed = wp.zeros(1, dtype=int)
534
- self.rollout_costs = wp.zeros(self.rollout_count, dtype=float, requires_grad=True)
535
-
536
- # Use the Euler integrator for stepping through the simulation.
537
- self.integrator = wp.sim.SemiImplicitIntegrator()
538
-
539
- self.optimizer = wp.optim.SGD(
540
- [self.rollouts.trajectories.flatten()],
541
- lr=1e-2,
542
- nesterov=False,
543
- momentum=0.0,
544
- )
545
-
546
- self.tape = None
547
-
548
- if enable_rendering:
549
- # Helper to render the physics scene as a USD file.
550
- self.renderer = wp.sim.render.SimRenderer(self.drone.model, stage, fps=self.fps)
551
-
552
- if isinstance(self.renderer, warp.sim.render.SimRendererUsd):
553
- from pxr import UsdGeom
554
-
555
- # Remove the default drone geometries.
556
- drone_root_prim = self.renderer.stage.GetPrimAtPath("/root/body_0_drone_0")
557
- for prim in drone_root_prim.GetChildren():
558
- self.renderer.stage.RemovePrim(prim.GetPath())
559
-
560
- # Add a reference to the drone geometry.
561
- drone_prim = self.renderer.stage.OverridePrim(f"{drone_root_prim.GetPath()}/crazyflie")
562
- drone_prim.GetReferences().AddReference(drone_path)
563
- drone_xform = UsdGeom.Xform(drone_prim)
564
- drone_xform.AddTranslateOp().Set((0.0, -0.05, 0.0))
565
- drone_xform.AddRotateYOp().Set(45.0)
566
- drone_xform.AddScaleOp().Set((drone_size * 0.2,) * 3)
567
-
568
- # Get the propellers to spin
569
- for turning_direction in ("CW", "CCW"):
570
- spin = 100.0 * 360.0 * self.frame_count / self.fps
571
- spin = spin if turning_direction == "CCW" else -spin
572
- for side in ("Back", "Front"):
573
- prop_prim = self.renderer.stage.OverridePrim(
574
- f"{drone_prim.GetPath()}/Propeller{turning_direction}{side}"
575
- )
576
- prop_xform = UsdGeom.Xform(prop_prim)
577
- rot = prop_xform.AddRotateYOp()
578
- rot.Set(0.0, 0.0)
579
- rot.Set(spin, self.frame_count)
580
- else:
581
- self.renderer = None
582
-
583
- self.use_cuda_graph = True
584
- self.optim_graph = None
585
-
586
- self.render_rollouts = render_rollouts
587
- self.verbose = verbose
588
-
589
- def update_drone(self, drone: Drone) -> None:
590
- drone.state.clear_forces()
591
-
592
- wp.launch(
593
- interpolate_control_linear,
594
- dim=(
595
- drone.variation_count,
596
- self.control_dim,
597
- ),
598
- inputs=(
599
- drone.trajectories,
600
- self.control_dofs,
601
- self.control_gains,
602
- drone.sim_tick / (self.sim_substep_count * self.control_point_step),
603
- self.control_dim,
604
- ),
605
- outputs=(drone.control.prop_controls,),
606
- )
607
-
608
- wp.sim.collide(drone.model, drone.state)
609
-
610
- wp.launch(
611
- compute_prop_wrenches,
612
- dim=len(drone.props),
613
- inputs=(
614
- drone.props,
615
- drone.control.prop_controls,
616
- drone.state.body_q,
617
- drone.model.body_com,
618
- ),
619
- outputs=(drone.state.body_f,),
620
- )
621
-
622
- self.integrator.simulate(
623
- drone.model,
624
- drone.state,
625
- drone.next_state,
626
- self.sim_dt,
627
- drone.control,
628
- )
629
-
630
- drone.sim_tick += 1
631
-
632
- def forward(self):
633
- # Evaluate the rollouts with their costs.
634
- self.rollouts.sim_tick = 0
635
- self.rollout_costs.zero_()
636
- wp.launch(
637
- replicate_states,
638
- dim=self.rollout_count,
639
- inputs=(
640
- self.drone.state.body_q,
641
- self.drone.state.body_qd,
642
- self.drone.body_count,
643
- ),
644
- outputs=(
645
- self.rollouts.state.body_q,
646
- self.rollouts.state.body_qd,
647
- ),
648
- )
649
-
650
- for i in range(self.rollout_step_count):
651
- for _ in range(self.sim_substep_count):
652
- self.update_drone(self.rollouts)
653
-
654
- wp.launch(
655
- drone_cost,
656
- dim=self.rollout_count,
657
- inputs=(
658
- self.rollouts.state.body_q,
659
- self.rollouts.state.body_qd,
660
- self.targets[self.target_idx],
661
- self.rollouts.control.prop_controls,
662
- i,
663
- self.rollout_step_count,
664
- 1e3,
665
- ),
666
- outputs=(self.rollout_costs,),
667
- )
668
- wp.launch(
669
- collision_cost,
670
- dim=(
671
- self.rollout_count,
672
- self.rollouts.collider_count,
673
- ),
674
- inputs=(
675
- self.rollouts.state.body_q,
676
- self.rollouts.colliders,
677
- self.rollouts.model.shape_transform,
678
- self.rollouts.model.shape_geo,
679
- self.rollouts.collision_radius,
680
- 1e4,
681
- ),
682
- outputs=(self.rollout_costs,),
683
- )
684
-
685
- def step_optimizer(self):
686
- if self.optim_graph is None:
687
- self.tape = wp.Tape()
688
- with self.tape:
689
- self.forward()
690
- self.rollout_costs.grad.fill_(1.0)
691
- self.tape.backward()
692
- else:
693
- wp.capture_launch(self.optim_graph)
694
-
695
- self.optimizer.step([self.rollouts.trajectories.grad.flatten()])
696
-
697
- # Enforce limits on the control points.
698
- wp.launch(
699
- enforce_control_limits,
700
- dim=self.rollouts.trajectories.shape,
701
- inputs=(self.control_limits,),
702
- outputs=(self.rollouts.trajectories,),
703
- )
704
- self.tape.zero()
705
-
706
- def step(self):
707
- if self.frame % int((self.frame_count / len(self.targets))) == 0:
708
- if self.verbose:
709
- print(f"Choosing new flight target: {self.target_idx+1}")
710
-
711
- self.target_idx += 1
712
-
713
- # Force recapturing the CUDA graph for the optimization pass
714
- # by invalidating it.
715
- self.optim_graph = None
716
-
717
- if self.use_cuda_graph and self.optim_graph is None:
718
- with wp.ScopedCapture() as capture:
719
- self.tape = wp.Tape()
720
- with self.tape:
721
- self.forward()
722
- self.rollout_costs.grad.fill_(1.0)
723
- self.tape.backward()
724
- self.optim_graph = capture.graph
725
-
726
- # Sample control waypoints around the nominal trajectory.
727
- self.seed.zero_()
728
- noise_scale = 0.15
729
- wp.launch(
730
- sample_gaussian,
731
- dim=(
732
- self.rollouts.trajectories.shape[0] - 1,
733
- self.rollouts.trajectories.shape[1],
734
- self.rollouts.trajectories.shape[2],
735
- ),
736
- inputs=(
737
- self.drone.trajectories,
738
- noise_scale,
739
- self.control_point_data_count,
740
- self.control_dim,
741
- self.control_limits,
742
- self.seed,
743
- ),
744
- outputs=(self.rollouts.trajectories,),
745
- )
746
-
747
- wp.launch(
748
- increment_seed,
749
- dim=1,
750
- inputs=(),
751
- outputs=(self.seed,),
752
- )
753
-
754
- for _ in range(self.optim_step_count):
755
- self.step_optimizer()
756
-
757
- # Pick the best trajectory.
758
- wp.synchronize()
759
- lowest_cost_id = np.argmin(self.rollout_costs.numpy())
760
- wp.launch(
761
- pick_best_trajectory,
762
- dim=(
763
- self.control_point_data_count,
764
- self.control_dim,
765
- ),
766
- inputs=(
767
- self.rollouts.trajectories,
768
- lowest_cost_id,
769
- ),
770
- outputs=(self.drone.trajectories,),
771
- )
772
- self.rollouts.trajectories[-1].assign(self.drone.trajectories[0])
773
-
774
- # Simulate the drone.
775
- self.drone.sim_tick = 0
776
- for _ in range(self.sim_substep_count):
777
- self.update_drone(self.drone)
778
-
779
- # Swap the drone's states.
780
- (self.drone.states[0], self.drone.states[1]) = (self.drone.states[1], self.drone.states[0])
781
-
782
- def render(self):
783
- if self.renderer is None:
784
- return
785
-
786
- self.renderer.begin_frame(self.frame / self.fps)
787
- self.renderer.render(self.drone.state)
788
-
789
- # Render a sphere as the current target.
790
- self.renderer.render_sphere(
791
- "target",
792
- self.targets[self.target_idx],
793
- wp.quat_identity(),
794
- 0.05,
795
- color=(1.0, 0.0, 0.0),
796
- )
797
-
798
- # Render the rollout trajectories.
799
- if self.render_rollouts:
800
- costs = self.rollout_costs.numpy()
801
-
802
- positions = np.array([x.body_q.numpy()[:, :3] for x in self.rollouts.states])
803
-
804
- min_cost = np.min(costs)
805
- max_cost = np.max(costs)
806
- for i in range(self.rollout_count):
807
- # Flip colors, so red means best trajectory, blue worst.
808
- color = wp.render.bourke_color_map(-max_cost, -min_cost, -costs[i])
809
- self.renderer.render_line_strip(
810
- name=f"rollout_{i}",
811
- vertices=positions[:, i],
812
- color=color,
813
- radius=0.001,
814
- )
815
-
816
- self.renderer.end_frame()
817
-
818
-
819
- if __name__ == "__main__":
820
- this_dir = os.path.realpath(os.path.dirname(__file__))
821
- stage_path = os.path.join(wp.examples.get_output_directory(), "example_drone.usd")
822
- drone_path = os.path.join(this_dir, "..", "assets", "crazyflie.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
+ wp.init()
32
+
33
+
34
+ @wp.struct
35
+ class Propeller:
36
+ body: int
37
+ pos: wp.vec3
38
+ dir: wp.vec3
39
+ thrust: float
40
+ power: float
41
+ diameter: float
42
+ height: float
43
+ max_rpm: float
44
+ max_thrust: float
45
+ max_torque: float
46
+ turning_direction: float
47
+ max_speed_square: float
48
+
49
+
50
+ @wp.kernel
51
+ def increment_seed(
52
+ seed: wp.array(dtype=int),
53
+ ):
54
+ seed[0] += 1
55
+
56
+
57
+ @wp.kernel
58
+ def sample_gaussian(
59
+ mean_trajectory: wp.array(dtype=float, ndim=3),
60
+ noise_scale: float,
61
+ num_control_points: int,
62
+ control_dim: int,
63
+ control_limits: wp.array(dtype=float, ndim=2),
64
+ seed: wp.array(dtype=int),
65
+ rollout_trajectories: wp.array(dtype=float, ndim=3),
66
+ ):
67
+ env_id, point_id, control_id = wp.tid()
68
+ unique_id = (env_id * num_control_points + point_id) * control_dim + control_id
69
+ r = wp.rand_init(seed[0], unique_id)
70
+ mean = mean_trajectory[0, point_id, control_id]
71
+ lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
72
+ sample = mean + noise_scale * wp.randn(r)
73
+ for _i in range(10):
74
+ if sample < lo or sample > hi:
75
+ sample = mean + noise_scale * wp.randn(r)
76
+ else:
77
+ break
78
+ rollout_trajectories[env_id, point_id, control_id] = wp.clamp(sample, lo, hi)
79
+
80
+
81
+ @wp.kernel
82
+ def replicate_states(
83
+ body_q_in: wp.array(dtype=wp.transform),
84
+ body_qd_in: wp.array(dtype=wp.spatial_vector),
85
+ bodies_per_env: int,
86
+ body_q_out: wp.array(dtype=wp.transform),
87
+ body_qd_out: wp.array(dtype=wp.spatial_vector),
88
+ ):
89
+ tid = wp.tid()
90
+ env_offset = tid * bodies_per_env
91
+ for i in range(bodies_per_env):
92
+ body_q_out[env_offset + i] = body_q_in[i]
93
+ body_qd_out[env_offset + i] = body_qd_in[i]
94
+
95
+
96
+ @wp.kernel
97
+ def drone_cost(
98
+ body_q: wp.array(dtype=wp.transform),
99
+ body_qd: wp.array(dtype=wp.spatial_vector),
100
+ targets: wp.array(dtype=wp.vec3),
101
+ prop_control: wp.array(dtype=float),
102
+ step: int,
103
+ horizon_length: int,
104
+ weighting: float,
105
+ cost: wp.array(dtype=wp.float32),
106
+ ):
107
+ env_id = wp.tid()
108
+ tf = body_q[env_id]
109
+ target = targets[0]
110
+
111
+ pos_drone = wp.transform_get_translation(tf)
112
+ pos_cost = wp.length_sq(pos_drone - target)
113
+ altitude_cost = wp.max(pos_drone[1] - 0.75, 0.0) + wp.max(0.25 - pos_drone[1], 0.0)
114
+ upvector = wp.vec3(0.0, 1.0, 0.0)
115
+ drone_up = wp.transform_vector(tf, upvector)
116
+ upright_cost = 1.0 - wp.dot(drone_up, upvector)
117
+
118
+ vel_drone = body_qd[env_id]
119
+
120
+ # Encourage zero velocity.
121
+ vel_cost = wp.length_sq(vel_drone)
122
+
123
+ control = wp.vec4(
124
+ prop_control[env_id * 4 + 0],
125
+ prop_control[env_id * 4 + 1],
126
+ prop_control[env_id * 4 + 2],
127
+ prop_control[env_id * 4 + 3],
128
+ )
129
+ control_cost = wp.dot(control, control)
130
+
131
+ discount = 0.8 ** wp.float(horizon_length - step - 1) / wp.float(horizon_length) ** 2.0
132
+
133
+ pos_weight = 1000.0
134
+ altitude_weight = 100.0
135
+ control_weight = 0.05
136
+ vel_weight = 0.1
137
+ upright_weight = 10.0
138
+ total_weight = pos_weight + altitude_weight + control_weight + vel_weight + upright_weight
139
+
140
+ wp.atomic_add(
141
+ cost,
142
+ env_id,
143
+ (
144
+ pos_cost * pos_weight
145
+ + altitude_cost * altitude_weight
146
+ + control_cost * control_weight
147
+ + vel_cost * vel_weight
148
+ + upright_cost * upright_weight
149
+ )
150
+ * (weighting / total_weight)
151
+ * discount,
152
+ )
153
+
154
+
155
+ @wp.kernel
156
+ def collision_cost(
157
+ body_q: wp.array(dtype=wp.transform),
158
+ obstacle_ids: wp.array(dtype=int, ndim=2),
159
+ shape_X_bs: wp.array(dtype=wp.transform),
160
+ geo: wp.sim.ModelShapeGeometry,
161
+ margin: float,
162
+ weighting: float,
163
+ cost: wp.array(dtype=wp.float32),
164
+ ):
165
+ env_id, obs_id = wp.tid()
166
+ shape_index = obstacle_ids[env_id, obs_id]
167
+
168
+ px = wp.transform_get_translation(body_q[env_id])
169
+
170
+ X_bs = shape_X_bs[shape_index]
171
+
172
+ # transform particle position to shape local space
173
+ x_local = wp.transform_point(wp.transform_inverse(X_bs), px)
174
+
175
+ # geo description
176
+ geo_type = geo.type[shape_index]
177
+ geo_scale = geo.scale[shape_index]
178
+
179
+ # evaluate shape sdf
180
+ d = 1e6
181
+
182
+ if geo_type == wp.sim.GEO_SPHERE:
183
+ d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
184
+ elif geo_type == wp.sim.GEO_BOX:
185
+ d = box_sdf(geo_scale, x_local)
186
+ elif geo_type == wp.sim.GEO_CAPSULE:
187
+ d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
188
+ elif geo_type == wp.sim.GEO_CYLINDER:
189
+ d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
190
+ elif geo_type == wp.sim.GEO_CONE:
191
+ d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
192
+ elif geo_type == wp.sim.GEO_MESH:
193
+ mesh = geo.source[shape_index]
194
+ min_scale = wp.min(geo_scale)
195
+ max_dist = margin / min_scale
196
+ d = mesh_sdf(mesh, wp.cw_div(x_local, geo_scale), max_dist)
197
+ d *= min_scale # TODO fix this, mesh scaling needs to be handled properly
198
+ elif geo_type == wp.sim.GEO_SDF:
199
+ volume = geo.source[shape_index]
200
+ xpred_local = wp.volume_world_to_index(volume, wp.cw_div(x_local, geo_scale))
201
+ nn = wp.vec3(0.0, 0.0, 0.0)
202
+ d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, nn)
203
+ elif geo_type == wp.sim.GEO_PLANE:
204
+ d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
205
+
206
+ d = wp.max(d, 0.0)
207
+ if d < margin:
208
+ c = margin - d
209
+ wp.atomic_add(cost, env_id, weighting * c)
210
+
211
+
212
+ @wp.kernel
213
+ def enforce_control_limits(
214
+ control_limits: wp.array(dtype=float, ndim=2),
215
+ control_points: wp.array(dtype=float, ndim=3),
216
+ ):
217
+ env_id, t_id, control_id = wp.tid()
218
+ lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
219
+ control_points[env_id, t_id, control_id] = wp.clamp(control_points[env_id, t_id, control_id], lo, hi)
220
+
221
+
222
+ @wp.kernel
223
+ def pick_best_trajectory(
224
+ rollout_trajectories: wp.array(dtype=float, ndim=3),
225
+ lowest_cost_id: int,
226
+ best_traj: wp.array(dtype=float, ndim=3),
227
+ ):
228
+ t_id, control_id = wp.tid()
229
+ best_traj[0, t_id, control_id] = rollout_trajectories[lowest_cost_id, t_id, control_id]
230
+
231
+
232
+ @wp.kernel
233
+ def interpolate_control_linear(
234
+ control_points: wp.array(dtype=float, ndim=3),
235
+ control_dofs: wp.array(dtype=int),
236
+ control_gains: wp.array(dtype=float),
237
+ t: float,
238
+ torque_dim: int,
239
+ torques: wp.array(dtype=float),
240
+ ):
241
+ env_id, control_id = wp.tid()
242
+ t_id = int(t)
243
+ frac = t - wp.floor(t)
244
+ control_left = control_points[env_id, t_id, control_id]
245
+ control_right = control_points[env_id, t_id + 1, control_id]
246
+ torque_id = env_id * torque_dim + control_dofs[control_id]
247
+ action = control_left * (1.0 - frac) + control_right * frac
248
+ torques[torque_id] = action * control_gains[control_id]
249
+
250
+
251
+ @wp.kernel
252
+ def compute_prop_wrenches(
253
+ props: wp.array(dtype=Propeller),
254
+ controls: wp.array(dtype=float),
255
+ body_q: wp.array(dtype=wp.transform),
256
+ body_com: wp.array(dtype=wp.vec3),
257
+ body_f: wp.array(dtype=wp.spatial_vector),
258
+ ):
259
+ tid = wp.tid()
260
+ prop = props[tid]
261
+ control = controls[tid]
262
+ tf = body_q[prop.body]
263
+ dir = wp.transform_vector(tf, prop.dir)
264
+ force = dir * prop.max_thrust * control
265
+ torque = dir * prop.max_torque * control * prop.turning_direction
266
+ moment_arm = wp.transform_point(tf, prop.pos) - wp.transform_point(tf, body_com[prop.body])
267
+ torque += wp.cross(moment_arm, force)
268
+ # Apply angular damping.
269
+ torque *= 0.8
270
+ wp.atomic_add(body_f, prop.body, wp.spatial_vector(torque, force))
271
+
272
+
273
+ def define_propeller(
274
+ drone: int,
275
+ pos: wp.vec3,
276
+ fps: float,
277
+ thrust: float = 0.109919,
278
+ power: float = 0.040164,
279
+ diameter: float = 0.2286,
280
+ height: float = 0.01,
281
+ max_rpm: float = 6396.667,
282
+ turning_direction: float = 1.0,
283
+ ):
284
+ # Air density at sea level.
285
+ air_density = 1.225 # kg / m^3
286
+
287
+ rps = max_rpm / fps
288
+ max_speed = rps * wp.TAU # radians / sec
289
+ rps_square = rps**2
290
+
291
+ prop = Propeller()
292
+ prop.body = drone
293
+ prop.pos = pos
294
+ prop.dir = wp.vec3(0.0, 1.0, 0.0)
295
+ prop.thrust = thrust
296
+ prop.power = power
297
+ prop.diameter = diameter
298
+ prop.height = height
299
+ prop.max_rpm = max_rpm
300
+ prop.max_thrust = thrust * air_density * rps_square * diameter**4
301
+ prop.max_torque = power * air_density * rps_square * diameter**5 / wp.TAU
302
+ prop.turning_direction = turning_direction
303
+ prop.max_speed_square = max_speed**2
304
+
305
+ return prop
306
+
307
+
308
+ class Drone:
309
+ def __init__(
310
+ self,
311
+ name: str,
312
+ fps: float,
313
+ trajectory_shape: Tuple[int, int],
314
+ variation_count: int = 1,
315
+ size: float = 1.0,
316
+ requires_grad: bool = False,
317
+ state_count: Optional[int] = None,
318
+ ) -> None:
319
+ self.variation_count = variation_count
320
+ self.requires_grad = requires_grad
321
+
322
+ # Current tick of the simulation, including substeps.
323
+ self.sim_tick = 0
324
+
325
+ # Initialize the helper to build a physics scene.
326
+ builder = wp.sim.ModelBuilder()
327
+ builder.rigid_contact_margin = 0.05
328
+
329
+ # Initialize the rigid bodies, propellers, and colliders.
330
+ props = []
331
+ colliders = []
332
+ crossbar_length = size
333
+ crossbar_height = size * 0.05
334
+ crossbar_width = size * 0.05
335
+ carbon_fiber_density = 1750.0 # kg / m^3
336
+ for i in range(variation_count):
337
+ # Register the drone as a rigid body in the simulation model.
338
+ body = builder.add_body(name=f"{name}_{i}")
339
+
340
+ # Define the shapes making up the drone's rigid body.
341
+ builder.add_shape_box(
342
+ body,
343
+ hx=crossbar_length,
344
+ hy=crossbar_height,
345
+ hz=crossbar_width,
346
+ density=carbon_fiber_density,
347
+ collision_group=i,
348
+ )
349
+ builder.add_shape_box(
350
+ body,
351
+ hx=crossbar_width,
352
+ hy=crossbar_height,
353
+ hz=crossbar_length,
354
+ density=carbon_fiber_density,
355
+ collision_group=i,
356
+ )
357
+
358
+ # Initialize the propellers.
359
+ props.extend(
360
+ (
361
+ define_propeller(
362
+ body,
363
+ wp.vec3(crossbar_length, 0.0, 0.0),
364
+ fps,
365
+ turning_direction=-1.0,
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(0.0, 0.0, crossbar_length),
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
+ ),
386
+ )
387
+
388
+ # Initialize the colliders.
389
+ colliders.append(
390
+ (
391
+ builder.add_shape_capsule(
392
+ -1,
393
+ pos=(0.5, 2.0, 0.5),
394
+ radius=0.15,
395
+ half_height=2.0,
396
+ collision_group=i,
397
+ ),
398
+ ),
399
+ )
400
+ self.props = wp.array(props, dtype=Propeller)
401
+ self.colliders = wp.array(colliders, dtype=int)
402
+
403
+ # Build the model and set-up its properties.
404
+ self.model = builder.finalize(requires_grad=requires_grad)
405
+ self.model.ground = False
406
+
407
+ # Initialize the required simulation states.
408
+ if requires_grad:
409
+ self.states = tuple(self.model.state() for _ in range(state_count + 1))
410
+ self.controls = tuple(self.model.control() for _ in range(state_count))
411
+ else:
412
+ # When only running a forward simulation, we don't need to store
413
+ # the history of the states at each step, instead we use double
414
+ # buffering to represent the previous and next states.
415
+ self.states = [self.model.state(), self.model.state()]
416
+ self.controls = (self.model.control(),)
417
+
418
+ # create array for the propeller controls
419
+ for control in self.controls:
420
+ control.prop_controls = wp.zeros(len(self.props), dtype=float, requires_grad=requires_grad)
421
+
422
+ # Define the trajectories as arrays of control points.
423
+ # The point data has an additional item to support linear interpolation.
424
+ self.trajectories = wp.zeros(
425
+ (variation_count, trajectory_shape[0], trajectory_shape[1]),
426
+ dtype=float,
427
+ requires_grad=requires_grad,
428
+ )
429
+
430
+ # Store some miscellaneous info.
431
+ self.body_count = len(builder.body_q)
432
+ self.collider_count = self.colliders.shape[1]
433
+ self.collision_radius = crossbar_length
434
+
435
+ @property
436
+ def state(self) -> wp.sim.State:
437
+ return self.states[self.sim_tick if self.requires_grad else 0]
438
+
439
+ @property
440
+ def next_state(self) -> wp.sim.State:
441
+ return self.states[self.sim_tick + 1 if self.requires_grad else 1]
442
+
443
+ @property
444
+ def control(self) -> wp.sim.Control:
445
+ return self.controls[min(len(self.controls) - 1, self.sim_tick) if self.requires_grad else 0]
446
+
447
+
448
+ class Example:
449
+ def __init__(
450
+ self,
451
+ stage_path="example_drone.usd",
452
+ verbose=False,
453
+ render_rollouts=False,
454
+ drone_path=DEFAULT_DRONE_PATH,
455
+ num_frames=360,
456
+ num_rollouts=16,
457
+ headless=True,
458
+ ) -> None:
459
+ # Number of frames per second.
460
+ self.fps = 60
461
+
462
+ # Duration of the simulation in number of frames.
463
+ self.num_frames = num_frames
464
+
465
+ # Number of simulation substeps to take per step.
466
+ self.sim_substep_count = 1
467
+
468
+ # Delta time between each simulation substep.
469
+ self.frame_dt = 1.0 / self.fps
470
+
471
+ # Delta time between each simulation substep.
472
+ self.sim_dt = self.frame_dt / self.sim_substep_count
473
+
474
+ # Frame number used for simulation and rendering.
475
+ self.frame = 0
476
+
477
+ # Targets positions that the drone will try to reach in turn.
478
+ self.targets = (
479
+ wp.vec3(0.0, 0.5, 1.0),
480
+ wp.vec3(1.0, 0.5, 0.0),
481
+ )
482
+
483
+ # Define the index of the active target.
484
+ # We start with -1 since it'll be incremented on the first frame.
485
+ self.target_idx = -1
486
+ # use a Warp array to store the current target so that we can assign
487
+ # a new target to it while retaining the original CUDA graph.
488
+ self.current_target = wp.array([self.targets[self.target_idx + 1]], dtype=wp.vec3)
489
+
490
+ # Number of steps to run at each frame for the optimisation pass.
491
+ self.optim_step_count = 20
492
+
493
+ # Time steps between control points.
494
+ self.control_point_step = 10
495
+
496
+ # Number of control horizon points to interpolate between.
497
+ self.control_point_count = 3
498
+
499
+ self.control_point_data_count = self.control_point_count + 1
500
+ self.control_dofs = wp.array((0, 1, 2, 3), dtype=int)
501
+ self.control_dim = len(self.control_dofs)
502
+ self.control_gains = wp.array((0.8,) * self.control_dim, dtype=float)
503
+ self.control_limits = wp.array(((0.1, 1.0),) * self.control_dim, dtype=float)
504
+
505
+ drone_size = 0.2
506
+
507
+ # Declare the reference drone.
508
+ self.drone = Drone(
509
+ "drone",
510
+ self.fps,
511
+ (self.control_point_data_count, self.control_dim),
512
+ size=drone_size,
513
+ )
514
+
515
+ # Declare the drone's rollouts.
516
+ # These allow to run parallel simulations in order to find the best
517
+ # trajectory at each control point.
518
+ self.rollout_count = num_rollouts
519
+ self.rollout_step_count = self.control_point_step * self.control_point_count
520
+ self.rollouts = Drone(
521
+ "rollout",
522
+ self.fps,
523
+ (self.control_point_data_count, self.control_dim),
524
+ variation_count=self.rollout_count,
525
+ size=drone_size,
526
+ requires_grad=True,
527
+ state_count=self.rollout_step_count * self.sim_substep_count,
528
+ )
529
+
530
+ self.seed = wp.zeros(1, dtype=int)
531
+ self.rollout_costs = wp.zeros(self.rollout_count, dtype=float, requires_grad=True)
532
+
533
+ # Use the Euler integrator for stepping through the simulation.
534
+ self.integrator = wp.sim.SemiImplicitIntegrator()
535
+
536
+ self.optimizer = wp.optim.SGD(
537
+ [self.rollouts.trajectories.flatten()],
538
+ lr=1e-2,
539
+ nesterov=False,
540
+ momentum=0.0,
541
+ )
542
+
543
+ self.tape = None
544
+
545
+ if stage_path:
546
+ if not headless:
547
+ self.renderer = wp.sim.render.SimRendererOpenGL(self.drone.model, stage_path, fps=self.fps)
548
+ else:
549
+ # Helper to render the physics scene as a USD file.
550
+ self.renderer = wp.sim.render.SimRenderer(self.drone.model, stage_path, fps=self.fps)
551
+
552
+ if isinstance(self.renderer, warp.sim.render.SimRendererUsd):
553
+ from pxr import UsdGeom
554
+
555
+ # Remove the default drone geometries.
556
+ drone_root_prim = self.renderer.stage.GetPrimAtPath("/root/body_0_drone_0")
557
+ for prim in drone_root_prim.GetChildren():
558
+ self.renderer.stage.RemovePrim(prim.GetPath())
559
+
560
+ # Add a reference to the drone geometry.
561
+ drone_prim = self.renderer.stage.OverridePrim(f"{drone_root_prim.GetPath()}/crazyflie")
562
+ drone_prim.GetReferences().AddReference(drone_path)
563
+ drone_xform = UsdGeom.Xform(drone_prim)
564
+ drone_xform.AddTranslateOp().Set((0.0, -0.05, 0.0))
565
+ drone_xform.AddRotateYOp().Set(45.0)
566
+ drone_xform.AddScaleOp().Set((drone_size * 20.0,) * 3)
567
+
568
+ # Get the propellers to spin
569
+ for turning_direction in ("cw", "ccw"):
570
+ spin = 100.0 * 360.0 * self.num_frames / self.fps
571
+ spin = spin if turning_direction == "ccw" else -spin
572
+ for side in ("back", "front"):
573
+ prop_prim = self.renderer.stage.OverridePrim(
574
+ f"{drone_prim.GetPath()}/propeller_{turning_direction}_{side}"
575
+ )
576
+ prop_xform = UsdGeom.Xform(prop_prim)
577
+ rot = prop_xform.AddRotateYOp()
578
+ rot.Set(0.0, 0.0)
579
+ rot.Set(spin, self.num_frames)
580
+ else:
581
+ self.renderer = None
582
+
583
+ self.use_cuda_graph = wp.get_device().is_cuda
584
+ self.optim_graph = None
585
+
586
+ self.render_rollouts = render_rollouts
587
+ self.verbose = verbose
588
+
589
+ def update_drone(self, drone: Drone) -> None:
590
+ drone.state.clear_forces()
591
+
592
+ wp.launch(
593
+ interpolate_control_linear,
594
+ dim=(
595
+ drone.variation_count,
596
+ self.control_dim,
597
+ ),
598
+ inputs=(
599
+ drone.trajectories,
600
+ self.control_dofs,
601
+ self.control_gains,
602
+ drone.sim_tick / (self.sim_substep_count * self.control_point_step),
603
+ self.control_dim,
604
+ ),
605
+ outputs=(drone.control.prop_controls,),
606
+ )
607
+
608
+ wp.launch(
609
+ compute_prop_wrenches,
610
+ dim=len(drone.props),
611
+ inputs=(
612
+ drone.props,
613
+ drone.control.prop_controls,
614
+ drone.state.body_q,
615
+ drone.model.body_com,
616
+ ),
617
+ outputs=(drone.state.body_f,),
618
+ )
619
+
620
+ self.integrator.simulate(
621
+ drone.model,
622
+ drone.state,
623
+ drone.next_state,
624
+ self.sim_dt,
625
+ drone.control,
626
+ )
627
+
628
+ drone.sim_tick += 1
629
+
630
+ def forward(self):
631
+ # Evaluate the rollouts with their costs.
632
+ self.rollouts.sim_tick = 0
633
+ self.rollout_costs.zero_()
634
+ wp.launch(
635
+ replicate_states,
636
+ dim=self.rollout_count,
637
+ inputs=(
638
+ self.drone.state.body_q,
639
+ self.drone.state.body_qd,
640
+ self.drone.body_count,
641
+ ),
642
+ outputs=(
643
+ self.rollouts.state.body_q,
644
+ self.rollouts.state.body_qd,
645
+ ),
646
+ )
647
+
648
+ for i in range(self.rollout_step_count):
649
+ for _ in range(self.sim_substep_count):
650
+ self.update_drone(self.rollouts)
651
+
652
+ wp.launch(
653
+ drone_cost,
654
+ dim=self.rollout_count,
655
+ inputs=(
656
+ self.rollouts.state.body_q,
657
+ self.rollouts.state.body_qd,
658
+ self.current_target,
659
+ self.rollouts.control.prop_controls,
660
+ i,
661
+ self.rollout_step_count,
662
+ 1e3,
663
+ ),
664
+ outputs=(self.rollout_costs,),
665
+ )
666
+ wp.launch(
667
+ collision_cost,
668
+ dim=(
669
+ self.rollout_count,
670
+ self.rollouts.collider_count,
671
+ ),
672
+ inputs=(
673
+ self.rollouts.state.body_q,
674
+ self.rollouts.colliders,
675
+ self.rollouts.model.shape_transform,
676
+ self.rollouts.model.shape_geo,
677
+ self.rollouts.collision_radius,
678
+ 1e4,
679
+ ),
680
+ outputs=(self.rollout_costs,),
681
+ )
682
+
683
+ def step_optimizer(self):
684
+ if self.optim_graph is None:
685
+ self.tape = wp.Tape()
686
+ with self.tape:
687
+ self.forward()
688
+ self.rollout_costs.grad.fill_(1.0)
689
+ self.tape.backward()
690
+ else:
691
+ wp.capture_launch(self.optim_graph)
692
+
693
+ self.optimizer.step([self.rollouts.trajectories.grad.flatten()])
694
+
695
+ # Enforce limits on the control points.
696
+ wp.launch(
697
+ enforce_control_limits,
698
+ dim=self.rollouts.trajectories.shape,
699
+ inputs=(self.control_limits,),
700
+ outputs=(self.rollouts.trajectories,),
701
+ )
702
+ self.tape.zero()
703
+
704
+ def step(self):
705
+ if self.frame % int((self.num_frames / len(self.targets))) == 0:
706
+ if self.verbose:
707
+ print(f"Choosing new flight target: {self.target_idx+1}")
708
+
709
+ self.target_idx += 1
710
+ self.target_idx %= len(self.targets)
711
+
712
+ # Assign the new target to the current target array.
713
+ self.current_target.assign([self.targets[self.target_idx]])
714
+
715
+ if self.use_cuda_graph and self.optim_graph is None:
716
+ with wp.ScopedCapture() as capture:
717
+ self.tape = wp.Tape()
718
+ with self.tape:
719
+ self.forward()
720
+ self.rollout_costs.grad.fill_(1.0)
721
+ self.tape.backward()
722
+ self.optim_graph = capture.graph
723
+
724
+ # Sample control waypoints around the nominal trajectory.
725
+ noise_scale = 0.15
726
+ wp.launch(
727
+ sample_gaussian,
728
+ dim=(
729
+ self.rollouts.trajectories.shape[0] - 1,
730
+ self.rollouts.trajectories.shape[1],
731
+ self.rollouts.trajectories.shape[2],
732
+ ),
733
+ inputs=(
734
+ self.drone.trajectories,
735
+ noise_scale,
736
+ self.control_point_data_count,
737
+ self.control_dim,
738
+ self.control_limits,
739
+ self.seed,
740
+ ),
741
+ outputs=(self.rollouts.trajectories,),
742
+ )
743
+
744
+ wp.launch(
745
+ increment_seed,
746
+ dim=1,
747
+ inputs=(),
748
+ outputs=(self.seed,),
749
+ )
750
+
751
+ for _ in range(self.optim_step_count):
752
+ self.step_optimizer()
753
+
754
+ # Pick the best trajectory.
755
+ wp.synchronize()
756
+ lowest_cost_id = np.argmin(self.rollout_costs.numpy())
757
+ wp.launch(
758
+ pick_best_trajectory,
759
+ dim=(
760
+ self.control_point_data_count,
761
+ self.control_dim,
762
+ ),
763
+ inputs=(
764
+ self.rollouts.trajectories,
765
+ lowest_cost_id,
766
+ ),
767
+ outputs=(self.drone.trajectories,),
768
+ )
769
+ self.rollouts.trajectories[-1].assign(self.drone.trajectories[0])
770
+
771
+ # Simulate the drone.
772
+ self.drone.sim_tick = 0
773
+ for _ in range(self.sim_substep_count):
774
+ self.update_drone(self.drone)
775
+
776
+ # Swap the drone's states.
777
+ (self.drone.states[0], self.drone.states[1]) = (self.drone.states[1], self.drone.states[0])
778
+
779
+ def render(self):
780
+ if self.renderer is None:
781
+ return
782
+
783
+ self.renderer.begin_frame(self.frame / self.fps)
784
+ self.renderer.render(self.drone.state)
785
+
786
+ # Render a sphere as the current target.
787
+ self.renderer.render_sphere(
788
+ "target",
789
+ self.targets[self.target_idx],
790
+ wp.quat_identity(),
791
+ 0.05,
792
+ color=(1.0, 0.0, 0.0),
793
+ )
794
+
795
+ # Render the rollout trajectories.
796
+ if self.render_rollouts:
797
+ costs = self.rollout_costs.numpy()
798
+
799
+ positions = np.array([x.body_q.numpy()[:, :3] for x in self.rollouts.states])
800
+
801
+ min_cost = np.min(costs)
802
+ max_cost = np.max(costs)
803
+ for i in range(self.rollout_count):
804
+ # Flip colors, so red means best trajectory, blue worst.
805
+ color = wp.render.bourke_color_map(-max_cost, -min_cost, -costs[i])
806
+ self.renderer.render_line_strip(
807
+ name=f"rollout_{i}",
808
+ vertices=positions[:, i],
809
+ color=color,
810
+ radius=0.001,
811
+ )
812
+
813
+ self.renderer.end_frame()
814
+
815
+
816
+ if __name__ == "__main__":
817
+ import argparse
818
+
819
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
820
+ parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
821
+ parser.add_argument(
822
+ "--stage_path",
823
+ type=lambda x: None if x == "None" else str(x),
824
+ default="example_drone.usd",
825
+ help="Path to the output USD file.",
826
+ )
827
+ parser.add_argument("--num_frames", type=int, default=360, help="Total number of frames.")
828
+ parser.add_argument("--num_rollouts", type=int, default=16, help="Number of drone rollouts.")
829
+ parser.add_argument(
830
+ "--drone_path",
831
+ type=str,
832
+ default=os.path.join(warp.examples.get_asset_directory(), "crazyflie.usd"),
833
+ help="Path to the USD file to use as the reference for the drone prim in the output stage.",
834
+ )
835
+ parser.add_argument("--render_rollouts", action="store_true", help="Add rollout trajectories to the output stage.")
836
+ parser.add_argument(
837
+ "--headless",
838
+ action="store_true",
839
+ help="Run in headless mode, suppressing the opening of any graphical windows.",
840
+ )
841
+ parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
842
+
843
+ args = parser.parse_known_args()[0]
844
+
845
+ with wp.ScopedDevice(args.device):
846
+ example = Example(
847
+ stage_path=args.stage_path,
848
+ verbose=args.verbose,
849
+ render_rollouts=args.render_rollouts,
850
+ drone_path=args.drone_path,
851
+ num_frames=args.num_frames,
852
+ num_rollouts=args.num_rollouts,
853
+ headless=args.headless,
854
+ )
855
+ for _i in range(args.num_frames):
856
+ example.step()
857
+ example.render()
858
+ example.frame += 1
859
+
860
+ loss = np.min(example.rollout_costs.numpy())
861
+ print(f"[{example.frame:3d}/{example.num_frames}] loss={loss:.8f}")
862
+
863
+ if example.renderer is not None:
864
+ example.renderer.save()