jaxsim 0.2.dev188__py3-none-any.whl → 0.2.dev364__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. jaxsim/__init__.py +3 -4
  2. jaxsim/_version.py +2 -2
  3. jaxsim/api/__init__.py +3 -1
  4. jaxsim/api/com.py +240 -0
  5. jaxsim/api/common.py +13 -2
  6. jaxsim/api/contact.py +120 -43
  7. jaxsim/api/data.py +112 -71
  8. jaxsim/api/joint.py +77 -36
  9. jaxsim/api/kin_dyn_parameters.py +777 -0
  10. jaxsim/api/link.py +150 -75
  11. jaxsim/api/model.py +542 -269
  12. jaxsim/api/ode.py +88 -72
  13. jaxsim/api/ode_data.py +694 -0
  14. jaxsim/api/references.py +12 -11
  15. jaxsim/integrators/__init__.py +2 -2
  16. jaxsim/integrators/common.py +110 -24
  17. jaxsim/integrators/fixed_step.py +11 -67
  18. jaxsim/integrators/variable_step.py +610 -0
  19. jaxsim/math/__init__.py +11 -0
  20. jaxsim/math/adjoint.py +24 -2
  21. jaxsim/math/joint_model.py +335 -0
  22. jaxsim/math/quaternion.py +44 -3
  23. jaxsim/math/rotation.py +4 -4
  24. jaxsim/math/transform.py +93 -0
  25. jaxsim/parsers/descriptions/collision.py +14 -0
  26. jaxsim/parsers/descriptions/link.py +13 -2
  27. jaxsim/parsers/kinematic_graph.py +5 -0
  28. jaxsim/parsers/rod/utils.py +7 -8
  29. jaxsim/rbda/__init__.py +7 -0
  30. jaxsim/rbda/aba.py +295 -0
  31. jaxsim/rbda/collidable_points.py +142 -0
  32. jaxsim/{physics/algos → rbda}/crba.py +43 -42
  33. jaxsim/rbda/forward_kinematics.py +113 -0
  34. jaxsim/rbda/jacobian.py +201 -0
  35. jaxsim/rbda/rnea.py +237 -0
  36. jaxsim/rbda/soft_contacts.py +296 -0
  37. jaxsim/rbda/utils.py +152 -0
  38. jaxsim/terrain/__init__.py +2 -0
  39. jaxsim/{physics/algos → terrain}/terrain.py +4 -6
  40. jaxsim/utils/__init__.py +1 -4
  41. jaxsim/utils/hashless.py +18 -0
  42. jaxsim/utils/jaxsim_dataclass.py +281 -30
  43. {jaxsim-0.2.dev188.dist-info → jaxsim-0.2.dev364.dist-info}/METADATA +4 -6
  44. jaxsim-0.2.dev364.dist-info/RECORD +64 -0
  45. {jaxsim-0.2.dev188.dist-info → jaxsim-0.2.dev364.dist-info}/WHEEL +1 -1
  46. jaxsim/high_level/__init__.py +0 -2
  47. jaxsim/high_level/common.py +0 -11
  48. jaxsim/high_level/joint.py +0 -148
  49. jaxsim/high_level/link.py +0 -259
  50. jaxsim/high_level/model.py +0 -1686
  51. jaxsim/math/conv.py +0 -114
  52. jaxsim/math/joint.py +0 -102
  53. jaxsim/math/plucker.py +0 -100
  54. jaxsim/physics/__init__.py +0 -12
  55. jaxsim/physics/algos/__init__.py +0 -0
  56. jaxsim/physics/algos/aba.py +0 -254
  57. jaxsim/physics/algos/aba_motors.py +0 -284
  58. jaxsim/physics/algos/forward_kinematics.py +0 -79
  59. jaxsim/physics/algos/jacobian.py +0 -98
  60. jaxsim/physics/algos/rnea.py +0 -180
  61. jaxsim/physics/algos/rnea_motors.py +0 -196
  62. jaxsim/physics/algos/soft_contacts.py +0 -523
  63. jaxsim/physics/algos/utils.py +0 -69
  64. jaxsim/physics/model/__init__.py +0 -0
  65. jaxsim/physics/model/ground_contact.py +0 -55
  66. jaxsim/physics/model/physics_model.py +0 -388
  67. jaxsim/physics/model/physics_model_state.py +0 -283
  68. jaxsim/simulation/__init__.py +0 -4
  69. jaxsim/simulation/integrators.py +0 -393
  70. jaxsim/simulation/ode.py +0 -290
  71. jaxsim/simulation/ode_data.py +0 -96
  72. jaxsim/simulation/ode_integration.py +0 -62
  73. jaxsim/simulation/simulator.py +0 -543
  74. jaxsim/simulation/simulator_callbacks.py +0 -79
  75. jaxsim/simulation/utils.py +0 -15
  76. jaxsim/sixd/__init__.py +0 -2
  77. jaxsim/utils/oop.py +0 -536
  78. jaxsim/utils/vmappable.py +0 -117
  79. jaxsim-0.2.dev188.dist-info/RECORD +0 -81
  80. {jaxsim-0.2.dev188.dist-info → jaxsim-0.2.dev364.dist-info}/LICENSE +0 -0
  81. {jaxsim-0.2.dev188.dist-info → jaxsim-0.2.dev364.dist-info}/top_level.txt +0 -0
@@ -1,393 +0,0 @@
1
- import enum
2
- from typing import Any, Callable
3
-
4
- import jax
5
- import jax.numpy as jnp
6
- from jax.tree_util import tree_map
7
-
8
- import jaxsim.typing as jtp
9
- from jaxsim.math.quaternion import Quaternion
10
- from jaxsim.physics.algos.soft_contacts import SoftContactsState
11
- from jaxsim.physics.model.physics_model_state import PhysicsModelState
12
- from jaxsim.simulation.ode_data import ODEState
13
- from jaxsim.sixd import se3, so3
14
-
15
- Time = jtp.FloatLike
16
- TimeStep = jtp.FloatLike
17
- TimeHorizon = jtp.VectorLike
18
-
19
- State = jtp.PyTree
20
- StateDerivative = jtp.PyTree
21
-
22
- StateDerivativeCallable = Callable[
23
- [State, Time], tuple[StateDerivative, dict[str, Any]]
24
- ]
25
-
26
-
27
- class IntegratorType(enum.IntEnum):
28
- RungeKutta4 = enum.auto()
29
- EulerForward = enum.auto()
30
- EulerSemiImplicit = enum.auto()
31
- EulerSemiImplicitManifold = enum.auto()
32
-
33
-
34
- # =======================
35
- # Single-step integration
36
- # =======================
37
-
38
-
39
- def integrator_fixed_single_step(
40
- dx_dt: StateDerivativeCallable,
41
- x0: State | ODEState,
42
- t0: Time,
43
- tf: Time,
44
- integrator_type: IntegratorType,
45
- num_sub_steps: int = 1,
46
- ) -> tuple[State | ODEState, dict[str, Any]]:
47
- """
48
- Advance a state vector by integrating a sytem dynamics with a fixed-step integrator.
49
-
50
- Args:
51
- dx_dt: Callable that computes the state derivative.
52
- x0: Initial state.
53
- t0: Initial time.
54
- tf: Final time.
55
- integrator_type: Integrator type.
56
- num_sub_steps: Number of sub-steps to break the integration into.
57
-
58
- Returns:
59
- The final state and a dictionary including auxiliary data at t0.
60
- """
61
-
62
- # Compute the sub-step size.
63
- # We break dt in configurable sub-steps.
64
- dt = tf - t0
65
- sub_step_dt = dt / num_sub_steps
66
-
67
- # Initialize the carry
68
- Carry = tuple[State | ODEState, Time]
69
- carry_init: Carry = (x0, t0)
70
-
71
- def forward_euler_body_fun(carry: Carry, xs: None) -> tuple[Carry, None]:
72
- """
73
- Forward Euler integrator.
74
- """
75
-
76
- # Unpack the carry
77
- x_t0, t0 = carry
78
-
79
- # Compute the state derivative
80
- dxdt_t0, _ = dx_dt(x_t0, t0)
81
-
82
- # Integrate the dynamics
83
- x_tf = jax.tree_util.tree_map(
84
- lambda x, dxdt: x + sub_step_dt * dxdt, x_t0, dxdt_t0
85
- )
86
-
87
- # Update the time
88
- tf = t0 + sub_step_dt
89
-
90
- # Pack the carry
91
- carry = (x_tf, tf)
92
-
93
- return carry, None
94
-
95
- def rk4_body_fun(carry: Carry, xs: None) -> tuple[Carry, None]:
96
- """
97
- Runge-Kutta 4 integrator.
98
- """
99
-
100
- # Unpack the carry
101
- x_t0, t0 = carry
102
-
103
- # Helper to forward the state to compute k2 and k3 at midpoint and k4 at final
104
- euler_mid = lambda x, dxdt: x + (0.5 * sub_step_dt) * dxdt
105
- euler_fin = lambda x, dxdt: x + sub_step_dt * dxdt
106
-
107
- # Compute the RK4 slopes
108
- k1, _ = dx_dt(x_t0, t0)
109
- k2, _ = dx_dt(tree_map(euler_mid, x_t0, k1), t0 + 0.5 * sub_step_dt)
110
- k3, _ = dx_dt(tree_map(euler_mid, x_t0, k2), t0 + 0.5 * sub_step_dt)
111
- k4, _ = dx_dt(tree_map(euler_fin, x_t0, k3), t0 + sub_step_dt)
112
-
113
- # Average the slopes and compute the RK4 state derivative
114
- average = lambda k1, k2, k3, k4: (k1 + 2 * k2 + 2 * k3 + k4) / 6
115
- dxdt = jax.tree_util.tree_map(average, k1, k2, k3, k4)
116
-
117
- # Integrate the dynamics
118
- x_tf = jax.tree_util.tree_map(euler_fin, x_t0, dxdt)
119
-
120
- # Update the time
121
- tf = t0 + sub_step_dt
122
-
123
- # Pack the carry
124
- carry = (x_tf, tf)
125
-
126
- return carry, None
127
-
128
- def semi_implicit_euler_body_fun(carry: Carry, xs: None) -> tuple[Carry, None]:
129
- """
130
- Semi-implicit Euler integrator.
131
- """
132
-
133
- # Unpack the carry
134
- x_t0, t0 = carry
135
-
136
- # Compute the state derivative.
137
- # We only keep the quantities related to the acceleration and discard those
138
- # related to the velocity since we are going to use those implicitly integrated
139
- # from the accelerations.
140
- StateDerivative = ODEState
141
- dxdt_t0: StateDerivative = dx_dt(x_t0, t0)[0]
142
-
143
- # Extract the initial position ∈ ℝ⁷⁺ⁿ and initial velocity ∈ ℝ⁶⁺ⁿ.
144
- # This integrator, contrarily to most of the other ones, is not generic.
145
- # It expects to operate on an x object of class ODEState.
146
- pos_t0 = x_t0.physics_model.position()
147
- vel_t0 = x_t0.physics_model.velocity()
148
-
149
- # Extract the velocity derivative
150
- d_vel_dt = dxdt_t0.physics_model.velocity()
151
-
152
- # =============================================
153
- # Perform semi-implicit Euler integration [1-4]
154
- # =============================================
155
-
156
- # 1. Integrate the accelerations obtaining the implicit velocities
157
- # 2. Compute the derivative of the generalized position
158
- # 3. Integrate the implicit velocities
159
- # 4. Integrate the remaining state
160
- # 5. Outside the loop: integrate the quaternion on SO(3) manifold
161
-
162
- # ----------------------------------------------------------------
163
- # 1. Integrate the accelerations obtaining the implicit velocities
164
- # ----------------------------------------------------------------
165
-
166
- vel_tf = vel_t0 + sub_step_dt * d_vel_dt
167
-
168
- # -----------------------------------------------------
169
- # 2. Compute the derivative of the generalized position
170
- # -----------------------------------------------------
171
-
172
- # Extract the implicit angular velocity and the initial base quaternion
173
- W_ω_WB = vel_tf[3:6]
174
- W_Q_B = x_t0.physics_model.base_quaternion
175
-
176
- # Compute the quaternion derivative and the base position derivative
177
- W_Qd_B = Quaternion.derivative(
178
- quaternion=W_Q_B, omega=W_ω_WB, omega_in_body_fixed=False
179
- ).squeeze()
180
-
181
- # Compute the transform of the mixed base frame at t0
182
- W_H_BW = jnp.vstack(
183
- [
184
- jnp.block([jnp.eye(3), jnp.vstack(x_t0.physics_model.base_position)]),
185
- jnp.array([0, 0, 0, 1]),
186
- ]
187
- )
188
-
189
- # The derivative W_ṗ_B of the base position is the linear component of the
190
- # mixed velocity B[W]_v_WB. We need to compute it from the velocity in
191
- # inertial-fixed representation W_vl_WB.
192
- W_v_WB = vel_tf[0:6]
193
- BW_Xv_W = se3.SE3.from_matrix(W_H_BW).inverse().adjoint()
194
- BW_vl_WB = (BW_Xv_W @ W_v_WB)[0:3]
195
-
196
- # Compute the derivative of the generalized position
197
- d_pos_tf = (
198
- jnp.hstack([BW_vl_WB, vel_tf[6:]])
199
- if integrator_type is IntegratorType.EulerSemiImplicitManifold
200
- else jnp.hstack([BW_vl_WB, W_Qd_B, vel_tf[6:]])
201
- )
202
-
203
- # ------------------------------------
204
- # 3. Integrate the implicit velocities
205
- # ------------------------------------
206
-
207
- pos_tf = pos_t0 + sub_step_dt * d_pos_tf
208
- joint_positions = (
209
- pos_tf[3:]
210
- if integrator_type is IntegratorType.EulerSemiImplicitManifold
211
- else pos_tf[7:]
212
- )
213
- base_quaternion = (
214
- jnp.zeros_like(x_t0.base_quaternion)
215
- if integrator_type is IntegratorType.EulerSemiImplicitManifold
216
- else pos_tf[3:7]
217
- )
218
-
219
- # ---------------------------------
220
- # 4. Integrate the remaining state
221
- # ---------------------------------
222
-
223
- # Integrate the derivative of the tangential material deformation
224
- m = x_t0.soft_contacts.tangential_deformation
225
- ṁ = dxdt_t0.soft_contacts.tangential_deformation
226
- tangential_deformation_tf = m + sub_step_dt * ṁ
227
-
228
- # Pack the new state into an ODEState object
229
- x_tf = ODEState(
230
- physics_model=PhysicsModelState(
231
- base_position=pos_tf[0:3],
232
- base_quaternion=base_quaternion,
233
- joint_positions=joint_positions,
234
- base_linear_velocity=vel_tf[0:3],
235
- base_angular_velocity=vel_tf[3:6],
236
- joint_velocities=vel_tf[6:],
237
- ),
238
- soft_contacts=SoftContactsState(
239
- tangential_deformation=tangential_deformation_tf
240
- ),
241
- )
242
-
243
- # Update the time
244
- tf = t0 + sub_step_dt
245
-
246
- # Pack the carry
247
- carry = (x_tf, tf)
248
-
249
- return carry, None
250
-
251
- _integrator_registry = {
252
- IntegratorType.RungeKutta4: rk4_body_fun,
253
- IntegratorType.EulerForward: forward_euler_body_fun,
254
- IntegratorType.EulerSemiImplicit: semi_implicit_euler_body_fun,
255
- IntegratorType.EulerSemiImplicitManifold: semi_implicit_euler_body_fun,
256
- }
257
-
258
- # Get the body function for the selected integrator
259
- body_fun = _integrator_registry[integrator_type]
260
-
261
- # Integrate over the given horizon
262
- (x_tf, _), _ = jax.lax.scan(
263
- f=body_fun, init=carry_init, xs=None, length=num_sub_steps
264
- )
265
-
266
- if integrator_type is IntegratorType.EulerSemiImplicitManifold:
267
- # Indices to convert quaternions between serializations
268
- to_xyzw = jnp.array([1, 2, 3, 0])
269
- to_wxyz = jnp.array([3, 0, 1, 2])
270
-
271
- # Get the initial quaternion and the implicitly integrated angular velocity
272
- W_ω_WB_tf = x_tf.physics_model.base_angular_velocity
273
- W_Q_B_t0 = so3.SO3.from_quaternion_xyzw(
274
- x0.physics_model.base_quaternion[to_xyzw]
275
- )
276
-
277
- # Integrate the quaternion on its manifold using the implicit angular velocity,
278
- # transformed in body-fixed representation since jaxlie uses this convention
279
- B_R_W = W_Q_B_t0.inverse().as_matrix()
280
- W_Q_B_tf = W_Q_B_t0 @ so3.SO3.exp(tangent=dt * B_R_W @ W_ω_WB_tf)
281
-
282
- # Store the quaternion in the final state
283
- x_tf = x_tf.replace(
284
- physics_model=x_tf.physics_model.replace(
285
- base_quaternion=W_Q_B_tf.as_quaternion_xyzw()[to_wxyz]
286
- )
287
- )
288
-
289
- # Compute the aux dictionary at t0
290
- _, aux_t0 = dx_dt(x0, t0)
291
-
292
- return x_tf, aux_t0
293
-
294
-
295
- # ===============================
296
- # Adapter: single step -> horizon
297
- # ===============================
298
-
299
-
300
- def integrate_single_step_over_horizon(
301
- integrator_single_step: Callable[[Time, Time, State], tuple[State, dict[str, Any]]],
302
- t: TimeHorizon,
303
- x0: State,
304
- ) -> tuple[State, dict[str, Any]]:
305
- """
306
- Integrate a single-step integrator over a given horizon.
307
-
308
- Args:
309
- integrator_single_step: A single-step integrator.
310
- t: The vector of time instants of the integration horizon.
311
- x0: The initial state of the integration horizon.
312
-
313
- Returns:
314
- The final state and auxiliary data produced by the integrator.
315
- """
316
-
317
- # Initialize the carry
318
- carry_init = (x0, t)
319
-
320
- def body_fun(carry: tuple, idx: int) -> tuple[tuple, jtp.PyTree]:
321
- # Unpack the carry
322
- x_t0, horizon = carry
323
-
324
- # Get the integration interval
325
- t0 = horizon[idx]
326
- tf = horizon[idx + 1]
327
-
328
- # Perform a single-step integration of the ODE
329
- x_tf, aux_t0 = integrator_single_step(t0, tf, x_t0)
330
-
331
- # Prepare returned data
332
- out = (x_t0, aux_t0)
333
- carry = (x_tf, horizon)
334
-
335
- return carry, out
336
-
337
- # Integrate over the given horizon
338
- _, (x_horizon, aux_horizon) = jax.lax.scan(
339
- f=body_fun, init=carry_init, xs=jnp.arange(start=0, stop=len(t), dtype=int)
340
- )
341
-
342
- return x_horizon, aux_horizon
343
-
344
-
345
- # ===================================================================
346
- # Integration over horizon (same APIs of jax.experimental.ode.odeint)
347
- # ===================================================================
348
-
349
-
350
- def odeint(
351
- func,
352
- y0: State,
353
- t: TimeHorizon,
354
- *args,
355
- num_sub_steps: int = 1,
356
- return_aux: bool = False,
357
- integrator_type: IntegratorType = None,
358
- ):
359
- """
360
- Integrate a system of ODEs with a fixed-step integrator.
361
-
362
- Args:
363
- func: A function that computes the time-derivative of the state.
364
- y0: The initial state.
365
- t: The vector of time instants of the integration horizon.
366
- *args: Additional arguments to be passed to the function func.
367
- num_sub_steps: The number of sub-steps to be performed within each integration step.
368
- return_aux: Whether to return the auxiliary data produced by the integrator.
369
-
370
- Returns:
371
- The state of the system at the end of the integration horizon, and optionally
372
- the auxiliary data produced by the integrator.
373
- """
374
-
375
- # Close func over additional inputs and parameters
376
- dx_dt_closure = lambda x, ts: func(x, ts, *args)
377
-
378
- # Close one-step integration over its arguments
379
- integrator_single_step = lambda t0, tf, x0: integrator_fixed_single_step(
380
- dx_dt=dx_dt_closure,
381
- x0=x0,
382
- t0=t0,
383
- tf=tf,
384
- num_sub_steps=num_sub_steps,
385
- integrator_type=integrator_type,
386
- )
387
-
388
- # Integrate the state and compute optional auxiliary data over the horizon
389
- out, aux = integrate_single_step_over_horizon(
390
- integrator_single_step=integrator_single_step, t=t, x0=y0
391
- )
392
-
393
- return (out, aux) if return_aux else out
jaxsim/simulation/ode.py DELETED
@@ -1,290 +0,0 @@
1
- from typing import Any, Dict, Tuple
2
-
3
- import jax
4
- import jax.numpy as jnp
5
- import numpy as np
6
-
7
- import jaxsim.typing as jtp
8
- from jaxsim.physics import algos
9
- from jaxsim.physics.algos.soft_contacts import (
10
- SoftContacts,
11
- SoftContactsParams,
12
- collidable_points_pos_vel,
13
- )
14
- from jaxsim.physics.algos.terrain import FlatTerrain, Terrain
15
- from jaxsim.physics.model.physics_model import PhysicsModel
16
-
17
- from . import ode_data
18
-
19
-
20
- def compute_contact_forces(
21
- physics_model: PhysicsModel,
22
- ode_state: ode_data.ODEState,
23
- soft_contacts_params: SoftContactsParams = SoftContactsParams(),
24
- terrain: Terrain = FlatTerrain(),
25
- ) -> Tuple[jtp.Matrix, jtp.Matrix, jtp.Matrix]:
26
- """
27
- Compute the contact forces acting on the collidable points of the model.
28
-
29
- Args:
30
- physics_model: The physics model to consider.
31
- ode_state: The state of the ODE corresponding to the physics model.
32
- soft_contacts_params: The parameters of the soft contacts model.
33
- terrain: The terrain model.
34
-
35
- Returns:
36
- A tuple containing:
37
- - The contact forces expressed in the world frame acting on the model's links.
38
- - The derivative of the tangential deformation of the terrain dynamics.
39
- - The contact forces expressed in the world frame acting on the model's collidable points.
40
- """
41
-
42
- # Compute position and linear mixed velocity of all model's collidable points
43
- # collidable_points_kinematics
44
- pos_cp, vel_cp = collidable_points_pos_vel(
45
- model=physics_model,
46
- q=ode_state.physics_model.joint_positions,
47
- qd=ode_state.physics_model.joint_velocities,
48
- xfb=ode_state.physics_model.xfb(),
49
- )
50
-
51
- # Compute the forces acting on the collidable points due to contact with
52
- # the compliant ground surface. Apply vmap to process all points together.
53
- contact_forces_points, tangential_deformation_dot = jax.vmap(
54
- SoftContacts(parameters=soft_contacts_params, terrain=terrain).contact_model
55
- )(pos_cp.T, vel_cp.T, ode_state.soft_contacts.tangential_deformation.T)
56
-
57
- contact_forces_points = contact_forces_points.T
58
- tangential_deformation_dot = tangential_deformation_dot.T
59
-
60
- # Initialize the contact forces, one per body
61
- contact_forces_links = jnp.zeros_like(
62
- ode_data.ODEInput.zero(physics_model).physics_model.f_ext
63
- )
64
-
65
- # Combine the contact forces of all collidable points belonging to the same body
66
- for body_idx in set(physics_model.gc.body):
67
- body_idx = int(body_idx)
68
- contact_forces_links = contact_forces_links.at[body_idx, :].set(
69
- jnp.sum(contact_forces_points[:, physics_model.gc.body == body_idx], axis=1)
70
- )
71
-
72
- return contact_forces_links, tangential_deformation_dot, contact_forces_points.T
73
-
74
-
75
- def dx_dt(
76
- x: ode_data.ODEState,
77
- t: jtp.Float | None,
78
- physics_model: PhysicsModel,
79
- soft_contacts_params: SoftContactsParams = SoftContactsParams(),
80
- ode_input: ode_data.ODEInput | None = None,
81
- terrain: Terrain = FlatTerrain(),
82
- ) -> Tuple[ode_data.ODEState, Dict[str, Any]]:
83
- """
84
- Compute the state derivative of the ODE corresponding to the physics model.
85
-
86
- Args:
87
- x: The state of the ODE.
88
- t: The current time.
89
- physics_model: The physics model to consider.
90
- soft_contacts_params: The parameters of the soft contacts model.
91
- ode_input: The input of the ODE.
92
- terrain: The terrain model.
93
-
94
- Returns:
95
- A tuple containing:
96
- - The state derivative of the ODE.
97
- - A dictionary containing auxiliary information.
98
- """
99
-
100
- if t is not None and isinstance(t, np.ndarray) and t.size != 1:
101
- raise ValueError(t.size)
102
-
103
- # Initialize arguments
104
- ode_state = x
105
- ode_input = (
106
- ode_input
107
- if ode_input is not None
108
- else ode_data.ODEInput.zero(physics_model=physics_model)
109
- )
110
-
111
- # ======================
112
- # Compute contact forces
113
- # ======================
114
-
115
- # Initialize the collidable points contact forces
116
- contact_forces_points = None
117
-
118
- # Initialize the contact forces, one per body
119
- contact_forces_links = jnp.zeros_like(ode_input.physics_model.f_ext)
120
-
121
- # Initialize the derivative of the tangential deformation
122
- tangential_deformation_dot = jnp.zeros_like(
123
- ode_state.soft_contacts.tangential_deformation
124
- )
125
-
126
- if physics_model.gc.body.size > 0:
127
- (
128
- contact_forces_links,
129
- tangential_deformation_dot,
130
- contact_forces_points,
131
- ) = compute_contact_forces(
132
- physics_model=physics_model,
133
- soft_contacts_params=soft_contacts_params,
134
- ode_state=ode_state,
135
- terrain=terrain,
136
- )
137
-
138
- # =====================
139
- # Joint position limits
140
- # =====================
141
-
142
- if physics_model.dofs() > 0:
143
- # Get the joint position limits
144
- s_min, s_max = jnp.array(
145
- [j.position_limit for j in physics_model.description.joints_dict.values()]
146
- ).T
147
-
148
- # Get the spring/damper parameters of joint limits enforcement
149
- k_damper = jnp.array(list(physics_model._joint_limit_damper.values()))
150
-
151
- # Compute the joint torques that enforce joint limits
152
- s = ode_state.physics_model.joint_positions
153
- tau_min = jnp.where(s <= s_min, k_damper * (s_min - s), 0)
154
- tau_max = jnp.where(s >= s_max, k_damper * (s_max - s), 0)
155
- tau_limit = tau_max + tau_min
156
-
157
- else:
158
- tau_limit = jnp.zeros_like(ode_input.physics_model.tau)
159
-
160
- # ==============
161
- # Joint friction
162
- # ==============
163
-
164
- if physics_model.dofs() > 0:
165
- # Static and viscous joint friction parameters
166
- kc = jnp.array(list(physics_model._joint_friction_static.values()))
167
- kv = jnp.array(list(physics_model._joint_friction_viscous.values()))
168
-
169
- # Compute the joint friction torque
170
- tau_friction = -(
171
- jnp.diag(kc) @ jnp.sign(ode_state.physics_model.joint_positions)
172
- + jnp.diag(kv) @ ode_state.physics_model.joint_velocities
173
- )
174
-
175
- else:
176
- tau_friction = jnp.zeros_like(ode_input.physics_model.tau)
177
-
178
- # ========================
179
- # Compute forward dynamics
180
- # ========================
181
-
182
- # Compute the total forces applied to the bodies
183
- total_forces = ode_input.physics_model.f_ext + contact_forces_links
184
-
185
- # Compute the joint torques to actuate
186
- tau = ode_input.physics_model.tau + tau_friction + tau_limit
187
-
188
- # Compute forward dynamics with the ABA algorithm
189
- W_a_WB, qdd = algos.aba.aba(
190
- model=physics_model,
191
- xfb=ode_state.physics_model.xfb(),
192
- q=ode_state.physics_model.joint_positions,
193
- qd=ode_state.physics_model.joint_velocities,
194
- tau=tau,
195
- f_ext=total_forces,
196
- )
197
-
198
- # =========================================
199
- # Compute the state derivative of base link
200
- # =========================================
201
-
202
- if not physics_model.is_floating_base:
203
- W_Qd_B = jnp.zeros(4)
204
- BW_v_WB = jnp.zeros(3)
205
-
206
- else:
207
- from jaxsim.math.conv import Convert
208
- from jaxsim.math.quaternion import Quaternion
209
-
210
- W_Qd_B = Quaternion.derivative(
211
- quaternion=ode_state.physics_model.base_quaternion,
212
- omega=ode_state.physics_model.base_angular_velocity,
213
- omega_in_body_fixed=False,
214
- ).squeeze()
215
-
216
- # Compute linear component of mixed velocity
217
- BW_v_WB = Convert.velocities_threed(
218
- v_6d=jnp.hstack(
219
- [
220
- ode_state.physics_model.base_linear_velocity,
221
- ode_state.physics_model.base_angular_velocity,
222
- ]
223
- ),
224
- p=ode_state.physics_model.base_position,
225
- ).squeeze()
226
-
227
- # Derivative of xfb (floating-base state)
228
- xd_fb = jnp.hstack([W_Qd_B, BW_v_WB, W_a_WB.squeeze()]).squeeze()
229
-
230
- # =====================================
231
- # Build the full derivative of ODEState
232
- # =====================================
233
-
234
- def fix_one_dof(vector: jtp.Vector) -> jtp.Vector | None:
235
- """Fix the shape of computed quantities for models with just 1 DoF."""
236
-
237
- if vector is None:
238
- return None
239
-
240
- return jnp.array([vector]) if vector.shape == () else vector
241
-
242
- # Fill the PhysicsModelState object included in the input ODEState to store the
243
- # returned PhysicsModelState derivative
244
- physics_model_state_derivative = ode_state.physics_model.replace(
245
- joint_positions=fix_one_dof(ode_state.physics_model.joint_velocities.squeeze()),
246
- joint_velocities=fix_one_dof(qdd.squeeze()),
247
- base_quaternion=xd_fb.squeeze()[0:4],
248
- base_position=xd_fb.squeeze()[4:7],
249
- base_angular_velocity=xd_fb.squeeze()[10:13],
250
- base_linear_velocity=xd_fb.squeeze()[7:10],
251
- )
252
-
253
- # Fill the SoftContactsState object included in the input ODEState to store the
254
- # returned SoftContactsState derivative
255
- soft_contacts_state_derivative = ode_state.soft_contacts.replace(
256
- tangential_deformation=tangential_deformation_dot.squeeze(),
257
- )
258
-
259
- # We store the state derivative using the ODEState class so that the pytree
260
- # structure remains consistent, allowing to use our generic pytree integrators
261
- state_derivative = ode_data.ODEState(
262
- physics_model=physics_model_state_derivative,
263
- soft_contacts=soft_contacts_state_derivative,
264
- )
265
-
266
- # ===============================
267
- # Build auxiliary data and return
268
- # ===============================
269
-
270
- # Real ODEInput containing the real joint forces that have been actuated and
271
- # the total external forces (= original external forces + terrain + limits)
272
- ode_input_real = ode_data.ODEInput(
273
- physics_model=ode_data.PhysicsModelInput(tau=tau, f_ext=total_forces)
274
- )
275
-
276
- # Pack the inertial-fixed floating-base acceleration
277
- W_nud_WB = jnp.hstack([W_a_WB.squeeze(), qdd.squeeze()])
278
-
279
- # Build the auxiliary data
280
- aux_dict = {
281
- "model_acceleration": W_nud_WB,
282
- "ode_input": ode_input,
283
- "ode_input_real": ode_input_real,
284
- "contact_forces_links": contact_forces_links,
285
- "contact_forces_points": contact_forces_points,
286
- "tangential_deformation_dot": tangential_deformation_dot,
287
- }
288
-
289
- # Return the state derivative as a generic PyTree, and the dict with auxiliary info
290
- return state_derivative, aux_dict