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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::Arc,
    time::Duration,
};

use arci::{
    BaseVelocity, Error as ArciError, JointTrajectoryClient, JointTrajectoryClientsContainer,
    Localization, MoveBase, Navigation, Speaker, WaitFuture,
};
use k::{nalgebra::Isometry2, Chain, Isometry3};
use openrr_planner::{
    collision::parse_colon_separated_pairs, JointPathPlannerConfig, SelfCollisionChecker,
    SelfCollisionCheckerConfig,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tracing::debug;

use crate::{
    create_collision_avoidance_client, create_collision_check_client, create_ik_solver_with_chain,
    CollisionAvoidanceClient, CollisionCheckClient, Error, IkClient, IkSolverConfig,
    IkSolverWithChain,
};

type ArcCollisionAvoidanceClient = Arc<CollisionAvoidanceClient<Arc<dyn JointTrajectoryClient>>>;
type ArcIkClient = Arc<IkClient<Arc<dyn JointTrajectoryClient>>>;
pub type ArcRobotClient =
    RobotClient<Arc<dyn Localization>, Arc<dyn MoveBase>, Arc<dyn Navigation>>;
pub type BoxRobotClient =
    RobotClient<Box<dyn Localization>, Box<dyn MoveBase>, Box<dyn Navigation>>;

type ArcJointTrajectoryClient = Arc<dyn JointTrajectoryClient>;

pub struct RobotClient<L, M, N>
where
    L: Localization,
    M: MoveBase,
    N: Navigation,
{
    full_chain_for_collision_checker: Option<Arc<Chain<f64>>>,
    raw_joint_trajectory_clients: HashMap<String, Arc<dyn JointTrajectoryClient>>,
    all_joint_trajectory_clients: HashMap<String, Arc<dyn JointTrajectoryClient>>,
    collision_avoidance_clients: HashMap<String, ArcCollisionAvoidanceClient>,
    collision_check_clients:
        HashMap<String, Arc<CollisionCheckClient<Arc<dyn JointTrajectoryClient>>>>,
    ik_clients: HashMap<String, ArcIkClient>,
    self_collision_checkers: HashMap<String, Arc<SelfCollisionChecker<f64>>>,
    ik_solvers: HashMap<String, Arc<IkSolverWithChain>>,
    speakers: HashMap<String, Arc<dyn Speaker>>,
    localization: Option<L>,
    move_base: Option<M>,
    navigation: Option<N>,
    joints_poses: HashMap<String, HashMap<String, Vec<f64>>>,
}

impl<L, M, N> RobotClient<L, M, N>
where
    L: Localization,
    M: MoveBase,
    N: Navigation,
{
    pub fn new(
        config: OpenrrClientsConfig,
        raw_joint_trajectory_clients: HashMap<String, Arc<dyn JointTrajectoryClient>>,
        speakers: HashMap<String, Arc<dyn Speaker>>,
        localization: Option<L>,
        move_base: Option<M>,
        navigation: Option<N>,
    ) -> Result<Self, Error> {
        debug!("{config:?}");

        let mut all_joint_trajectory_clients = HashMap::new();
        for (name, client) in &raw_joint_trajectory_clients {
            all_joint_trajectory_clients.insert(name.to_owned(), client.clone());
        }
        for container_config in &config.joint_trajectory_clients_container_configs {
            let mut clients = vec![];
            for name in &container_config.clients_names {
                clients.push(raw_joint_trajectory_clients[name].clone())
            }
            all_joint_trajectory_clients.insert(
                container_config.name.to_owned(),
                Arc::new(JointTrajectoryClientsContainer::new(clients)),
            );
        }

        let (
            full_chain_for_collision_checker,
            collision_avoidance_clients,
            collision_check_clients,
            ik_clients,
            self_collision_checkers,
            ik_solvers,
        ) = if let Some(urdf_full_path) = config.urdf_full_path() {
            debug!("Loading {urdf_full_path:?}");
            let full_chain_for_collision_checker = Arc::new(Chain::from_urdf_file(urdf_full_path)?);

            let collision_avoidance_clients = create_collision_avoidance_clients(
                urdf_full_path,
                &config.self_collision_check_pairs,
                &config.collision_avoidance_clients_configs,
                &all_joint_trajectory_clients,
                full_chain_for_collision_checker.clone(),
            );

            for (name, client) in &collision_avoidance_clients {
                all_joint_trajectory_clients.insert(name.to_owned(), client.clone());
            }

            let collision_check_clients = create_collision_check_clients(
                urdf_full_path,
                &config.self_collision_check_pairs,
                &config.collision_check_clients_configs,
                &all_joint_trajectory_clients,
                full_chain_for_collision_checker.clone(),
            );

            let mut self_collision_checkers = HashMap::new();

            for (name, client) in &collision_check_clients {
                self_collision_checkers.insert(name.to_owned(), client.collision_checker.clone());
                all_joint_trajectory_clients.insert(name.to_owned(), client.clone());
            }

            let mut ik_solvers = HashMap::new();
            for (k, c) in &config.ik_solvers_configs {
                ik_solvers.insert(
                    k.to_owned(),
                    Arc::new(create_ik_solver_with_chain(
                        &full_chain_for_collision_checker,
                        c,
                    )),
                );
            }

            let ik_clients = create_ik_clients(
                &config.ik_clients_configs,
                &all_joint_trajectory_clients,
                &ik_solvers,
            );

            for (name, client) in &ik_clients {
                all_joint_trajectory_clients.insert(name.to_owned(), client.clone());
            }
            (
                Some(full_chain_for_collision_checker),
                collision_avoidance_clients,
                collision_check_clients,
                ik_clients,
                self_collision_checkers,
                ik_solvers,
            )
        } else {
            (
                None,
                HashMap::new(),
                HashMap::new(),
                HashMap::new(),
                HashMap::new(),
                HashMap::new(),
            )
        };
        let mut joints_poses: HashMap<String, HashMap<String, Vec<f64>>> = HashMap::new();
        for joints_pose in &config.joints_poses {
            joints_poses
                .entry(joints_pose.client_name.clone())
                .or_default()
                .insert(
                    joints_pose.pose_name.to_owned(),
                    joints_pose.positions.to_owned(),
                );
        }
        Ok(Self {
            full_chain_for_collision_checker,
            raw_joint_trajectory_clients,
            all_joint_trajectory_clients,
            collision_avoidance_clients,
            collision_check_clients,
            ik_clients,
            self_collision_checkers,
            ik_solvers,
            speakers,
            localization,
            move_base,
            navigation,
            joints_poses,
        })
    }

    /// Set the current joint positions to the robot kinematic model.
    ///
    /// Returns Error::FullChainNotFound when self.full_chain_for_collision_checker is None.
    pub fn set_raw_clients_joint_positions_to_full_chain_for_collision_checker(
        &self,
    ) -> Result<(), Error> {
        if self.full_chain_for_collision_checker.is_none() {
            debug!("There are no full_chain_for_collision_checker");
            return Err(Error::FullChainNotFound(
                "set_raw_clients_joint_positions_to_full_chain_for_collision_checker is called"
                    .to_owned(),
            ));
        }
        for client in self.raw_joint_trajectory_clients.values() {
            let positions = client.current_joint_positions()?;
            let joint_names = client.joint_names();
            if positions.len() != joint_names.len() {
                return Err(Error::MismatchedLength(positions.len(), joint_names.len()));
            }
            for (index, joint_name) in joint_names.iter().enumerate() {
                if let Some(joint) = self
                    .full_chain_for_collision_checker
                    .as_ref()
                    .expect("full_chain_for_collision_checker not found")
                    .find(joint_name)
                {
                    joint.set_joint_position_clamped(positions[index])
                } else {
                    return Err(ArciError::NoJoint(joint_name.to_owned()).into());
                }
            }
        }
        self.full_chain_for_collision_checker
            .as_ref()
            .expect("full_chain_for_collision_checker not found")
            .update_transforms();
        Ok(())
    }

    pub fn is_raw_joint_trajectory_client(&self, name: &str) -> bool {
        self.raw_joint_trajectory_clients.contains_key(name)
    }

    pub fn is_joint_trajectory_client(&self, name: &str) -> bool {
        self.all_joint_trajectory_clients.contains_key(name)
    }

    pub fn is_collision_avoidance_client(&self, name: &str) -> bool {
        self.collision_avoidance_clients.contains_key(name)
    }

    pub fn is_collision_check_client(&self, name: &str) -> bool {
        self.collision_check_clients.contains_key(name)
    }

    pub fn is_ik_client(&self, name: &str) -> bool {
        self.ik_clients.contains_key(name)
    }

    fn joint_trajectory_client(
        &self,
        name: &str,
    ) -> Result<&Arc<dyn JointTrajectoryClient>, Error> {
        if self.is_joint_trajectory_client(name) {
            Ok(&self.all_joint_trajectory_clients[name])
        } else {
            Err(Error::NoJointTrajectoryClient(name.to_owned()))
        }
    }

    fn ik_client(&self, name: &str) -> Result<&ArcIkClient, Error> {
        if self.is_ik_client(name) {
            Ok(&self.ik_clients[name])
        } else {
            Err(Error::NoIkClient(name.to_owned()))
        }
    }

    pub fn joint_trajectory_clients(&self) -> &HashMap<String, Arc<dyn JointTrajectoryClient>> {
        &self.all_joint_trajectory_clients
    }

    pub fn self_collision_checkers(&self) -> &HashMap<String, Arc<SelfCollisionChecker<f64>>> {
        &self.self_collision_checkers
    }

    pub fn ik_solvers(&self) -> &HashMap<String, Arc<IkSolverWithChain>> {
        &self.ik_solvers
    }

    pub fn collision_avoidance_clients(&self) -> &HashMap<String, ArcCollisionAvoidanceClient> {
        &self.collision_avoidance_clients
    }

    pub fn ik_clients(&self) -> &HashMap<String, ArcIkClient> {
        &self.ik_clients
    }

    pub fn send_joint_positions(
        &self,
        name: &str,
        positions: &[f64],
        duration_sec: f64,
    ) -> Result<WaitFuture, Error> {
        if self.full_chain_for_collision_checker.is_some() {
            self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
        }
        if self.is_ik_client(name) {
            Ok(self.ik_client(name)?.client.send_joint_positions(
                positions.to_owned(),
                Duration::from_secs_f64(duration_sec),
            )?)
        } else {
            Ok(self.joint_trajectory_client(name)?.send_joint_positions(
                positions.to_owned(),
                Duration::from_secs_f64(duration_sec),
            )?)
        }
    }

    pub fn current_joint_positions(&self, name: &str) -> Result<Vec<f64>, Error> {
        if self.is_ik_client(name) {
            self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
            Ok(self.ik_client(name)?.current_joint_positions()?)
        } else {
            Ok(self
                .joint_trajectory_client(name)?
                .current_joint_positions()?)
        }
    }

    /// Returns the joint names which is handled by the joint trajectory client with `name`
    pub fn joint_names(&self, name: &str) -> Result<Vec<String>, Error> {
        Ok(self.joint_trajectory_client(name)?.joint_names())
    }

    pub fn send_joints_pose(
        &self,
        name: &str,
        pose_name: &str,
        duration_sec: f64,
    ) -> Result<WaitFuture, Error> {
        if self.joints_poses.contains_key(name) && self.joints_poses[name].contains_key(pose_name) {
            Ok(self.send_joint_positions(
                name,
                &self.joints_poses[name][pose_name],
                duration_sec,
            )?)
        } else {
            Err(Error::NoJointsPose(name.to_owned(), pose_name.to_owned()))
        }
    }

    pub fn current_end_transform(&self, name: &str) -> Result<Isometry3<f64>, Error> {
        self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
        Ok(self.ik_client(name)?.current_end_transform()?)
    }

    pub fn transform(&self, name: &str, pose: &Isometry3<f64>) -> Result<Isometry3<f64>, Error> {
        self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
        Ok(self.ik_client(name)?.transform(pose)?)
    }

    pub fn move_ik(
        &self,
        name: &str,
        target_pose: &Isometry3<f64>,
        duration_sec: f64,
    ) -> Result<WaitFuture, Error> {
        self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
        Ok(self.ik_client(name)?.move_ik(target_pose, duration_sec)?)
    }

    pub fn move_ik_with_interpolation(
        &self,
        name: &str,
        target_pose: &Isometry3<f64>,
        duration_sec: f64,
        max_resolution: f64,
        min_number_of_points: i32,
    ) -> Result<WaitFuture, Error> {
        self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
        Ok(self.ik_client(name)?.move_ik_with_interpolation(
            target_pose,
            duration_sec,
            max_resolution,
            min_number_of_points,
        )?)
    }

    pub fn send_joint_positions_with_pose_interpolation(
        &self,
        name: &str,
        positions: &[f64],
        duration_sec: f64,
        max_resolution: f64,
        min_number_of_points: i32,
    ) -> Result<WaitFuture, Error> {
        self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?;
        let target_pose = {
            let ik_client = self.ik_client(name)?;
            ik_client.set_joint_positions_clamped(positions);
            ik_client.ik_solver_with_chain.end_transform()
        };
        self.move_ik_with_interpolation(
            name,
            &target_pose,
            duration_sec,
            max_resolution,
            min_number_of_points,
        )
    }

    pub fn raw_joint_trajectory_clients_names(&self) -> Vec<String> {
        self.raw_joint_trajectory_clients
            .keys()
            .map(|k| k.to_owned())
            .collect::<Vec<String>>()
    }

    pub fn joint_trajectory_clients_names(&self) -> Vec<String> {
        self.all_joint_trajectory_clients
            .keys()
            .map(|k| k.to_owned())
            .collect::<Vec<String>>()
    }

    pub fn collision_avoidance_clients_names(&self) -> Vec<String> {
        self.collision_avoidance_clients
            .keys()
            .map(|k| k.to_owned())
            .collect::<Vec<String>>()
    }

    pub fn collision_check_clients_names(&self) -> Vec<String> {
        self.collision_check_clients
            .keys()
            .map(|k| k.to_owned())
            .collect::<Vec<String>>()
    }

    pub fn ik_clients_names(&self) -> Vec<String> {
        self.ik_clients
            .keys()
            .map(|k| k.to_owned())
            .collect::<Vec<String>>()
    }

    pub fn full_chain_for_collision_checker(&self) -> &Option<Arc<Chain<f64>>> {
        &self.full_chain_for_collision_checker
    }

    pub fn speakers(&self) -> &HashMap<String, Arc<dyn Speaker>> {
        &self.speakers
    }

    pub fn speak(&self, name: &str, message: &str) -> Result<WaitFuture, Error> {
        match self.speakers.get(name) {
            Some(speaker) => Ok(speaker.speak(message)?),
            _ => Err(anyhow::format_err!("Speaker \"{name}\" is not found.").into()),
        }
    }
}

impl<L, M, N> Localization for RobotClient<L, M, N>
where
    L: Localization,
    M: MoveBase,
    N: Navigation,
{
    fn current_pose(&self, frame_id: &str) -> Result<Isometry2<f64>, ArciError> {
        self.localization.as_ref().unwrap().current_pose(frame_id)
    }
}

impl<L, M, N> Navigation for RobotClient<L, M, N>
where
    L: Localization,
    M: MoveBase,
    N: Navigation,
{
    fn send_goal_pose(
        &self,
        goal: Isometry2<f64>,
        frame_id: &str,
        timeout: std::time::Duration,
    ) -> Result<WaitFuture, ArciError> {
        self.navigation
            .as_ref()
            .unwrap()
            .send_goal_pose(goal, frame_id, timeout)
    }

    fn cancel(&self) -> Result<(), ArciError> {
        self.navigation.as_ref().unwrap().cancel()
    }
}

impl<L, M, N> MoveBase for RobotClient<L, M, N>
where
    L: Localization,
    M: MoveBase,
    N: Navigation,
{
    fn send_velocity(&self, velocity: &BaseVelocity) -> Result<(), ArciError> {
        self.move_base.as_ref().unwrap().send_velocity(velocity)
    }

    fn current_velocity(&self) -> Result<BaseVelocity, ArciError> {
        self.move_base.as_ref().unwrap().current_velocity()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct JointTrajectoryClientsContainerConfig {
    pub name: String,
    pub clients_names: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct OpenrrClientsConfig {
    pub urdf_path: Option<String>,
    urdf_full_path: Option<PathBuf>,
    #[serde(default)]
    pub self_collision_check_pairs: Vec<String>,

    #[serde(default)]
    // https://github.com/alexcrichton/toml-rs/issues/258
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub joint_trajectory_clients_container_configs: Vec<JointTrajectoryClientsContainerConfig>,
    #[serde(default)]
    // https://github.com/alexcrichton/toml-rs/issues/258
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub collision_avoidance_clients_configs: Vec<CollisionAvoidanceClientConfig>,
    #[serde(default)]
    // https://github.com/alexcrichton/toml-rs/issues/258
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub collision_check_clients_configs: Vec<CollisionCheckClientConfig>,
    #[serde(default)]
    // https://github.com/alexcrichton/toml-rs/issues/258
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ik_clients_configs: Vec<IkClientConfig>,
    #[serde(default)]
    pub ik_solvers_configs: HashMap<String, IkSolverConfig>,

    #[serde(default)]
    // https://github.com/alexcrichton/toml-rs/issues/258
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub joints_poses: Vec<JointsPose>,
}

/// Make relative path into absolute path from base file (not base dir).
///
/// # Example
/// ```
/// use std::path::PathBuf;
/// let abs_path = openrr_client::resolve_relative_path("/home/a/base_file.toml", "../another_file.mp3").unwrap();
/// assert_eq!(abs_path, PathBuf::from("/home/a/../another_file.mp3"));
/// ```
pub fn resolve_relative_path<B: AsRef<Path>, P: AsRef<Path>>(
    base_path: B,
    path: P,
) -> Result<PathBuf, Error> {
    Ok(base_path
        .as_ref()
        .parent()
        .ok_or_else(|| Error::NoParentDirectory(base_path.as_ref().to_owned()))?
        .join(path))
}

impl OpenrrClientsConfig {
    pub fn resolve_path<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
        if let Some(urdf_path) = self.urdf_path.as_ref() {
            // TODO: pass Some(config_file_dir)
            let urdf_path = openrr_config::evaluate(urdf_path, None)?;
            self.urdf_full_path = Some(resolve_relative_path(path, urdf_path)?);
        } else {
            return Err(Error::NoUrdfPath);
        }
        Ok(())
    }

    pub fn urdf_full_path(&self) -> Option<&Path> {
        self.urdf_full_path.as_deref()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct JointsPose {
    pub pose_name: String,
    pub client_name: String,
    pub positions: Vec<f64>,
}

#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct IkClientConfig {
    pub name: String,
    pub client_name: String,
    pub solver_name: String,
}

pub fn create_ik_clients(
    configs: &[IkClientConfig],
    name_to_joint_trajectory_client: &HashMap<String, ArcJointTrajectoryClient>,
    name_to_ik_solvers: &HashMap<String, Arc<IkSolverWithChain>>,
) -> HashMap<String, Arc<IkClient<ArcJointTrajectoryClient>>> {
    let mut clients = HashMap::new();
    for config in configs {
        clients.insert(
            config.name.clone(),
            Arc::new(IkClient::new(
                name_to_joint_trajectory_client[&config.client_name].clone(),
                name_to_ik_solvers[&config.solver_name].clone(),
            )),
        );
    }
    clients
}

#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CollisionAvoidanceClientConfig {
    pub name: String,
    pub client_name: String,
    #[serde(default)]
    pub joint_path_planner_config: JointPathPlannerConfig,
}

pub fn create_collision_avoidance_clients<P: AsRef<Path>>(
    urdf_path: P,
    self_collision_check_pairs: &[String],
    configs: &[CollisionAvoidanceClientConfig],
    name_to_joint_trajectory_client: &HashMap<String, Arc<dyn JointTrajectoryClient>>,
    full_chain: Arc<k::Chain<f64>>,
) -> HashMap<String, Arc<CollisionAvoidanceClient<Arc<dyn JointTrajectoryClient>>>> {
    let mut clients = HashMap::new();
    for config in configs {
        clients.insert(
            config.name.clone(),
            Arc::new(create_collision_avoidance_client(
                &urdf_path,
                parse_colon_separated_pairs(self_collision_check_pairs).unwrap(),
                &config.joint_path_planner_config,
                name_to_joint_trajectory_client[&config.client_name].clone(),
                full_chain.clone(),
            )),
        );
    }
    clients
}

#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CollisionCheckClientConfig {
    pub name: String,
    pub client_name: String,
    #[serde(default)]
    pub self_collision_checker_config: SelfCollisionCheckerConfig,
}

pub fn create_collision_check_clients<P: AsRef<Path>>(
    urdf_path: P,
    self_collision_check_pairs: &[String],
    configs: &[CollisionCheckClientConfig],
    name_to_joint_trajectory_client: &HashMap<String, Arc<dyn JointTrajectoryClient>>,
    full_chain: Arc<k::Chain<f64>>,
) -> HashMap<String, Arc<CollisionCheckClient<Arc<dyn JointTrajectoryClient>>>> {
    let mut clients = HashMap::new();
    for config in configs {
        clients.insert(
            config.name.clone(),
            Arc::new(create_collision_check_client(
                &urdf_path,
                self_collision_check_pairs,
                &config.self_collision_checker_config,
                name_to_joint_trajectory_client[&config.client_name].clone(),
                full_chain.clone(),
            )),
        );
    }
    clients
}