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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791 | @struct.dataclass
class System(_Base):
"System object. Create using `System.create(path_xml)`"
link_parents: list[int] = struct.field(False)
links: Link
link_types: list[str] = struct.field(False)
link_damping: jax.Array
link_armature: jax.Array
link_spring_stiffness: jax.Array
link_spring_zeropoint: jax.Array
# simulation timestep size
dt: float = struct.field(False)
# geometries in the system
geoms: list[Geometry]
# root / base acceleration offset
gravity: jax.Array = struct.field(default_factory=lambda: jnp.array([0, 0, -9.81]))
integration_method: str = struct.field(
False, default_factory=lambda: "semi_implicit_euler"
)
mass_mat_iters: int = struct.field(False, default_factory=lambda: 0)
link_names: list[str] = struct.field(False, default_factory=lambda: [])
model_name: Optional[str] = struct.field(False, default_factory=lambda: None)
omc: list[MaxCoordOMC | None] = struct.field(True, default_factory=lambda: [])
def num_links(self) -> int:
return len(self.link_parents)
def q_size(self) -> int:
return sum([Q_WIDTHS[typ] for typ in self.link_types])
def qd_size(self) -> int:
return sum([QD_WIDTHS[typ] for typ in self.link_types])
def name_to_idx(self, name: str) -> int:
return self.link_names.index(name)
def idx_to_name(self, idx: int, allow_world: bool = False) -> str:
if allow_world and idx == -1:
return "world"
assert idx >= 0, "Worldbody index has no name."
return self.link_names[idx]
def idx_map(self, type: str) -> dict:
"type: is either `l` or `q` or `d`"
dict_int_slices = {}
def f(_, idx_map, name: str, link_idx: int):
dict_int_slices[name] = idx_map[type](link_idx)
self.scan(f, "ll", self.link_names, list(range(self.num_links())))
return dict_int_slices
def parent_name(self, name: str) -> str:
return self.idx_to_name(self.link_parents[self.name_to_idx(name)])
def add_prefix(self, prefix: str = "") -> "System":
return self.replace(link_names=[prefix + name for name in self.link_names])
def change_model_name(
self,
new_name: Optional[str] = None,
prefix: Optional[str] = None,
suffix: Optional[str] = None,
) -> "System":
if prefix is None:
prefix = ""
if suffix is None:
suffix = ""
if new_name is None:
new_name = self.model_name
name = prefix + new_name + suffix
return self.replace(model_name=name)
def change_link_name(self, old_name: str, new_name: str) -> "System":
old_idx = self.name_to_idx(old_name)
new_link_names = self.link_names.copy()
new_link_names[old_idx] = new_name
return self.replace(link_names=new_link_names)
def add_prefix_suffix(
self, prefix: Optional[str] = None, suffix: Optional[str] = None
) -> "System":
if prefix is None:
prefix = ""
if suffix is None:
suffix = ""
new_link_names = [prefix + name + suffix for name in self.link_names]
return self.replace(link_names=new_link_names)
def _replace_free_with_cor(self) -> "System":
# check that
# - all free joints connect to -1
# - all joints connecting to -1 are free joints
for i, p in enumerate(self.link_parents):
link_type = self.link_types[i]
if (p == -1 and link_type != "free") or (link_type == "free" and p != -1):
raise InvalidSystemError(
f"link={self.idx_to_name(i)}, parent="
f"{self.idx_to_name(p, allow_world=True)},"
f" joint={link_type}. Hint: Try setting `config.cor` to false."
)
def logic_replace_free_with_cor(name, olt, ola, old, ols, olz):
# by default new is equal to old
nlt, nla, nld, nls, nlz = olt, ola, old, ols, olz
# old link type == free
if olt == "free":
# cor joint is (free, p3d) stacked
nlt = "cor"
# entries of old armature are 3*ang (spherical), 3*pos (p3d)
nla = jnp.concatenate((ola, ola[3:]))
nld = jnp.concatenate((old, old[3:]))
nls = jnp.concatenate((ols, ols[3:]))
nlz = jnp.concatenate((olz, olz[4:]))
return nlt, nla, nld, nls, nlz
return _update_sys_if_replace_joint_type(self, logic_replace_free_with_cor)
def freeze(self, name: str | list[str]):
if isinstance(name, list):
sys = self
for n in name:
sys = sys.freeze(n)
return sys
def logic_freeze(link_name, olt, ola, old, ols, olz):
nlt, nla, nld, nls, nlz = olt, ola, old, ols, olz
if link_name == name:
nlt = "frozen"
nla = nld = nls = nlz = jnp.array([])
return nlt, nla, nld, nls, nlz
return _update_sys_if_replace_joint_type(self, logic_freeze)
def unfreeze(self, name: str, new_joint_type: str):
assert self.link_types[self.name_to_idx(name)] == "frozen"
assert new_joint_type != "frozen"
return self.change_joint_type(name, new_joint_type)
def change_joint_type(
self,
name: str,
new_joint_type: str,
new_arma: Optional[jax.Array] = None,
new_damp: Optional[jax.Array] = None,
new_stif: Optional[jax.Array] = None,
new_zero: Optional[jax.Array] = None,
seed: int = 1,
):
"By default damping, stiffness are set to zero."
from ring.algorithms import get_joint_model
q_size, qd_size = Q_WIDTHS[new_joint_type], QD_WIDTHS[new_joint_type]
def logic_unfreeze_to_spherical(link_name, olt, ola, old, ols, olz):
nlt, nla, nld, nls, nlz = olt, ola, old, ols, olz
if link_name == name:
nlt = new_joint_type
q_zeros = jnp.zeros((q_size))
qd_zeros = jnp.zeros((qd_size,))
nla = qd_zeros if new_arma is None else new_arma
nld = qd_zeros if new_damp is None else new_damp
nls = qd_zeros if new_stif is None else new_stif
nlz = q_zeros if new_zero is None else new_zero
# unit quaternion
if new_joint_type in ["spherical", "free", "cor"] and new_zero is None:
nlz = nlz.at[0].set(1.0)
return nlt, nla, nld, nls, nlz
sys = _update_sys_if_replace_joint_type(self, logic_unfreeze_to_spherical)
jm = get_joint_model(new_joint_type)
if jm.init_joint_params is not None:
sys = sys.from_str(sys.to_str(), seed=seed)
return sys
def findall_imus(self) -> list[str]:
return [name for name in self.link_names if name[:3] == "imu"]
def findall_segments(self) -> list[str]:
imus = self.findall_imus()
return [name for name in self.link_names if name not in imus]
def _bodies_indices_to_bodies_name(self, bodies: list[int]) -> list[str]:
return [self.idx_to_name(i) for i in bodies]
def findall_bodies_to_world(self, names: bool = False) -> list[int] | list[str]:
bodies = [i for i, p in enumerate(self.link_parents) if p == -1]
return self._bodies_indices_to_bodies_name(bodies) if names else bodies
def find_body_to_world(self, name: bool = False) -> int | str:
bodies = self.findall_bodies_to_world(names=name)
assert len(bodies) == 1
return bodies[0]
def findall_bodies_with_jointtype(
self, typ: str, names: bool = False
) -> list[int] | list[str]:
bodies = [i for i, _typ in enumerate(self.link_types) if _typ == typ]
return self._bodies_indices_to_bodies_name(bodies) if names else bodies
def scan(self, f: Callable, in_types: str, *args, reverse: bool = False):
"""Scan `f` along each link in system whilst carrying along state.
Args:
f (Callable[..., Y]): f(y: Y, *args) -> y
in_types: string specifying the type of each input arg:
'l' is an input to be split according to link ranges
'q' is an input to be split according to q ranges
'd' is an input to be split according to qd ranges
args: Arguments passed to `f`, and split to match the link.
reverse (bool, optional): If `true` from leaves to root. Defaults to False.
Returns:
ys: Stacked output y of f.
"""
return _scan_sys(self, f, in_types, *args, reverse=reverse)
def parse(self) -> "System":
"""Initial setup of system. System object does not work unless it is parsed.
Currently it does:
- some consistency checks
- populate the spatial inertia tensors
- check that all names are unique
- check that names are strings
- check that all pos_min <= pos_max (unless traced)
- order geoms in ascending order based on their parent link idx
- check that all links have the correct size of
- damping
- armature
- stiffness
- zeropoint
- check that n_links == len(sys.omc)
"""
return _parse_system(self)
def render(
self,
xs: Optional[Transform | list[Transform]] = None,
camera: Optional[str] = None,
show_pbar: bool = True,
backend: str = "mujoco",
render_every_nth: int = 1,
**scene_kwargs,
) -> list[np.ndarray]:
"""Render frames from system and trajectory of maximal coordinates `xs`.
Args:
sys (base.System): System to render.
xs (base.Transform | list[base.Transform]): Single or time-series
of maximal coordinates `xs`.
show_pbar (bool, optional): Whether or not to show a progress bar.
Defaults to True.
Returns:
list[np.ndarray]: Stacked rendered frames. Length == len(xs).
"""
return ring.rendering.render(
self, xs, camera, show_pbar, backend, render_every_nth, **scene_kwargs
)
def render_prediction(
self,
xs: Transform | list[Transform],
yhat: dict | jax.Array | np.ndarray,
# by default we don't predict the global rotation
transparent_segment_to_root: bool = True,
**kwargs,
):
"`xs` matches `sys`. `yhat` matches `sys_noimu`. `yhat` are child-to-parent."
return ring.rendering.render_prediction(
self, xs, yhat, transparent_segment_to_root, **kwargs
)
def delete_system(self, link_name: str | list[str], strict: bool = True):
"Cut subsystem starting at `link_name` (inclusive) from tree."
return ring.sys_composer.delete_subsystem(self, link_name, strict)
def make_sys_noimu(self, imu_link_names: Optional[list[str]] = None):
"Returns, e.g., imu_attachment = {'imu1': 'seg1', 'imu2': 'seg3'}"
return ring.sys_composer.make_sys_noimu(self, imu_link_names)
def inject_system(self, other_system: "System", at_body: Optional[str] = None):
"""Combine two systems into one.
Args:
sys (base.System): Large system.
sub_sys (base.System): Small system that will be included into the
large system `sys`.
at_body (Optional[str], optional): Into which body of the large system
small system will be included. Defaults to `worldbody`.
Returns:
base.System: _description_
"""
return ring.sys_composer.inject_system(self, other_system, at_body)
def morph_system(
self,
new_parents: Optional[list[int | str]] = None,
new_anchor: Optional[int | str] = None,
):
"""Re-orders the graph underlying the system. Returns a new system.
Args:
sys (base.System): System to be modified.
new_parents (list[int]): Let the i-th entry have value j. Then, after
morphing the system the system will be such that the link corresponding
to the i-th link in the old system will have as parent the link
corresponding to the j-th link in the old system.
Returns:
base.System: Modified system.
"""
return ring.sys_composer.morph_system(self, new_parents, new_anchor)
@staticmethod
def from_xml(path: str, seed: int = 1):
return ring.io.load_sys_from_xml(path, seed)
@staticmethod
def from_str(xml: str, seed: int = 1):
return ring.io.load_sys_from_str(xml, seed)
def to_str(self) -> str:
return ring.io.save_sys_to_str(self)
def to_xml(self, path: str) -> None:
ring.io.save_sys_to_xml(self, path)
@classmethod
def create(cls, path_or_str: str, seed: int = 1) -> "System":
path = Path(path_or_str).with_suffix(".xml")
exists = False
try:
exists = path.exists()
except OSError:
# file length too length
pass
if exists:
return cls.from_xml(path, seed=seed)
else:
return cls.from_str(path_or_str)
def coordinate_vector_to_q(
self,
q: jax.Array,
custom_joints: dict[str, Callable] = {},
) -> jax.Array:
"""Map a coordinate vector `q` to the minimal coordinates vector of the sys"""
# Does, e.g.
# - normalize quaternions
# - hinge joints in [-pi, pi]
q_preproc = []
def preprocess(_, __, link_type, q):
to_q = ring.algorithms.jcalc.get_joint_model(
link_type
).coordinate_vector_to_q
# function in custom_joints has priority over JointModel
if link_type in custom_joints:
to_q = custom_joints[link_type]
if to_q is None:
raise NotImplementedError(
f"Please specify the custom joint `{link_type}`"
" either using the `custom_joints` arguments or using the"
" JointModel.coordinate_vector_to_q field."
)
new_q = to_q(q)
q_preproc.append(new_q)
self.scan(preprocess, "lq", self.link_types, q)
return jnp.concatenate(q_preproc)
|