warp-lang 1.0.2__py3-none-manylinux2014_x86_64.whl → 1.1.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 (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 -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 +146 -146
  34. warp/examples/benchmarks/benchmark_launches.py +295 -295
  35. warp/examples/browse.py +29 -29
  36. warp/examples/core/example_dem.py +234 -219
  37. warp/examples/core/example_fluid.py +293 -267
  38. warp/examples/core/example_graph_capture.py +144 -126
  39. warp/examples/core/example_marching_cubes.py +188 -174
  40. warp/examples/core/example_mesh.py +174 -155
  41. warp/examples/core/example_mesh_intersect.py +205 -193
  42. warp/examples/core/example_nvdb.py +176 -170
  43. warp/examples/core/example_raycast.py +105 -90
  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 -387
  47. warp/examples/core/example_torch.py +222 -181
  48. warp/examples/core/example_wave.py +263 -248
  49. warp/examples/fem/bsr_utils.py +378 -380
  50. warp/examples/fem/example_apic_fluid.py +407 -389
  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 -246
  65. warp/examples/optim/example_cloth_throw.py +222 -209
  66. warp/examples/optim/example_diffray.py +566 -536
  67. warp/examples/optim/example_drone.py +864 -835
  68. warp/examples/optim/example_inverse_kinematics.py +176 -168
  69. warp/examples/optim/example_inverse_kinematics_torch.py +185 -169
  70. warp/examples/optim/example_spring_cage.py +239 -231
  71. warp/examples/optim/example_trajectory.py +223 -199
  72. warp/examples/optim/example_walker.py +306 -293
  73. warp/examples/sim/example_cartpole.py +139 -129
  74. warp/examples/sim/example_cloth.py +196 -186
  75. warp/examples/sim/example_granular.py +124 -111
  76. warp/examples/sim/example_granular_collision_sdf.py +197 -186
  77. warp/examples/sim/example_jacobian_ik.py +236 -214
  78. warp/examples/sim/example_particle_chain.py +118 -105
  79. warp/examples/sim/example_quadruped.py +193 -180
  80. warp/examples/sim/example_rigid_chain.py +197 -187
  81. warp/examples/sim/example_rigid_contact.py +189 -177
  82. warp/examples/sim/example_rigid_force.py +127 -125
  83. warp/examples/sim/example_rigid_gyroscopic.py +109 -95
  84. warp/examples/sim/example_rigid_soft_contact.py +134 -122
  85. warp/examples/sim/example_soft_body.py +190 -177
  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.2.dist-info → warp_lang-1.1.0.dist-info}/LICENSE.md +126 -126
  339. {warp_lang-1.0.2.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.2.dist-info/RECORD +0 -352
  345. {warp_lang-1.0.2.dist-info → warp_lang-1.1.0.dist-info}/WHEEL +0 -0
  346. {warp_lang-1.0.2.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.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
+ 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()