-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgo2_dual_element_push_mappo.py
More file actions
3073 lines (2519 loc) · 133 KB
/
go2_dual_element_push_mappo.py
File metadata and controls
3073 lines (2519 loc) · 133 KB
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
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Go2 Dual Robot Collaborative Element Pushing MAPPO Training Script using Genesis MARL Framework V4
This script implements multi-agent PPO (MAPPO) training where two Go2 robots learn independent
policies to collaborate and push an element to a target position. Each robot has its own
network parameters following the MAPush paper specifications for multi-agent collaborative pushing.
"""
import argparse
from dataclasses import asdict, dataclass, field
import os
import threading
import time
from typing import Any, Dict, List, Tuple, Optional
from abc import ABC, abstractmethod
import genesis as gs
import gymnasium as gym
import numpy as np
import torch
from utils import inv_quat, quat_to_xyz, transform_by_quat, transform_quat_by_quat
from configs.SimulatorConfig import SimulatorConfig
from configs.RobotConfig import RobotConfig
from configs.TrainingConfig import TrainingConfig
from marl_logging import get_class_logger
from utils import gs_rand_float
from trainer_interfaces.openrl_interface import (
OpenRLTrainingConfig,
OpenRLConfig,
OpenRLAlgorithmConfig,
OpenRLPolicyConfig,
OpenRLRunnerConfig,
OpenRLTrainConfig,
OpenRLEnvConfig,
OpenRLDeviceConfig,
)
from trainer_interfaces.frozen_model_interface import FrozenModelConfig
# Import MARL framework components
from vectorized_aec_env import VectorizedAECEnv
from configs.CameraConfig import CameraConfig
# Setup logging
logger = get_class_logger("TrainingScript", "dual_go2_element_push_mappo", level="INFO")
# ========================= Helper Functions =========================
def compute_orientation_difference(quat1: torch.Tensor, quat2: torch.Tensor) -> torch.Tensor:
"""Compute angular difference between two quaternions in radians.
Args:
quat1, quat2: Quaternion tensors [N, 4] in format [w, x, y, z]
Returns:
Angular difference in radians [N], range [0, π]
"""
quat_dot = torch.abs(torch.sum(quat1 * quat2, dim=1))
quat_dot = torch.clamp(quat_dot, 0.0, 1.0)
angular_diff = 2.0 * torch.acos(quat_dot)
return angular_diff
# ========================= Configuration Classes =========================
@dataclass
class ElementConfig(ABC):
"""Base configuration for pushable elements."""
mass: float
friction: float
spawn_pos: List[float] # [x, y] position
marker_color: Tuple[float, float, float, float] = (0, 1, 0, 1) # RGBA
@abstractmethod
def validate(self) -> None:
"""Validate element configuration parameters."""
pass
def _validate_base(self) -> None:
"""Validate common element properties."""
if self.mass <= 0 or self.mass > 100:
raise ValueError(f"Element mass must be between 0 and 100 kg, got {self.mass}")
if self.friction < 0 or self.friction > 2:
raise ValueError(f"Friction coefficient must be between 0 and 2, got {self.friction}")
if len(self.spawn_pos) != 2:
raise ValueError(f"Spawn position must be 2D [x, y], got {self.spawn_pos}")
if len(self.marker_color) != 4:
raise ValueError(f"Marker color must be RGBA tuple, got {self.marker_color}")
for val in self.marker_color:
if val < 0 or val > 1:
raise ValueError(f"Color values must be between 0 and 1, got {self.marker_color}")
@dataclass
class CylinderConfig(ElementConfig):
"""Configuration for cylinder element."""
radius: float = 0.5
height: float = 0.4
def validate(self) -> None:
"""Validate cylinder configuration."""
self._validate_base()
if self.radius <= 0 or self.radius > 2:
raise ValueError(f"Cylinder radius must be between 0 and 2 meters, got {self.radius}")
if self.height <= 0 or self.height > 2:
raise ValueError(f"Cylinder height must be between 0 and 2 meters, got {self.height}")
@dataclass
class BoxConfig(ElementConfig):
"""Configuration for box element."""
size: List[float] = field(default_factory=lambda: [1.0, 1.0, 0.4]) # [length, width, height]
def validate(self) -> None:
"""Validate box configuration."""
self._validate_base()
if len(self.size) != 3:
raise ValueError(f"Box size must be 3D [length, width, height], got {self.size}")
for dim in self.size:
if dim <= 0 or dim > 3:
raise ValueError(f"Box dimensions must be between 0 and 3 meters, got {self.size}")
@dataclass
class TBlockConfig(ElementConfig):
"""Configuration for T-block element."""
horizontal_size: List[float] = field(default_factory=lambda: [1.5, 0.5, 0.5]) # [width, depth, height]
vertical_size: List[float] = field(default_factory=lambda: [0.5, 1.0, 0.5]) # [width, depth, height]
def validate(self) -> None:
"""Validate T-block configuration."""
self._validate_base()
if len(self.horizontal_size) != 3:
raise ValueError(f"Horizontal size must be 3D [width, depth, height], got {self.horizontal_size}")
if len(self.vertical_size) != 3:
raise ValueError(f"Vertical size must be 3D [width, depth, height], got {self.vertical_size}")
for dim in self.horizontal_size + self.vertical_size:
if dim <= 0 or dim > 3:
raise ValueError(f"T-block dimensions must be between 0 and 3 meters")
def create_element_config(object_type: str) -> ElementConfig:
"""Factory method to create appropriate ElementConfig based on object type.
Args:
object_type: Type of object ('cylinder', 'box', or 'tblock')
Returns:
Appropriate ElementConfig subclass instance
Raises:
ValueError: If object_type is not recognized
"""
configs = {
"cylinder": CylinderConfig(
mass=7.0,
friction=0.5,
spawn_pos=[0.0, 0.0],
radius=0.5,
height=0.4
),
"box": BoxConfig(
mass=5.0,
friction=0.5,
spawn_pos=[0.0, 0.0],
# size=[0.5, 0.5, 0.5]
size=[0.7620, 0.4674, 0.4674]
),
"tblock": TBlockConfig(
mass=5.0,
friction=0.5,
spawn_pos=[0.0, 0.0],
horizontal_size=[1.5, 0.5, 0.5],
vertical_size=[0.5, 1.0, 0.5]
)
}
if object_type not in configs:
raise ValueError(f"Unknown object type: {object_type}. Must be one of {list(configs.keys())}")
config = configs[object_type]
config.validate()
return config
@dataclass
class SimulationConfig:
"""Configuration for simulation parameters."""
episode_length_s: float = 20.0
resampling_time_s: float = 4.0
go2_frequency: float = 50.0 # Hz
def validate(self) -> None:
"""Validate simulation configuration."""
if self.episode_length_s <= 0:
raise ValueError(f"Episode length must be positive, got {self.episode_length_s}")
if self.resampling_time_s <= 0:
raise ValueError(f"Resampling time must be positive, got {self.resampling_time_s}")
if self.go2_frequency <= 0:
raise ValueError(f"Robot frequency must be positive, got {self.go2_frequency}")
@dataclass
class RobotControlConfig:
"""Configuration for robot control parameters."""
action_scale: float = 0.25
clip_actions: float = 100.0
simulate_action_latency: bool = False
action_latency: int = 0 # Number of steps to delay action application
robot_spawn_radius: float = 1.0
robot_min_separation: float = 0.5
robo_colors: List[Tuple[float, float, float, float]] = field(default_factory=lambda: [
(1, 0, 0, 1), # Red
(0, 0, 1, 1), # Blue
(0, 1, 0, 1), # Green
(1, 1, 0, 1), # Yellow
])
def validate(self) -> None:
"""Validate robot control configuration."""
if self.action_scale <= 0:
raise ValueError(f"Action scale must be positive, got {self.action_scale}")
if self.clip_actions <= 0:
raise ValueError(f"Action clipping must be positive, got {self.clip_actions}")
if self.action_latency < 0:
raise ValueError(f"Action latency must be non-negative, got {self.action_latency}")
if self.robot_spawn_radius <= 0:
raise ValueError(f"Robot spawn radius must be positive, got {self.robot_spawn_radius}")
if self.robot_min_separation <= 0:
raise ValueError(f"Minimum robot separation must be positive, got {self.robot_min_separation}")
@dataclass
class TaskConfig:
"""Configuration for task-specific parameters."""
goal_distance: float = 2.0
goal_tolerance: float = 0.3 # Position tolerance (meters)
orientation_tolerance: float = 0.26 # Orientation tolerance (~15 degrees in radians)
far_from_goal_tolerance:float = 10.0
goal_height: float = 0.1
goal_marker_size: float = 0.1
def validate(self) -> None:
"""Validate task configuration."""
if self.goal_distance <= 0:
raise ValueError(f"Goal distance must be positive, got {self.goal_distance}")
if self.goal_tolerance <= 0:
raise ValueError(f"Goal tolerance must be positive, got {self.goal_tolerance}")
if self.orientation_tolerance <= 0:
raise ValueError(f"Orientation tolerance must be positive, got {self.orientation_tolerance}")
if self.goal_height < 0:
raise ValueError(f"Goal height must be non-negative, got {self.goal_height}")
if self.goal_marker_size <= 0:
raise ValueError(f"Goal marker size must be positive, got {self.goal_marker_size}")
@dataclass
class ObservationConfig:
"""Configuration for observation space."""
num_obs: int = 23 # 5D proprioceptive + 8D positions + 6D orientations + 3D action + 1D id
obs_scales: Dict[str, float] = field(default_factory=lambda: {
"lin_vel": 2.0,
"ang_vel": 0.25,
"dof_pos": 1.0,
"dof_vel": 0.05,
"height_measurements": 5.0,
})
def validate(self) -> None:
"""Validate observation configuration."""
if self.num_obs <= 0:
raise ValueError(f"Number of observations must be positive, got {self.num_obs}")
@dataclass
class RewardConfig:
"""Configuration for reward scales."""
# MAPush reward scales
target_reward_scale: float = 0.00325
approach_reward_scale: float = 0.00075
push_reward_scale: float = 0.0015
ocb_reward_scale: float = 0.004
orientation_reward_scale: float = 0.005
reach_target_reward_scale: float = 10.0
too_far_punishment_scale: float = -5.0
exception_punishment_scale: float = -0.5
# Object-specific collision scales
collision_scale_cylinder: float = -0.0015
collision_scale_box: float = -0.0005
# collision_scale_box: float = -0.005
collision_scale_tblock: float = -0.0025
def validate(self) -> None:
"""Validate reward configuration."""
# Positive rewards should be positive
if self.target_reward_scale < 0:
raise ValueError(f"Target reward scale should be positive, got {self.target_reward_scale}")
if self.approach_reward_scale < 0:
raise ValueError(f"Approach reward scale should be positive, got {self.approach_reward_scale}")
if self.push_reward_scale < 0:
raise ValueError(f"Push reward scale should be positive, got {self.push_reward_scale}")
if self.ocb_reward_scale < 0:
raise ValueError(f"OCB reward scale should be positive, got {self.ocb_reward_scale}")
if self.reach_target_reward_scale < 0:
raise ValueError(f"Reach target reward scale should be positive, got {self.reach_target_reward_scale}")
# Negative rewards should be negative
if self.collision_scale_cylinder > 0:
raise ValueError(f"Collision punishment scale should be negative, got {self.collision_scale_cylinder}")
if self.exception_punishment_scale > 0:
raise ValueError(f"Exception punishment scale should be negative, got {self.exception_punishment_scale}")
@dataclass
class CommandConfig:
"""Configuration for command ranges."""
num_commands: int = 3
lin_vel_x_range: List[float] = field(default_factory=lambda: [-0.8, 2.5])
lin_vel_y_range: List[float] = field(default_factory=lambda: [-0.8, 0.8])
ang_vel_range: List[float] = field(default_factory=lambda: [-0.9, 0.9])
def validate(self) -> None:
"""Validate command configuration."""
if self.num_commands <= 0:
raise ValueError(f"Number of commands must be positive, got {self.num_commands}")
if len(self.lin_vel_x_range) != 2:
raise ValueError(f"Linear velocity X range must have 2 values, got {self.lin_vel_x_range}")
if len(self.lin_vel_y_range) != 2:
raise ValueError(f"Linear velocity Y range must have 2 values, got {self.lin_vel_y_range}")
if len(self.ang_vel_range) != 2:
raise ValueError(f"Angular velocity range must have 2 values, got {self.ang_vel_range}")
@dataclass
class MAPushConfig:
"""Master configuration class for MAPPO dual robot push training."""
simulation: SimulationConfig = field(default_factory=SimulationConfig)
robot_control: RobotControlConfig = field(default_factory=RobotControlConfig)
task: TaskConfig = field(default_factory=TaskConfig)
observation: ObservationConfig = field(default_factory=ObservationConfig)
reward: RewardConfig = field(default_factory=RewardConfig)
command: CommandConfig = field(default_factory=CommandConfig)
element: Optional[ElementConfig] = None
def set_element(self, object_type: str) -> None:
"""Set element configuration based on object type.
Args:
object_type: Type of object ('cylinder', 'box', or 'tblock')
"""
self.element = create_element_config(object_type)
def validate(self) -> None:
"""Validate all configuration components."""
self.simulation.validate()
self.robot_control.validate()
self.task.validate()
self.observation.validate()
self.reward.validate()
self.command.validate()
if self.element is not None:
self.element.validate()
else:
raise ValueError("Element configuration not set. Call set_element() first.")
def to_legacy_dicts(self) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
"""Convert to legacy dictionary format for backward compatibility.
Returns:
Tuple of (env_cfg, obs_cfg, reward_cfg, command_cfg) dictionaries
"""
# Build env_cfg with all the original fields
env_cfg = {
"episode_length_s": self.simulation.episode_length_s,
"go2_frequency": self.simulation.go2_frequency,
"resampling_time_s": self.simulation.resampling_time_s,
"action_scale": self.robot_control.action_scale,
"simulate_action_latency": self.robot_control.simulate_action_latency,
"action_latency": self.robot_control.action_latency,
"clip_actions": self.robot_control.clip_actions,
"goal_distance": self.task.goal_distance,
"goal_tolerance": self.task.goal_tolerance,
"orientation_tolerance": self.task.orientation_tolerance,
"far_from_goal_tolerance": self.task.far_from_goal_tolerance,
"goal_height": self.task.goal_height,
"goal_marker_size": self.task.goal_marker_size,
"robot_spawn_radius": self.robot_control.robot_spawn_radius,
"robot_min_separation": self.robot_control.robot_min_separation,
"robo_colors": self.robot_control.robo_colors,
}
# Add element-specific fields
if self.element:
env_cfg["element_spawn_pos"] = self.element.spawn_pos
env_cfg["element_marker_color"] = self.element.marker_color
env_cfg["element_friction"] = self.element.friction
if isinstance(self.element, CylinderConfig):
env_cfg["cylinder_radius"] = self.element.radius
env_cfg["cylinder_height"] = self.element.height
env_cfg["element_mass"] = self.element.mass
elif isinstance(self.element, BoxConfig):
env_cfg["box_size"] = self.element.size
env_cfg["element_mass"] = self.element.mass
elif isinstance(self.element, TBlockConfig):
env_cfg["tblock_horizontal_size"] = self.element.horizontal_size
env_cfg["tblock_vertical_size"] = self.element.vertical_size
env_cfg["tblock_mass"] = self.element.mass
# Build other configs
obs_cfg = {
"num_obs": self.observation.num_obs,
"obs_scales": self.observation.obs_scales
}
reward_cfg = {
"target_reward_scale": self.reward.target_reward_scale,
"approach_reward_scale": self.reward.approach_reward_scale,
"push_reward_scale": self.reward.push_reward_scale,
"ocb_reward_scale": self.reward.ocb_reward_scale,
"orientation_reward_scale": self.reward.orientation_reward_scale,
"reach_target_reward_scale": self.reward.reach_target_reward_scale,
"too_far_punishment_scale" : self.reward.too_far_punishment_scale,
"exception_punishment_scale": self.reward.exception_punishment_scale,
"collision_scale_cylinder": self.reward.collision_scale_cylinder,
"collision_scale_box": self.reward.collision_scale_box,
"collision_scale_tblock": self.reward.collision_scale_tblock,
}
command_cfg = {
"num_commands": self.command.num_commands,
"lin_vel_x_range": self.command.lin_vel_x_range,
"lin_vel_y_range": self.command.lin_vel_y_range,
"ang_vel_range": self.command.ang_vel_range,
}
return env_cfg, obs_cfg, reward_cfg, command_cfg
# ========================= End Configuration Classes =========================
# Initialize configuration system
def get_config(object_type: str = "cylinder") -> tuple:
"""Get configuration for the specified object type.
Args:
object_type: Type of object ('cylinder', 'box', or 'tblock')
Returns:
Tuple of (env_cfg, obs_cfg, reward_cfg, command_cfg) dictionaries
"""
# Create master configuration
config = MAPushConfig()
config.set_element(object_type)
config.validate()
# Convert to legacy format for backward compatibility
env_cfg, obs_cfg, reward_cfg, command_cfg = config.to_legacy_dicts()
# Add Go2-specific configuration that's not in the new config system
env_cfg.update({
"num_actions": 3, # 3D position commands (x, y, yaw) for locomotion
"default_joint_angles": { # [rad]
"FL_hip_joint": 0.0,
"FR_hip_joint": 0.0,
"RL_hip_joint": 0.0,
"RR_hip_joint": 0.0,
"FL_thigh_joint": 0.8,
"FR_thigh_joint": 0.8,
"RL_thigh_joint": 1.0,
"RR_thigh_joint": 1.0,
"FL_calf_joint": -1.5,
"FR_calf_joint": -1.5,
"RL_calf_joint": -1.5,
"RR_calf_joint": -1.5,
},
"joint_names": [
"FR_hip_joint",
"FR_thigh_joint",
"FR_calf_joint",
"FL_hip_joint",
"FL_thigh_joint",
"FL_calf_joint",
"RR_hip_joint",
"RR_thigh_joint",
"RR_calf_joint",
"RL_hip_joint",
"RL_thigh_joint",
"RL_calf_joint",
],
"kp": 20.0,
"kd": 0.5,
"termination_if_roll_greater_than": 10, # degree
"termination_if_pitch_greater_than": 10,
})
return env_cfg, obs_cfg, reward_cfg, command_cfg
# Initialize with default configs for module-level access
env_cfg, obs_cfg, reward_cfg, command_cfg = get_config("cylinder")
def generate_tblock_mesh(horizontal_size, vertical_size, save_path="meshes/tblock_generated.obj"):
"""Generate a T-block mesh programmatically based on size configurations.
Args:
horizontal_size: [width, depth, height] of horizontal bar
vertical_size: [width, depth, height] of vertical bar
save_path: Path to save the generated mesh file
Returns:
str: Path to the generated mesh file
"""
import os
os.makedirs(os.path.dirname(save_path), exist_ok=True)
# Unpack dimensions
h_width, h_depth, h_height = horizontal_size
v_width, v_depth, v_height = vertical_size
# Calculate half dimensions for easier vertex calculation
h_hw, h_hd, h_hh = h_width/2, h_depth/2, h_height/2
v_hw, v_hd, v_hh = v_width/2, v_depth/2, v_height/2
# Generate vertices
vertices = []
# Horizontal bar vertices (8 vertices for a box)
# Bottom face
vertices.extend([
[-h_hw, -h_hd, -h_hh], # 1
[ h_hw, -h_hd, -h_hh], # 2
[ h_hw, h_hd, -h_hh], # 3
[-h_hw, h_hd, -h_hh], # 4
])
# Top face
vertices.extend([
[-h_hw, -h_hd, h_hh], # 5
[ h_hw, -h_hd, h_hh], # 6
[ h_hw, h_hd, h_hh], # 7
[-h_hw, h_hd, h_hh], # 8
])
# Vertical bar vertices (8 vertices)
# Position vertical bar on top of horizontal bar
# Bottom face (connects to horizontal bar)
y_offset = h_hd # Start from the back edge of horizontal bar
vertices.extend([
[-v_hw, y_offset, -v_hh], # 9
[ v_hw, y_offset, -v_hh], # 10
[ v_hw, y_offset, v_hh], # 11
[-v_hw, y_offset, v_hh], # 12
])
# Top face
vertices.extend([
[-v_hw, y_offset + v_depth, -v_hh], # 13
[ v_hw, y_offset + v_depth, -v_hh], # 14
[ v_hw, y_offset + v_depth, v_hh], # 15
[-v_hw, y_offset + v_depth, v_hh], # 16
])
# Define faces (using 1-indexed vertex numbers for OBJ format)
faces = []
# Horizontal bar faces
faces.extend([
[1, 2, 3, 4], # Bottom
[5, 8, 7, 6], # Top
[1, 5, 6, 2], # Front
[3, 7, 8, 4], # Back
[1, 4, 8, 5], # Left
[2, 6, 7, 3], # Right
])
# Vertical bar faces
faces.extend([
[9, 13, 14, 10], # Front
[11, 15, 16, 12], # Back
[9, 12, 16, 13], # Left
[10, 14, 15, 11], # Right
[13, 16, 15, 14], # Top
# Bottom face is inside the T-junction, so we skip it
])
# Write OBJ file
with open(save_path, 'w') as f:
f.write(f"# T-block mesh generated programmatically\n")
f.write(f"# Horizontal bar: {horizontal_size}\n")
f.write(f"# Vertical bar: {vertical_size}\n\n")
# Write vertices
for v in vertices:
f.write(f"v {v[0]:.6f} {v[1]:.6f} {v[2]:.6f}\n")
f.write("\n")
# Write faces
for face in faces:
f.write("f " + " ".join(str(i) for i in face) + "\n")
return save_path
def mapush_obs_function(robot_name: str, env: VectorizedAECEnv) -> torch.Tensor:
"""MAPush observation function for MAPPO training with orientation target.
Computes 23D observation vector for collaborative pushing task:
- Proprioceptive state (5D): base linear velocity (2D), base angular velocity (3D)
- Task positions (8D): element relative position (2D), other robot relative position (2D),
goal from robot (2D), goal from element (2D)
- Orientation information (6D): element error sin/cos (2D), robot-to-target sin/cos (2D),
robot-to-element sin/cos (2D)
- Action history (3D): Previous high-level velocity commands
- Agent identification (1D): Robot index for multi-agent distinction
Note: Projected gravity, joint positions, and joint velocities are excluded for stability.
Args:
robot_name: Name of the robot ("go2_robot_1" or "go2_robot_2")
env: VectorizedAECEnv instance
Returns:
torch.Tensor: 23D observation tensor for the robot [n_envs, 23]
"""
# Get configs from training config
training_config = env.training_configs[env.robot_2_training_name[robot_name]]
env_cfg = training_config.task_config["env_cfg"]
obs_cfg = training_config.task_config["obs_cfg"]
command_cfg = training_config.task_config["command_cfg"]
robot = env.robots[robot_name]
n_envs = env.n_envs
device = env.device
# ============================================
# PROPRIOCEPTIVE STATE (33D)
# ============================================
# Get robot orientation for frame transformations
base_quat = robot.get_orientation(format="quat")
inv_base_quat = inv_quat(base_quat)
# 1. Base angular velocity in robot frame (3D)
base_ang_vel = robot.get_ang_vel(relative_to=base_quat)
base_ang_vel_scaled = base_ang_vel * obs_cfg["obs_scales"]["ang_vel"]
# 2. Projected gravity vector in robot frame (3D)
global_gravity = torch.tensor([0.0, 0.0, -1.0], device=device, dtype=torch.float32).repeat(n_envs, 1)
projected_gravity = transform_by_quat(global_gravity, inv_base_quat)
# 3. Command velocities (3D) - from action buffer or zeros
if robot_name in env.action_buffers:
commands = env.action_buffers[robot_name].detach().clone()
else:
commands = torch.zeros((n_envs, 3), device=device, dtype=torch.float32)
# Scale unbounded actions from OpenRL to command ranges
# OpenRL's DiagGaussian outputs unbounded values, we need to map them to our command ranges
# # Apply tanh to bound actions to [-1, 1]
# bounded_commands = torch.tanh(commands)
# # Scale and shift to match command_cfg ranges
# commands = torch.zeros_like(bounded_commands)
# # Linear velocity X: map from [-1, 1] to [lin_vel_x_range[0], lin_vel_x_range[1]]
# x_min, x_max = command_cfg["lin_vel_x_range"]
# commands[:, 0] = (x_max - x_min) * (bounded_commands[:, 0] + 1) / 2 + x_min
# # Linear velocity Y: map from [-1, 1] to [lin_vel_y_range[0], lin_vel_y_range[1]]
# y_min, y_max = command_cfg["lin_vel_y_range"]
# commands[:, 1] = (y_max - y_min) * (bounded_commands[:, 1] + 1) / 2 + y_min
# # Angular velocity: map from [-1, 1] to [ang_vel_range[0], ang_vel_range[1]]
# ang_min, ang_max = command_cfg["ang_vel_range"]
# commands[:, 2] = (ang_max - ang_min) * (bounded_commands[:, 2] + 1) / 2 + ang_min
# just_reset_idx=env.episode_frame_count < 20 # First 20 frames do nothing to make the robot stablize
# commands[just_reset_idx] = 0
# Directly clamp unbounded actions from OpenRL to command ranges
# OpenRL's DiagGaussian outputs unbounded values, we clamp them directly
# Linear velocity X: clamp to [lin_vel_x_range[0], lin_vel_x_range[1]]
x_min, x_max = command_cfg["lin_vel_x_range"]
commands[:, 0] = torch.clamp(commands[:, 0], min=x_min, max=x_max)
# Linear velocity Y: clamp to [lin_vel_y_range[0], lin_vel_y_range[1]]
y_min, y_max = command_cfg["lin_vel_y_range"]
commands[:, 1] = torch.clamp(commands[:, 1], min=y_min, max=y_max)
# Angular velocity: clamp to [ang_vel_range[0], ang_vel_range[1]]
ang_min, ang_max = command_cfg["ang_vel_range"]
commands[:, 2] = torch.clamp(commands[:, 2], min=ang_min, max=ang_max)
commands_scaled = commands * torch.tensor(
[obs_cfg["obs_scales"]["lin_vel"], obs_cfg["obs_scales"]["lin_vel"], obs_cfg["obs_scales"]["ang_vel"]],
device=device, dtype=torch.float32
)
# 4. Joint positions relative to default (12D)
default_joint_pos = torch.tensor(
[env_cfg["default_joint_angles"][joint] for joint in env_cfg["joint_names"]],
device=device, dtype=torch.float32
).repeat(n_envs, 1)
if hasattr(env, 'joint_dofs_idx_locals') and robot_name in env.joint_dofs_idx_locals:
dofs_idx_local = env.joint_dofs_idx_locals[robot_name]
joint_pos = robot.get_joint_pos(joint_indices=dofs_idx_local, relative_to=default_joint_pos)
else:
# During detection phase, use all joints
joint_pos = robot.get_joint_pos(relative_to=default_joint_pos)
joint_pos_scaled = joint_pos * obs_cfg["obs_scales"]["dof_pos"]
# 5. Joint velocities (12D)
if hasattr(env, 'joint_dofs_idx_locals') and robot_name in env.joint_dofs_idx_locals:
joint_vel = robot.get_joint_vel(joint_indices=dofs_idx_local)
else:
# During detection phase, use all joints
joint_vel = robot.get_joint_vel()
joint_vel_scaled = joint_vel * obs_cfg["obs_scales"]["dof_vel"]
# 6. Previous joint actions for locomotion model (12D) - needed for locomotion cache
if hasattr(env, 'joint_action_buffers') and robot_name in env.joint_action_buffers:
prev_joint_actions = env.joint_action_buffers[robot_name]
else:
prev_joint_actions = torch.zeros((n_envs, 12), device=device, dtype=torch.float32)
# Note: Previous joint actions excluded from observation to match 47D spec (33D proprioceptive + 10D task + 3D action + 1D id)
# ============================================
# TASK-SPECIFIC OBSERVATIONS (10D)
# ============================================
# Get robot position
base_pos = robot.get_pos()
robot_xy = base_pos[:, :2]
# 7. Base linear velocity in robot frame (2D)
robot_vel = robot.get_lin_vel(relative_to=base_quat)[:, :2]
base_lin_vel_scaled = robot_vel * obs_cfg["obs_scales"]["lin_vel"]
# 8. Element relative position in robot frame (2D)
element_pos = env.element.get_pos()[:, :2]
element_direction_world = element_pos - robot_xy
element_direction_world_3d = torch.cat(
[element_direction_world, torch.zeros((n_envs, 1), device=device, dtype=torch.float32)], dim=1
)
element_direction_robot_frame = transform_by_quat(element_direction_world_3d, inv_base_quat)[:, :2]
# 9. Other robot relative position in robot frame (2D)
robot_names = list(env.robots.keys())
other_robot_names = [name for name in robot_names if name != robot_name]
if other_robot_names:
other_robot = env.robots[other_robot_names[0]]
other_robot_pos = other_robot.get_pos()[:, :2]
other_robot_direction_world = other_robot_pos - robot_xy
other_robot_direction_world_3d = torch.cat(
[other_robot_direction_world, torch.zeros((n_envs, 1), device=device, dtype=torch.float32)], dim=1
)
other_robot_direction_robot_frame = transform_by_quat(other_robot_direction_world_3d, inv_base_quat)[:, :2]
else:
other_robot_direction_robot_frame = torch.zeros((n_envs, 2), device=device, dtype=torch.float32)
# 10. Goal position from robot in robot frame (2D)
if hasattr(env, 'goal_position'):
goal_pos = env.goal_position
else:
# During detection phase, use default goal position
goal_pos = torch.tensor([[1.0, 0.0]], device=device, dtype=torch.float32).repeat(n_envs, 1)
goal_from_robot_world = goal_pos - robot_xy
goal_from_robot_world_3d = torch.cat(
[goal_from_robot_world, torch.zeros((n_envs, 1), device=device, dtype=torch.float32)], dim=1
)
goal_from_robot_frame = transform_by_quat(goal_from_robot_world_3d, inv_base_quat)[:, :2]
# 11. Goal position from element in world frame (2D)
goal_from_element = goal_pos - element_pos
# ============================================
# ORIENTATION OBSERVATIONS (6D)
# ============================================
# Get orientations
robot_quat = base_quat # Already computed above
element_quat = env.element.get_orientation(format="quat")
target_quat = env.target_element_orientation
# Extract yaw angles using existing quat_to_xyz utility
robot_yaw = quat_to_xyz(robot_quat, rpy=True, degrees=False)[:, 2] # Yaw is 3rd component
element_yaw = quat_to_xyz(element_quat, rpy=True, degrees=False)[:, 2]
target_yaw = quat_to_xyz(target_quat, rpy=True, degrees=False)[:, 2]
# 12. Element orientation error (target - current element) [2D]
element_yaw_diff = target_yaw - element_yaw
element_orientation_error = torch.stack([
torch.sin(element_yaw_diff),
torch.cos(element_yaw_diff)
], dim=1)
# 13. Robot to target element orientation [2D]
robot_to_target_diff = target_yaw - robot_yaw
robot_to_target_orientation = torch.stack([
torch.sin(robot_to_target_diff),
torch.cos(robot_to_target_diff)
], dim=1)
# 14. Robot to current element orientation [2D]
robot_to_element_diff = element_yaw - robot_yaw
robot_to_element_orientation = torch.stack([
torch.sin(robot_to_element_diff),
torch.cos(robot_to_element_diff)
], dim=1)
# ============================================
# ACTION HISTORY (3D)
# ============================================
# 12. Previous high-level action (3D velocity commands)
# Use action_buffers which contains previous actions (not cleared until after obs computation)
if robot_name in env.action_buffers:
previous_action = env.action_buffers[robot_name].detach().clone()
else:
# During detection phase or initial step, use zeros
previous_action = torch.zeros((n_envs, 3), device=device, dtype=torch.float32)
# ============================================
# AGENT IDENTIFICATION (1D)
# ============================================
# 13. Robot index for multi-agent distinction
robot_idx = env.robot_names.index(robot_name)
robot_idx_tensor = torch.full((n_envs, 1), float(robot_idx), device=device, dtype=torch.float32)
# ============================================
# COMBINE ALL OBSERVATIONS (23D total)
# ============================================
obs = torch.cat([
# Proprioceptive (5D)
base_lin_vel_scaled, # 2D
base_ang_vel_scaled, # 3D
# Task-specific positions (8D)
element_direction_robot_frame, # 2D
other_robot_direction_robot_frame, # 2D
goal_from_robot_frame, # 2D
goal_from_element, # 2D
# Orientation information (6D)
element_orientation_error, # 2D
robot_to_target_orientation, # 2D
robot_to_element_orientation, # 2D
# Action history (3D)
previous_action, # 3D
# Agent identification (1D)
robot_idx_tensor, # 1D
# For stability (excluded from final obs)
# projected_gravity, # 3D
# joint_pos_scaled, # 12D
# joint_vel_scaled, # 12D
], dim=1)
# ============================================
# CACHE LOCOMOTION INPUT (45D) for action preprocessing
# ============================================
# Build the locomotion input that will be needed later
locomotion_input = torch.cat([
base_ang_vel_scaled, # 3D (already scaled)
projected_gravity, # 3D
commands_scaled, # 3D (already scaled)
joint_pos_scaled, # 12D (already scaled)
joint_vel_scaled, # 12D (already scaled)
prev_joint_actions, # 12D
], dim=-1) # Total: 45D
# ============================================
# NaN CHECKING AND DEBUGGING
# ============================================
if torch.isnan(obs).any() or torch.isinf(obs).any() or (torch.abs(obs) > 200).any():
print(f"\n{'='*60}")
print(f"Invalid values detected in observation for {robot_name}!")
print(f"{'='*60}")
# Collect all problematic environment indices
problematic_envs = set()
# Check each component with correct indices for 47D observation
components = {
"base_lin_vel_scaled (0:2)": base_lin_vel_scaled,
"base_ang_vel_scaled (2:5)": base_ang_vel_scaled,
"element_direction_robot (5:7)": element_direction_robot_frame,
"other_robot_direction (7:9)": other_robot_direction_robot_frame,
"goal_from_robot (9:11)": goal_from_robot_frame,
"goal_from_element (11:13)": goal_from_element,
"previous_action (13:16)": previous_action,
"robot_idx (16:17)": robot_idx_tensor,
"projected_gravity (17:20)": projected_gravity,
"joint_pos_scaled (20:32)": joint_pos_scaled,
"joint_vel_scaled (32:44)": joint_vel_scaled,
# locomotion compoennets
"commands_scaled (locomotion [6:9])": commands_scaled,
"prev_joint_actions (locomotion [32:44])": prev_joint_actions,
}
for name, tensor in components.items():
if torch.isnan(tensor).any():
nan_count = torch.isnan(tensor).sum().item()
nan_envs = torch.isnan(tensor).any(dim=-1).nonzero(as_tuple=True)[0]
problematic_envs.update(nan_envs.tolist())
print(f" ❌ {name}: {nan_count} NaN values in envs {nan_envs[:5].tolist()}...")
# Show sample values
sample_idx = nan_envs[0] if len(nan_envs) > 0 else 0
print(f" Sample values: {tensor[sample_idx]}")
elif torch.isinf(tensor).any():
inf_count = torch.isinf(tensor).sum().item()
inf_envs = torch.isinf(tensor).any(dim=-1).nonzero(as_tuple=True)[0]
problematic_envs.update(inf_envs.tolist())
print(f" ⚠️ {name}: {inf_count} Inf values in envs {inf_envs[:5].tolist()}...")
# Show sample values
sample_idx = inf_envs[0] if len(inf_envs) > 0 else 0
print(f" Sample values: {tensor[sample_idx]}")
elif (torch.abs(tensor) > 200).any():
large_count = (torch.abs(tensor) > 200).sum().item()
large_envs = (torch.abs(tensor) > 200).any(dim=-1).nonzero(as_tuple=True)[0]
problematic_envs.update(large_envs.tolist())
print(f" 🔴 {name}: {large_count} values with |val| > 200 in envs {large_envs[:5].tolist()}...")
# Show sample values
sample_idx = large_envs[0] if len(large_envs) > 0 else 0
print(f" Sample values: {tensor[sample_idx]}")
# Also show which specific values are large
large_mask = torch.abs(tensor[sample_idx]) > 200
if large_mask.any():
print(f" Large values at indices: {large_mask.nonzero(as_tuple=True)[0].tolist()}")
else:
print(f" ✓ {name}: OK")
# Additional debug info
print(f"\nAdditional debug info:")
print(f" base_quat sample: {base_quat[0]}")
print(f" base_pos sample: {robot.get_pos()[0]}")
print(f" element_pos sample: {env.element.get_pos()[0]}")
if hasattr(env, 'goal_position'):
print(f" goal_position: {env.goal_position}")
print(f"{'='*60}\n")
# Store problematic environment indices - create boolean mask for all envs
problematic_mask = torch.zeros(env.n_envs, device=env.device, dtype=torch.bool)
if problematic_envs:
problematic_mask[list(problematic_envs)] = True
print(f"⚠️ Marked {len(problematic_envs)} environments for early truncation: {list(problematic_envs)[:10]}...")
env.problematic_obs[robot_name] = problematic_mask
# Replace NaN/Inf with zeros to prevent training crash
obs = torch.nan_to_num(obs, nan=0.0, posinf=0.0, neginf=0.0)
locomotion_input = torch.nan_to_num(locomotion_input, nan=0.0, posinf=0.0, neginf=0.0)
print(f"⚠️ Replaced NaN/Inf values with zeros to continue training")
env.locomotion_input_cache[robot_name] = locomotion_input
return obs