dynibo 0.3.0

Tree-structured robot kinematics and dynamics with runtime-size workspace APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::path::PathBuf;

use approx::assert_relative_eq;
use dynibo::{BaseMode, BaseState, Frame, IndexedLoad, Robot, Twist, Workspace, Wrench};
use nalgebra::{DMatrix, Vector3};

fn tree_arm() -> Robot {
    Robot::from_urdf(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_tree_7.urdf"))
        .expect("tree fixture must load")
}

fn mixed_oracle_arm() -> Robot {
    Robot::from_urdf(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/oracle_mixed.urdf"))
        .expect("mixed oracle fixture must load")
}

fn deterministic_state(sample: usize, phase: f64, amplitude: f64) -> [f64; 7] {
    std::array::from_fn(|joint| {
        let argument = (sample + 1) as f64 * (joint + 3) as f64 * 0.731 + phase;
        amplitude * argument.sin()
    })
}

fn assert_slice_close(actual: &[f64], expected: &[f64], epsilon: f64) {
    assert_eq!(actual.len(), expected.len());
    for (&actual, &expected) in actual.iter().zip(expected) {
        assert_relative_eq!(actual, expected, epsilon = epsilon);
    }
}

/// Extracts the mass matrix column-wise from Newton-Euler evaluations:
/// `M e_j = RNEA(q, 0, e_j) - RNEA(q, 0, 0)`.
fn rnea_mass_matrix(robot: &Robot, q: &[f64], workspace: &mut Workspace) -> Vec<f64> {
    let joint_count = robot.joint_count();
    let zero = vec![0.0; joint_count];
    let mut bias = vec![0.0; joint_count];
    robot
        .inverse_dynamics(
            &dynibo::BaseState::fixed(),
            q,
            &zero,
            &zero,
            &[],
            workspace,
            &mut bias,
        )
        .unwrap();
    let mut mass = vec![0.0; joint_count * joint_count];
    for column in 0..joint_count {
        let mut unit_acceleration = vec![0.0; joint_count];
        unit_acceleration[column] = 1.0;
        let mut torque = vec![0.0; joint_count];
        robot
            .inverse_dynamics(
                &dynibo::BaseState::fixed(),
                q,
                &zero,
                &unit_acceleration,
                &[],
                workspace,
                &mut torque,
            )
            .unwrap();
        for row in 0..joint_count {
            mass[column * joint_count + row] = torque[row] - bias[row];
        }
    }
    mass
}

#[test]
fn mass_matrix_matches_rnea_columns_and_keeps_structural_guarantees() {
    for robot in [tree_arm(), mixed_oracle_arm()] {
        let joint_count = robot.joint_count();
        let mut workspace = robot.workspace();
        for sample in 0..16 {
            let q: Vec<f64> = (0..joint_count)
                .map(|joint| {
                    let argument = (sample + 1) as f64 * (joint + 2) as f64 * 0.531 + 0.2;
                    (0.9 + 0.1 * joint as f64) * argument.sin()
                })
                .collect();
            let mut mass = vec![f64::NAN; joint_count * joint_count];
            robot
                .mass_matrix(&dynibo::BaseState::fixed(), &q, &mut workspace, &mut mass)
                .unwrap();
            let expected = rnea_mass_matrix(&robot, &q, &mut workspace);
            assert_slice_close(&mass, &expected, 2.0e-11);

            for row in 0..joint_count {
                for column in 0..joint_count {
                    assert_relative_eq!(
                        mass[column * joint_count + row],
                        mass[row * joint_count + column],
                        epsilon = 1.0e-12
                    );
                }
            }
            for index in 0..joint_count {
                assert!(
                    mass[index * joint_count + index] > 0.0,
                    "mass matrix diagonal must be positive: sample={sample}, joint={index}"
                );
            }
            assert!(
                DMatrix::from_column_slice(joint_count, joint_count, &mass)
                    .cholesky()
                    .is_some(),
                "mass matrix must be positive definite: sample={sample}"
            );
        }
    }
}

#[test]
fn floating_mass_matrix_propagates_through_fixed_ancestors() {
    let robot = Robot::from_urdf_with_base(
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/oracle_mixed.urdf"),
        BaseMode::Floating,
    )
    .unwrap();
    let base = BaseState::new(Frame::identity(), Twist::zeros(), Twist::zeros()).unwrap();
    let q = [0.3, -0.2, 0.4];
    let generalized_count = robot.generalized_count();
    let mut mass = vec![0.0; generalized_count * generalized_count];

    robot
        .mass_matrix(&base, &q, &mut robot.workspace(), &mut mass)
        .unwrap();

    let mass = DMatrix::from_column_slice(generalized_count, generalized_count, &mass);
    assert_relative_eq!(mass, mass.transpose(), epsilon = 2.0e-12);
}

#[test]
fn deterministic_tree_jacobians_match_finite_difference() {
    let robot = tree_arm();
    let epsilon = 1.0e-7;

    for target_name in ["left_tool", "right_tool"] {
        let target = robot.link_id(target_name).unwrap();
        let mut workspace = robot.workspace();
        for sample in 0..16 {
            let q = deterministic_state(sample, 0.0, 0.8);
            let mut jacobian = [0.0; 42];
            robot
                .jacobian(
                    &dynibo::BaseState::fixed(),
                    &q,
                    target,
                    &mut workspace,
                    &mut jacobian,
                )
                .unwrap();

            for joint in 0..7 {
                let mut plus_q = q;
                let mut minus_q = q;
                plus_q[joint] += epsilon;
                minus_q[joint] -= epsilon;
                let plus = robot
                    .forward_kinematics(
                        &dynibo::BaseState::fixed(),
                        &plus_q,
                        target,
                        &mut workspace,
                    )
                    .unwrap();
                let minus = robot
                    .forward_kinematics(
                        &dynibo::BaseState::fixed(),
                        &minus_q,
                        target,
                        &mut workspace,
                    )
                    .unwrap();
                let angular =
                    (plus.rotation * minus.rotation.inverse()).scaled_axis() / (2.0 * epsilon);
                let linear = (plus.translation.vector - minus.translation.vector) / (2.0 * epsilon);
                for row in 0..3 {
                    assert_relative_eq!(jacobian[6 * joint + row], angular[row], epsilon = 3.0e-8);
                    assert_relative_eq!(
                        jacobian[6 * joint + row + 3],
                        linear[row],
                        epsilon = 3.0e-8
                    );
                }
            }
        }
    }
}

fn sample_state(joint_count: usize, sample: usize, phase: f64, amplitude: f64) -> Vec<f64> {
    (0..joint_count)
        .map(|joint| {
            let argument = (sample + 1) as f64 * (joint + 2) as f64 * 0.531 + phase;
            amplitude * (1.0 + 0.1 * joint as f64) * argument.sin()
        })
        .collect()
}

#[test]
fn velocity_product_matches_rnea_minus_gravity() {
    for robot in [tree_arm(), mixed_oracle_arm()] {
        let joint_count = robot.joint_count();
        let zero = vec![0.0; joint_count];
        let mut workspace = robot.workspace();
        for sample in 0..16 {
            let q = sample_state(joint_count, sample, 0.2, 0.9);
            let qd = sample_state(joint_count, sample, 0.9, 0.7);
            let mut velocity_product = vec![f64::NAN; robot.generalized_count()];
            robot
                .velocity_product_forces(
                    &dynibo::BaseState::fixed(),
                    &q,
                    &qd,
                    &mut workspace,
                    &mut velocity_product,
                )
                .unwrap();

            let mut gravity = vec![0.0; robot.generalized_count()];
            robot
                .gravity(
                    &dynibo::BaseState::fixed(),
                    &q,
                    &[],
                    &mut workspace,
                    &mut gravity,
                )
                .unwrap();
            let mut bias = vec![0.0; robot.generalized_count()];
            robot
                .inverse_dynamics(
                    &dynibo::BaseState::fixed(),
                    &q,
                    &qd,
                    &zero,
                    &[],
                    &mut workspace,
                    &mut bias,
                )
                .unwrap();
            let expected: Vec<f64> = bias
                .iter()
                .zip(&gravity)
                .map(|(bias, gravity)| bias - gravity)
                .collect();
            assert_slice_close(&velocity_product, &expected, 2.0e-11);

            let mut zero_product = vec![f64::NAN; robot.generalized_count()];
            robot
                .velocity_product_forces(
                    &dynibo::BaseState::fixed(),
                    &q,
                    &zero,
                    &mut workspace,
                    &mut zero_product,
                )
                .unwrap();
            assert_slice_close(
                &zero_product,
                &vec![0.0; robot.generalized_count()],
                1.0e-14,
            );
        }
    }
}

#[test]
fn jacobian_derivative_matches_zero_acceleration_and_finite_difference() {
    let epsilon = 1.0e-7;
    for (robot, target_names) in [
        (tree_arm(), &["left_tool", "right_tool"][..]),
        (mixed_oracle_arm(), &["tool"][..]),
    ] {
        let joint_count = robot.joint_count();
        for &target_name in target_names {
            let target = robot.link_id(target_name).unwrap();
            let mut workspace = robot.workspace();
            for sample in 0..8 {
                let q = sample_state(joint_count, sample, 0.3, 0.85);
                let qd = sample_state(joint_count, sample, 1.2, 0.75);
                let zero = vec![0.0; joint_count];

                let mut derivative = vec![f64::NAN; 6 * joint_count];
                robot
                    .jacobian_derivative(
                        &dynibo::BaseState::fixed(),
                        &q,
                        &qd,
                        target,
                        &mut workspace,
                        &mut derivative,
                    )
                    .unwrap();

                // J_dot qd == forward_acceleration(q, qd, 0).
                let acceleration = robot
                    .forward_acceleration_kinematics(
                        &dynibo::BaseState::fixed(),
                        &q,
                        &qd,
                        &zero,
                        target,
                        &mut workspace,
                    )
                    .unwrap();
                let contracted: Vec<f64> = (0..6)
                    .map(|row| {
                        (0..joint_count)
                            .map(|joint| derivative[6 * joint + row] * qd[joint])
                            .sum()
                    })
                    .collect();
                assert_slice_close(&contracted, acceleration.to_vector().as_slice(), 2.0e-11);

                // Central finite difference of J along qd.
                let plus_q: Vec<f64> = q.iter().zip(&qd).map(|(q, qd)| q + epsilon * qd).collect();
                let minus_q: Vec<f64> = q.iter().zip(&qd).map(|(q, qd)| q - epsilon * qd).collect();
                let mut plus = vec![0.0; 6 * joint_count];
                let mut minus = vec![0.0; 6 * joint_count];
                robot
                    .jacobian(
                        &dynibo::BaseState::fixed(),
                        &plus_q,
                        target,
                        &mut workspace,
                        &mut plus,
                    )
                    .unwrap();
                robot
                    .jacobian(
                        &dynibo::BaseState::fixed(),
                        &minus_q,
                        target,
                        &mut workspace,
                        &mut minus,
                    )
                    .unwrap();
                for index in 0..6 * joint_count {
                    assert_relative_eq!(
                        derivative[index],
                        (plus[index] - minus[index]) / (2.0 * epsilon),
                        epsilon = 1.0e-6
                    );
                }
            }
        }

        // The root link has no moving ancestor joints.
        let root = robot.link_id(robot.root_link().name()).unwrap();
        let mut workspace = robot.workspace();
        let q = sample_state(joint_count, 0, 0.3, 0.85);
        let qd = sample_state(joint_count, 0, 1.2, 0.75);
        let mut derivative = vec![f64::NAN; 6 * joint_count];
        robot
            .jacobian_derivative(
                &dynibo::BaseState::fixed(),
                &q,
                &qd,
                root,
                &mut workspace,
                &mut derivative,
            )
            .unwrap();
        assert_slice_close(&derivative, &vec![0.0; 6 * joint_count], 0.0);
    }
}

#[test]
fn deterministic_dynamics_preserve_gravity_and_load_invariants() {
    let robot = tree_arm();
    let left = robot.link_id("left_tool").unwrap();
    let right = robot.link_id("right_tool").unwrap();
    let left_load = IndexedLoad {
        link: left,
        wrench: Wrench::new(Vector3::new(0.3, -0.2, 0.4), Vector3::new(1.0, 0.5, -0.7)),
    };
    let right_load = IndexedLoad {
        link: right,
        wrench: Wrench::new(Vector3::new(-0.4, 0.1, 0.2), Vector3::new(-0.6, 0.8, 0.3)),
    };
    let zero = [0.0; 7];
    let mut workspace = robot.workspace();

    for sample in 0..32 {
        let q = deterministic_state(sample, 0.2, 0.85);
        let base = Frame::rotation(Vector3::new(
            0.2 * (sample as f64 * 0.31).sin(),
            -0.15 * (sample as f64 * 0.47).cos(),
            0.1 * (sample as f64 * 0.23).sin(),
        ));
        let base = dynibo::BaseState::fixed_at(base).unwrap();
        let mut gravity = [0.0; 7];
        let mut inverse = [0.0; 7];
        robot
            .gravity(&base, &q, &[], &mut workspace, &mut gravity)
            .unwrap();
        robot
            .inverse_dynamics(&base, &q, &zero, &zero, &[], &mut workspace, &mut inverse)
            .unwrap();
        assert_slice_close(&gravity, &inverse, 3.0e-12);

        let mut left_only = [0.0; 7];
        let mut right_only = [0.0; 7];
        let mut both = [0.0; 7];
        robot
            .gravity(&base, &q, &[left_load], &mut workspace, &mut left_only)
            .unwrap();
        robot
            .gravity(&base, &q, &[right_load], &mut workspace, &mut right_only)
            .unwrap();
        robot
            .gravity(
                &base,
                &q,
                &[left_load, right_load],
                &mut workspace,
                &mut both,
            )
            .unwrap();
        let expected: [f64; 7] =
            std::array::from_fn(|joint| left_only[joint] + right_only[joint] - gravity[joint]);
        assert_slice_close(&both, &expected, 4.0e-12);
    }
}

#[test]
fn mixed_joint_mass_matrix_is_symmetric_and_positive_on_moving_coordinates() {
    let robot = mixed_oracle_arm();
    let mut workspace = robot.workspace();
    let zero = [0.0; 3];

    for sample in 0..16 {
        let q = [
            1.4 * ((sample + 1) as f64 * 0.71).sin(),
            0.3 * ((sample + 1) as f64 * 0.37).sin(),
            2.5 * ((sample + 1) as f64 * 0.29).sin(),
        ];
        let mut bias = [0.0; 3];
        robot
            .inverse_dynamics(
                &dynibo::BaseState::fixed(),
                &q,
                &zero,
                &zero,
                &[],
                &mut workspace,
                &mut bias,
            )
            .unwrap();

        let mut mass = DMatrix::<f64>::zeros(3, 3);
        for column in 0..3 {
            let mut unit_acceleration = [0.0; 3];
            unit_acceleration[column] = 1.0;
            let mut torque = [0.0; 3];
            robot
                .inverse_dynamics(
                    &dynibo::BaseState::fixed(),
                    &q,
                    &zero,
                    &unit_acceleration,
                    &[],
                    &mut workspace,
                    &mut torque,
                )
                .unwrap();
            for row in 0..3 {
                mass[(row, column)] = torque[row] - bias[row];
            }
        }

        assert_relative_eq!(mass, mass.transpose(), epsilon = 2.0e-11);
        for direction in [[1.0, -0.4, 0.7], [-0.3, 1.2, -0.8], [0.6, 0.2, 1.4]] {
            let direction = nalgebra::DVector::from_column_slice(&direction);
            let energy = direction.dot(&(&mass * &direction));
            assert!(
                energy > 1.0e-8,
                "mass matrix is not positive on moving coordinates: sample={sample}, energy={energy}, mass={mass:?}"
            );
        }
    }
}