phoxal 0.7.0

Phoxal — production-oriented autonomous robot framework (engine, model, typed bus, contracts).
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
use std::collections::{BTreeMap, HashMap};

use crate::model::component::v1::capability::Capability;
use crate::model::component::v1::{CapabilityRef, Component as SourceComponent};
use crate::model::robot::v1::Robot;
use crate::model::structure::Structure;
use anyhow::{Result, bail};
use nalgebra::{Isometry3, UnitQuaternion};

use crate::spatial::frame::{extract_link_transforms, resolve_target_link};

const DEFAULT_DEPTH_FOV_RAD: f32 = std::f32::consts::FRAC_PI_2;
const DEFAULT_DEPTH_MAX_RANGE_M: f32 = 5.0;
const DEFAULT_LIDAR_FOV_RAD: f32 = std::f32::consts::TAU;
const DEFAULT_LIDAR_MAX_RANGE_M: f32 = 10.0;

#[derive(Debug, Clone)]
pub struct ResolvedSensorPose {
    pub capability: CapabilityRef,
    pub offset_xyz_m: [f32; 3],
    pub yaw_rad: f32,
    pub local_rotation: UnitQuaternion<f32>,
    pub kind: ResolvedSensorKind,
}

#[derive(Debug, Clone)]
pub enum ResolvedSensorKind {
    Range {
        field_of_view_rad: f32,
        max_range_m: f32,
    },
    Depth {
        field_of_view_rad: f32,
        max_range_m: f32,
        width_px: u32,
        height_px: u32,
    },
    Lidar {
        field_of_view_rad: f32,
        max_range_m: f32,
    },
}

pub fn resolve_sensor_poses(
    model: &Robot,
    components: &BTreeMap<String, SourceComponent>,
    structure: &Structure,
    devices: &[CapabilityRef],
) -> Result<Vec<ResolvedSensorPose>> {
    resolve_sensor_poses_in_frame(
        model,
        components,
        structure,
        devices,
        structure.root_link_name()?,
    )
}

pub fn resolve_sensor_poses_in_frame(
    model: &Robot,
    components: &BTreeMap<String, SourceComponent>,
    structure: &Structure,
    devices: &[CapabilityRef],
    target_frame: &str,
) -> Result<Vec<ResolvedSensorPose>> {
    let link_transforms = extract_link_transforms(structure)?;
    let target_to_root = link_transforms
        .get(target_frame)
        .copied()
        .ok_or_else(|| anyhow::anyhow!("missing target frame '{target_frame}' transform"))?
        .inverse();
    devices
        .iter()
        .map(|capability_ref| {
            resolve_sensor_pose_with_transforms(
                model,
                components,
                structure,
                &link_transforms,
                target_to_root,
                capability_ref,
            )
        })
        .collect()
}

pub fn resolve_capability_link_pose_in_frame(
    model: &Robot,
    components: &BTreeMap<String, SourceComponent>,
    structure: &Structure,
    capability: &CapabilityRef,
    target_frame: &str,
) -> Result<Isometry3<f64>> {
    let link_transforms = extract_link_transforms(structure)?;
    let target_to_root = link_transforms
        .get(target_frame)
        .copied()
        .ok_or_else(|| anyhow::anyhow!("missing target frame '{target_frame}' transform"))?
        .inverse();

    resolve_capability_link_pose_with_transforms(
        model,
        components,
        structure,
        &link_transforms,
        target_to_root,
        capability,
    )
}

fn resolve_sensor_pose_with_transforms(
    model: &Robot,
    components: &BTreeMap<String, SourceComponent>,
    structure: &Structure,
    link_transforms: &HashMap<String, Isometry3<f64>>,
    target_to_root: Isometry3<f64>,
    capability_ref: &CapabilityRef,
) -> Result<ResolvedSensorPose> {
    let capability = configuration_capability(model, components, capability_ref)?;
    let kind = resolved_sensor_kind(capability, capability_ref)?;
    let transform = resolve_capability_link_pose_with_transforms(
        model,
        components,
        structure,
        link_transforms,
        target_to_root,
        capability_ref,
    )?;
    let (_, _, yaw_rad) = transform.rotation.euler_angles();

    Ok(ResolvedSensorPose {
        capability: capability_ref.clone(),
        offset_xyz_m: [
            transform.translation.x as f32,
            transform.translation.y as f32,
            transform.translation.z as f32,
        ],
        yaw_rad: yaw_rad as f32,
        local_rotation: UnitQuaternion::from_quaternion(nalgebra::Quaternion::new(
            transform.rotation.w as f32,
            transform.rotation.i as f32,
            transform.rotation.j as f32,
            transform.rotation.k as f32,
        )),
        kind,
    })
}

fn resolve_capability_link_pose_with_transforms(
    model: &Robot,
    components: &BTreeMap<String, SourceComponent>,
    structure: &Structure,
    link_transforms: &HashMap<String, Isometry3<f64>>,
    target_to_root: Isometry3<f64>,
    capability_ref: &CapabilityRef,
) -> Result<Isometry3<f64>> {
    let capability = configuration_capability(model, components, capability_ref)?;
    let namespaced_target = capability.target().namespaced(&capability_ref.component_id);
    let link_id = match resolve_target_link(&namespaced_target, structure) {
        Ok(link_id) => link_id,
        Err(target_error) => {
            let Some(model_component) = model.component_instance(&capability_ref.component_id)
            else {
                return Err(target_error);
            };
            structure
                .link(&model_component.mount_link)
                .map(|link| link.name.as_str())
                .ok_or(target_error)?
        }
    };
    let transform = target_to_root
        * link_transforms
            .get(link_id)
            .copied()
            .ok_or_else(|| anyhow::anyhow!("missing transform for sensor link '{link_id}'"))?;
    Ok(transform)
}

fn configuration_capability<'a>(
    model: &'a Robot,
    components: &'a BTreeMap<String, SourceComponent>,
    capability_ref: &CapabilityRef,
) -> Result<&'a Capability> {
    let model_component = model
        .component_instance(&capability_ref.component_id)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "component instance '{}' is not defined in robot.yaml",
                capability_ref.component_id
            )
        })?;
    components
        .get(&model_component.component)
        .and_then(|component| component.capabilities.get(&capability_ref.capability_id))
        .ok_or_else(|| {
            anyhow::anyhow!(
                "capability '{}' is not defined in component.yaml",
                capability_ref
            )
        })
}

fn resolved_sensor_kind(
    capability: &Capability,
    capability_ref: &CapabilityRef,
) -> Result<ResolvedSensorKind> {
    match capability {
        Capability::Range(cfg) => Ok(ResolvedSensorKind::Range {
            field_of_view_rad: cfg.field_of_view_rad as f32,
            max_range_m: cfg.max_range_m as f32,
        }),
        Capability::Depth(cfg) => Ok(ResolvedSensorKind::Depth {
            field_of_view_rad: cfg
                .field_of_view_rad
                .unwrap_or(f64::from(DEFAULT_DEPTH_FOV_RAD)) as f32,
            max_range_m: cfg
                .max_range_m
                .unwrap_or(f64::from(DEFAULT_DEPTH_MAX_RANGE_M)) as f32,
            width_px: cfg.width_px,
            height_px: cfg.height_px,
        }),
        Capability::Lidar(cfg) => Ok(ResolvedSensorKind::Lidar {
            field_of_view_rad: cfg
                .horizontal_fov_rad
                .unwrap_or(f64::from(DEFAULT_LIDAR_FOV_RAD)) as f32,
            max_range_m: cfg
                .max_range_m
                .unwrap_or(f64::from(DEFAULT_LIDAR_MAX_RANGE_M)) as f32,
        }),
        _ => bail!(
            "capability '{}' must be a range, depth, or lidar capability",
            capability_ref
        ),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::{Path, PathBuf};

    use crate::model::component::v1::CapabilityRef;
    use crate::model::component::v1::capability::{
        Capability, Depth, Lidar, LidarOutput, Range, StructuralTarget,
    };
    use crate::model::structure::Structure;
    use anyhow::{Context, Result};

    use super::{
        DEFAULT_DEPTH_FOV_RAD, DEFAULT_DEPTH_MAX_RANGE_M, DEFAULT_LIDAR_FOV_RAD,
        DEFAULT_LIDAR_MAX_RANGE_M, ResolvedSensorKind, resolve_capability_link_pose_in_frame,
        resolve_sensor_poses_in_frame, resolved_sensor_kind,
    };

    #[test]
    fn resolve_sensor_pose_falls_back_to_model_mount_link_when_namespaced_target_absent()
    -> Result<()> {
        let bundle_root = workspace_root()
            .join("fixture")
            .join("robot")
            .join("rgbd-imu-diff-drive");
        let model = crate::model::robot::v1::Robot::read_from_dir(&bundle_root)?;
        let components = source_components(&bundle_root, &model)?;
        let structure = Structure::read_from_dir(&bundle_root)?;
        assert!(
            structure.link("front_center_tof__sensor_link").is_none(),
            "fixture should exercise the mount-link fallback"
        );

        let sensors = resolve_sensor_poses_in_frame(
            &model,
            &components,
            &structure,
            &[CapabilityRef::new("front_center_tof", "range")],
            "base_footprint",
        )?;

        assert_eq!(sensors.len(), 1);
        assert_eq!(
            sensors[0].capability,
            CapabilityRef::new("front_center_tof", "range")
        );
        assert!(sensors[0].offset_xyz_m[2] > 0.0);
        Ok(())
    }

    #[test]
    fn resolve_capability_link_pose_resolves_rgb_camera_link_in_base_footprint() -> Result<()> {
        let bundle_root = workspace_root()
            .join("fixture")
            .join("robot")
            .join("rgbd-imu-diff-drive");
        let model = crate::model::robot::v1::Robot::read_from_dir(&bundle_root)?;
        let components = source_components(&bundle_root, &model)?;
        let structure = Structure::read_from_dir(&bundle_root)?;

        let transform = resolve_capability_link_pose_in_frame(
            &model,
            &components,
            &structure,
            &CapabilityRef::new("front_camera", "rgb"),
            "base_footprint",
        )?;

        assert!(
            transform.translation.x > 0.0,
            "front camera rgb link should be forward of base_footprint: {}",
            transform.translation.x
        );
        assert!(
            transform.translation.z > 0.0,
            "front camera rgb link should be above base_footprint: {}",
            transform.translation.z
        );
        Ok(())
    }

    #[test]
    fn resolved_sensor_kind_uses_depth_and_lidar_defaults() {
        let depth = Capability::Depth(Depth {
            target: StructuralTarget::Link {
                id: "sensor_link".to_string(),
            },
            publish_rate_hz: 30.0,
            width_px: 640,
            height_px: 400,
            field_of_view_rad: None,
            min_range_m: None,
            max_range_m: None,
        });
        let lidar = Capability::Lidar(Lidar {
            target: StructuralTarget::Link {
                id: "sensor_link".to_string(),
            },
            publish_rate_hz: 10.0,
            output: LidarOutput::Ranges,
            horizontal_resolution_rad: None,
            vertical_resolution_rad: None,
            horizontal_fov_rad: None,
            vertical_fov_rad: None,
            min_range_m: None,
            max_range_m: None,
        });
        let range = Capability::Range(Range {
            target: StructuralTarget::Link {
                id: "sensor_link".to_string(),
            },
            publish_rate_hz: 20.0,
            field_of_view_rad: 0.3,
            min_range_m: 0.1,
            max_range_m: 4.0,
        });

        assert!(matches!(
            resolved_sensor_kind(&depth, &CapabilityRef::new("c", "d")).expect("depth"),
            ResolvedSensorKind::Depth {
                field_of_view_rad,
                max_range_m,
                width_px,
                height_px,
            } if (field_of_view_rad - DEFAULT_DEPTH_FOV_RAD).abs() < 1e-6
                && (max_range_m - DEFAULT_DEPTH_MAX_RANGE_M).abs() < 1e-6
                && width_px == 640
                && height_px == 400
        ));
        assert!(matches!(
            resolved_sensor_kind(&lidar, &CapabilityRef::new("c", "l")).expect("lidar"),
            ResolvedSensorKind::Lidar {
                field_of_view_rad,
                max_range_m
            } if (field_of_view_rad - DEFAULT_LIDAR_FOV_RAD).abs() < 1e-6 && (max_range_m - DEFAULT_LIDAR_MAX_RANGE_M).abs() < 1e-6
        ));
        assert!(matches!(
            resolved_sensor_kind(&range, &CapabilityRef::new("c", "r")).expect("range"),
            ResolvedSensorKind::Range {
                field_of_view_rad,
                max_range_m
            } if (field_of_view_rad - 0.3).abs() < 1e-6 && (max_range_m - 4.0).abs() < 1e-6
        ));
    }

    fn source_components(
        bundle_root: &Path,
        model: &crate::model::robot::v1::Robot,
    ) -> Result<BTreeMap<String, crate::model::component::v1::Component>> {
        let fixture_root = bundle_root
            .parent()
            .and_then(Path::parent)
            .context("fixture bundle root must live under fixture/robot")?;
        model
            .used_component_types()
            .into_iter()
            .map(|component_type| {
                let component = crate::model::component::Component::read_from_dir(
                    fixture_root.join("component").join(component_type),
                )?
                .as_v1()
                .context("fixture components must use component.yaml version v1")?
                .clone();
                Ok((component_type.to_string(), component))
            })
            .collect()
    }

    fn workspace_root() -> PathBuf {
        let manifest_dir = match std::env::var("CARGO_MANIFEST_DIR") {
            Ok(value) => PathBuf::from(value),
            Err(error) => panic!("CARGO_MANIFEST_DIR is not set: {error}"),
        };
        // phoxal sits one level below the workspace root.
        let workspace_root = match manifest_dir.parent() {
            Some(path) => path,
            None => panic!(
                "phoxal CARGO_MANIFEST_DIR must live one level below the workspace root: {}",
                manifest_dir.display()
            ),
        };
        workspace_root.to_path_buf()
    }
}