File size: 22,999 Bytes
c99d198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
  Useful methods shared by all scripts.
  Reference: https://github.com/google-research/google-research/tree/master/xirl
"""

import os
import pickle
import typing
from typing import Any, Dict, Optional

from absl import logging
from gymnasium.wrappers import RescaleAction
import matplotlib.pyplot as plt
from ml_collections import config_dict
import numpy as np
from sac import replay_buffer
from sac import wrappers
import torch
from torchkit import CheckpointManager
from torchkit.experiment import git_revision_hash
from xirl import common
import yaml
import robosuite as suite
from gymnasium import spaces
import gymnasium as gym
from robosuite.wrappers import GymWrapper as RoboGymWrapper
from robosuite.controllers import load_composite_controller_config
from robosuite.utils.placement_samplers import ObjectPositionSampler

from metaworld.envs import ALL_V2_ENVIRONMENTS_GOAL_OBSERVABLE as env_dict


class _StackPlacementSampler(ObjectPositionSampler):
    """Stack cube placement: red (cubeA) near robot, green (cubeB) far, low xy noise."""

    TABLE_Z = 0.8 + 0.01
    QUAT = np.array([1.0, 0.0, 0.0, 0.0])
    # Negative x = closer to robot base; positive x = farther from robot.
    CUBE_CENTERS = {
        "cubeA": np.array([-0.110, 0.0, TABLE_Z]),  # red, near robot
        "cubeB": np.array([-0.030, 0.0, TABLE_Z]),  # green, farther but still close
    }

    def __init__(self, xy_noise=0.01, **kwargs):
        super().__init__(**kwargs)
        self.xy_noise = xy_noise

    def sample(self, fixtures=None, reference=None, on_top=True):
        placed = {} if fixtures is None else dict(fixtures)
        rng = getattr(self, "rng", np.random)
        for obj in self.mujoco_objects:
            if obj.name in placed:
                continue
            center = self.CUBE_CENTERS.get(
                obj.name, np.array([0.0, 0.0, self.TABLE_Z])
            )
            pos = center.copy()
            if self.xy_noise > 0:
                pos[:2] += rng.uniform(-self.xy_noise, self.xy_noise, size=2)
            placed[obj.name] = (pos, self.QUAT.copy(), obj)
        return placed

# pylint: disable=logging-fstring-interpolation

ConfigDict = config_dict.ConfigDict
FrozenConfigDict = config_dict.FrozenConfigDict


# ========================================= #
# Experiment utils.
# ========================================= #

def setup_experiment(exp_dir, config, resume = False):
    """Initializes a pretraining or RL experiment."""
    #  If the experiment directory doesn't exist yet, creates it and dumps the
    # config dict as a yaml file and git hash as a text file.
    # If it exists already, raises a ValueError to prevent overwriting
    # unless resume is set to True.
    if os.path.exists(exp_dir):
        if not resume:
            raise ValueError(
                "Experiment already exists. Run with --resume to continue.")
        load_config_from_dir(exp_dir, config)
    else:
        os.makedirs(exp_dir)
        with open(os.path.join(exp_dir, "config.yaml"), "w") as fp:
            yaml.dump(ConfigDict.to_dict(config), fp)
        with open(os.path.join(exp_dir, "git_hash.txt"), "w") as fp:
            fp.write(git_revision_hash())

def load_config_from_dir(
    exp_dir,
    config = None,
):
    """Load experiment config."""
    with open(os.path.join(exp_dir, "config.yaml"), "r") as fp:
        cfg = yaml.load(fp, Loader=yaml.FullLoader)
    # Inplace update the config if one is provided.
    if config is not None:
        config.update(cfg)
    return ConfigDict(cfg)

def dump_config(exp_dir, config):
    """Dump config to disk."""
    # Note: No need to explicitly delete the previous config file as "w" will
    # overwrite the file if it already exists.
    with open(os.path.join(exp_dir, "config.yaml"), "w") as fp:
        yaml.dump(ConfigDict.to_dict(config), fp)

def copy_config_and_replace(
    config,
    update_dict = None,
    freeze = False,
):
    """Makes a copy of a config and optionally updates its values."""
    # Using the ConfigDict constructor leaves the `FieldReferences` untouched
    # unlike `ConfigDict.copy_and_resolve_references`.
    new_config = ConfigDict(config)
    if update_dict is not None:
        new_config.update(update_dict)
    if freeze:
        return FrozenConfigDict(new_config)
    return new_config

def load_model_checkpoint(pretrained_path, device):
    """Load a pretrained model and optionally a precomputed goal embedding."""
    config = load_config_from_dir(pretrained_path)
    model = common.get_model(config)
    model.to(device).eval()
    checkpoint_dir = os.path.join(pretrained_path, "checkpoints")
    checkpoint_manager = CheckpointManager(checkpoint_dir, model=model)
    global_step = checkpoint_manager.restore_or_initialize()
    logging.info("Restored model from checkpoint %d.", global_step)
    return config, model

def save_pickle(experiment_path, arr, name):
    """Save an array as a pickle file."""
    filename = os.path.join(experiment_path, name)
    with open(filename, "wb") as fp:
        pickle.dump(arr, fp)
    logging.info("Saved %s to %s", name, filename)

def load_pickle(pretrained_path, name):
    """Load a pickled array."""
    filename = os.path.join(pretrained_path, name)
    with open(filename, "rb") as fp:
        arr = pickle.load(fp)
    logging.info("Successfully loaded %s from %s", name, filename)
    return arr


# ========================================= #
# RL utils.
# ========================================= #

def make_env(
    env_name,
    seed,
    save_dir = None,
    add_episode_monitor = True,
    action_repeat = 1,
    frame_stack = 1,
    robots="XArm7",
    camera_heights=84,
    camera_widths=84,
    randomize_initial_state = True,
    terminate_on_success = True,
    has_renderer = False,
    render_camera = None,
    **robosuite_kwargs,
):
    """Env factory with wrapping for robosuite benchmark.

    Args:
        env_name: The name of the environment.
        seed: The RNG seed.
        save_dir: Specifiy a save directory to wrap with `VideoRecorder`.
        add_episode_monitor: Set to True to wrap with `EpisodeMonitor`.
        action_repeat: A value > 1 will wrap with `ActionRepeat`.
        frame_stack: A value > 1 will wrap with `FrameStack`.
        randomize_initial_state: If True (default), each reset() randomizes object
            positions and (if applicable) robot initialization noise. If False,
            robot init noise is disabled. Stack always uses a low-noise placement
            sampler with red cubeA near the robot and green cubeB farther away.
        terminate_on_success: If True (default), end the episode as soon as
            robosuite reports task success (e.g. cube lifted / stacked).

    Returns:
        gym.Env object.
    """
    robosuite_kwargs = dict(robosuite_kwargs)
    if env_name == "Stack":
        cube_xy_noise = 0.015 if randomize_initial_state else 0.01
        robosuite_kwargs.setdefault(
            "placement_initializer",
            _StackPlacementSampler(
                name="StackPlacementSampler",
                mujoco_objects=None,
                reference_pos=np.array([0.0, 0.0, 0.8]),
                z_offset=0.01,
                xy_noise=cube_xy_noise,
            ),
        )
    if not randomize_initial_state:
        # Disable robot joint initialization noise so reset is deterministic.
        robosuite_kwargs.setdefault(
            "initialization_noise",
            {"magnitude": 0.0, "type": "gaussian"},
        )
    elif env_name == "Stack":
        robosuite_kwargs.setdefault(
            "initialization_noise",
            {"magnitude": 0.02, "type": "gaussian"},
        )
    # ------- base robosuite env -------.
    # controller_config = load_controller_config(default_controller="OSC_POSE")
    # robosuite_kwargs["controller_configs"] = controller_config
    # env = RobosuiteGymnasiumEnv(
    #     env_name=env_name,
    #     robots=robots,
    #     control_freq=30,
    #     camera_heights=camera_heights,
    #     camera_widths=camera_widths,
    #     **robosuite_kwargs,
    # )
    env = RobosuiteGymnasiumEnv(
        env_name=env_name,
        robots=robots,
        control_freq=30,
        has_renderer=has_renderer,
        render_camera=render_camera,
        camera_heights=camera_heights,
        camera_widths=camera_widths,
        rot_eps=0.01,
        **robosuite_kwargs,
    )

    env = wrappers.RenderWrapper(env)
    env = wrappers.EnforceMaxPathLength(env)
    if terminate_on_success:
        env = wrappers.TerminateOnSuccess(env)

    if add_episode_monitor:
        env = wrappers.EpisodeMonitor(env)
    if action_repeat > 1:
        env = wrappers.ActionRepeat(env, action_repeat)
    # env = RescaleAction(env, -1.0, 1.0)
    if save_dir is not None:
        env = wrappers.VideoRecorder(env, save_dir=save_dir)
    if frame_stack > 1:
        env = wrappers.FrameStack(env, frame_stack)

    # Seed.
    env.action_space.seed(seed)
    np.random.seed(seed)

    return env

# class RobosuiteGymnasiumEnv(gym.Env):
#     metadata = {"render_modes": ["rgb_array"]}

#     def __init__(
#         self,
#         env_name,
#         robots="Panda",
#         camera_names="agentview",
#         camera_heights=84,
#         camera_widths=84,
#         **robosuite_kwargs,
#     ):
#         super().__init__()

#         # --- create raw robosuite env (very close to your example) ---
#         self._rs_env = suite.make(
#             env_name=env_name,
#             robots=robots,
#             has_renderer=False,
#             has_offscreen_renderer=True,
#             use_camera_obs=True,
#             camera_names=camera_names,
#             camera_heights=camera_heights,
#             camera_widths=camera_widths,
#             **robosuite_kwargs,
#         )

#         self._camera_names = (
#             camera_names if isinstance(camera_names, (list, tuple)) else [camera_names]
#         )

#         # --- action space from robosuite action_spec ---
#         low, high = self._rs_env.action_spec
#         low[3:6] = -0.01
#         high[3:6] = 0.01
#         self.action_space = spaces.Box(low=low, high=high, dtype=np.float32)

#         # --- observation space: use agentview image ---
#         obs = self._rs_env.reset()
#         img = self._obs_from_dict(obs)  # (H, W, C)
#         H, W, C = img.shape
#         self.observation_space = spaces.Box(
#             low=0, high=255, shape=(H, W, C), dtype=np.uint8
#         )

#         self._last_obs = img

#     def _obs_from_dict(self, obs_dict):
#         # adjust key if you want another camera
#         img = obs_dict["agentview_image"]
#         # robosuite images are usually upside-down; flip vertically if desired
#         img = img[::-1, :, :]
#         return img

#     def reset(self, *, seed=None, options=None):
#         if seed is not None:
#             # robosuite doesn’t always implement seed(), so just do numpy here
#             np.random.seed(seed)
#         obs_dict = self._rs_env.reset()
#         img = self._obs_from_dict(obs_dict)
#         self._last_obs = img
#         # gymnasium API: (obs, info)
#         return img, {}

#     def step(self, action):
#         obs_dict, reward, done, info = self._rs_env.step(action)
#         img = self._obs_from_dict(obs_dict)
#         self._last_obs = img

#         # gymnasium API: terminated / truncated
#         terminated = bool(done)
#         truncated = False  # you can refine this if you track time limits
#         return img, reward, terminated, truncated, info

#     def render(self):
#         # Let your wrappers grab the latest observation as an image
#         return self._last_obs

#     def close(self):
#         self._rs_env.close()

import gymnasium as gym
import numpy as np
from gymnasium import spaces

# import robosuite as suite
# from robosuite.controllers import load_composite_controller_config


class RobosuiteGymnasiumEnv(gym.Env):
    metadata = {"render_modes": ["rgb_array"]}

    def __init__(
        self,
        env_name,
        robots="XArm7",
        camera_names="agentview",
        camera_heights=84,
        camera_widths=84,
        rot_eps=0.01,               # <-- physical rotation constraint (per-step / per-command units)
        has_renderer=False,
        render_camera=None,
        **robosuite_kwargs,
    ):
        super().__init__()

        # Avoid duplicate kwargs if caller also passed these via robosuite_kwargs.
        robosuite_kwargs.pop("has_renderer", None)
        robosuite_kwargs.pop("render_camera", None)

        # 1) Controller config: keep policy action in [-1,1], but shrink *applied* rotation
        controller_config = load_composite_controller_config(controller="BASIC")
        controller_config["body_parts"] = {"right": controller_config["body_parts"]["right"]}

        # For OSC_POSE, action = [dx, dy, dz, dRx, dRy, dRz] (+ gripper handled separately by robosuite if present)
        # Constrain ONLY rotation outputs (indices 3:6) to [-rot_eps, rot_eps]

        arm_cfg = controller_config["body_parts"]["right"]
        assert arm_cfg["type"] == "OSC_POSE"

        arm_cfg["output_max"][3] = rot_eps
        arm_cfg["output_min"][3] = -rot_eps
        arm_cfg["output_max"][4] = rot_eps
        arm_cfg["output_min"][4] = -rot_eps
        arm_cfg["output_max"][5] = 0.1
        arm_cfg["output_min"][5] = -0.1


        # 2) Create robosuite env with controller_configs (this is where the real constraint lives)
        self._rs_env = suite.make(
            env_name=env_name,
            robots=robots,
            controller_configs=controller_config,     # <-- important
            has_renderer=has_renderer,
            render_camera=render_camera,
            has_offscreen_renderer=True,
            use_camera_obs=True,
            camera_names=camera_names,
            camera_heights=camera_heights,
            camera_widths=camera_widths,
            **robosuite_kwargs,
        )

        self._camera_names = (
            camera_names if isinstance(camera_names, (list, tuple)) else [camera_names]
        )

        # 3) Action space: DO NOT manually tighten bounds here
        low, high = self._rs_env.action_spec
        low = low.astype(np.float32)
        high = high.astype(np.float32)
        self.action_space = spaces.Box(low=low, high=high, dtype=np.float32)

        # 4) Observation space
        obs = self._rs_env.reset()
        img = self._obs_from_dict(obs)
        H, W, C = img.shape
        self.observation_space = spaces.Box(low=0, high=255, shape=(H, W, C), dtype=np.uint8)

        self._last_obs = img

    def _obs_from_dict(self, obs_dict):
        img = obs_dict["agentview_image"]
        img = img[::-1, :, :]  # flip vertically if desired
        return img

    def reset(self, *, seed=None, options=None):
        if seed is not None:
            np.random.seed(seed)
        obs_dict = self._rs_env.reset()
        img = self._obs_from_dict(obs_dict)
        self._last_obs = img
        return img, {}

    def step(self, action):
        # Safety: clip to env bounds so executed == valid (good for consistency)
        action = np.asarray(action, dtype=np.float32)
        action = np.clip(action, self.action_space.low, self.action_space.high)

        obs_dict, reward, done, info = self._rs_env.step(action)
        img = self._obs_from_dict(obs_dict)
        self._last_obs = img

        terminated = bool(done)
        truncated = False
        return img, reward, terminated, truncated, info

    def render(self):
        return self._last_obs

    def close(self):
        self._rs_env.close()

def make_env_thunk(env_name, seed, **kwargs):
    def _thunk():
        return make_env(env_name=env_name, seed=seed, **kwargs)
    return _thunk

def wrap_learned_reward(env, config):
    """Wrap the environment with a learned reward wrapper.

    Args:
        env: A `gym.Env` to wrap with a `LearnedVisualRewardWrapper` wrapper.
        config: RL config dict, must inherit from base config defined in
        `configs/rl_default.py`.

    Returns:
        gym.Env object.
    """
    pretrained_path = config.reward_wrapper.pretrained_path
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model_config, model = load_model_checkpoint(pretrained_path, device)

    kwargs = {
        "env": env,
        "model": model,
        "device": device,
        "res_hw": model_config.data_augmentation.image_size,
    }

    if config.reward_wrapper.type == "goal_classifier":
        env = wrappers.GoalClassifierLearnedVisualReward(**kwargs)

    elif config.reward_wrapper.type == "distance_to_goal":
        kwargs["goal_emb"] = load_pickle(pretrained_path, "goal_emb.pkl")
        kwargs["distance_scale"] = load_pickle(pretrained_path, "distance_scale.pkl")
        env = wrappers.DistanceToGoalLearnedVisualReward(**kwargs)

    else:
        raise ValueError(
            f"{config.reward_wrapper.type} is not a valid reward wrapper.")

    return env

def make_buffer(
    env,
    device,
    config,
):
    """Replay buffer factory.

    Args:
        env: A `gym.Env`.
        device: A `torch.device` object.
        config: RL config dict, must inherit from base config defined in
        `configs/rl_default.py`.

    Returns:
        ReplayBuffer.
    """

    kwargs = {
        "obs_shape": (config.sac.obs_dim,), #env.observation_space.shape,
        "action_shape": (config.sac.actor.action_dim,), #env.action_space.shape,
        "capacity": config.replay_buffer_capacity,
        "device": device,
    }

    pretrained_path = config.reward_wrapper.pretrained_path
    if not pretrained_path:
        return replay_buffer.ReplayBuffer(**kwargs)

    model_config, model = load_model_checkpoint(pretrained_path, device)
    kwargs["model"] = model
    kwargs["res_hw"] = model_config.data_augmentation.image_size

    if config.reward_wrapper.type == "goal_classifier":
        buffer = replay_buffer.ReplayBufferGoalClassifier(**kwargs)

    elif config.reward_wrapper.type == "distance_to_goal":
        kwargs["goal_emb"] = load_pickle(pretrained_path, "subgoals_emb.pkl") #goal_emb.pkl
        kwargs["distance_scale"] = load_pickle(pretrained_path, "distance_scale.pkl")
        kwargs["scale_factors"] = load_pickle(pretrained_path, "subgoal_scale_factors.pkl")
        buffer = replay_buffer.ReplayBufferDistanceToGoal(**kwargs)

    else:
        raise ValueError(
            f"{config.reward_wrapper.type} is not a valid reward wrapper.")

    return buffer, kwargs["goal_emb"], kwargs["scale_factors"]

# ========================================= #
# AVDC utils.
# ========================================= #

def get_paths_from_dir(dir_path):
    paths = glob.glob(os.path.join(dir_path, 'im*.jpg'))
    try:
        paths = sorted(paths, key=lambda x: int((x.split('/')[-1].split('.')[0])[3:]))
    except:
        print(paths)
    return paths

# ========================================= #
# Misc. utils.
# ========================================= #

def plot_reward(rews):
    """Plot raw and cumulative rewards over an episode."""
    _, axes = plt.subplots(1, 2, figsize=(12, 4), sharex=True)
    axes[0].plot(rews)
    axes[0].set_xlabel("Timestep")
    axes[0].set_ylabel("Reward")
    axes[1].plot(np.cumsum(rews))
    axes[1].set_xlabel("Timestep")
    axes[1].set_ylabel("Cumulative Reward")
    for ax in axes:
        ax.grid(visible=True, which="major", linestyle="-")
        ax.grid(visible=True, which="minor", linestyle="-", alpha=0.2)
    plt.minorticks_on()

def plot_distance_by_subgoal(dist_txt_path, subgoal_steps, save_dir):
    """
    Plots reward curves broken down by subgoal, handling multiple lines (episodes)
    from a single text log file.

    Args:
        dist_txt_path: Path to the text log file containing comma-separated distances.
        subgoal_steps: A list of integers representing the number of total steps for each subgoal.
        save_dir: The directory to save the generated plot.
    """
    if not os.path.exists(dist_txt_path):
        print(f"Distance log file not found at {dist_txt_path}")
        return

    try:
        all_dists = np.genfromtxt(dist_txt_path, delimiter=',')
        if all_dists.ndim == 1:
            all_dists = all_dists.reshape(1, -1)
    except Exception as e:
        print(f"Error reading file {dist_txt_path}: {e}")
        return

    num_episodes = all_dists.shape[0]
    num_subgoals = len(subgoal_steps)
    total_steps_expected = sum(subgoal_steps)

    if all_dists.shape[1] != total_steps_expected:
        print(f"Data in file has {all_dists.shape[1]} steps, but expected {total_steps_expected}.")
        print("This may be due to early termination of an episode.")
    
    num_rows = int(np.ceil(num_subgoals / 2.0))
    fig, axes = plt.subplots(num_rows, 2, figsize=(12, 5 * num_rows))
    axes = axes.flatten()

    # Create empty lists to store handles and labels for the single legend
    handles = []
    labels = []

    start_idx = 0
    for i, steps in enumerate(subgoal_steps):
        # Calculate the number of reward data points for this subgoal
        num_reward_points = steps // 3
        end_idx = start_idx + num_reward_points
        
        # Correctly slice the data for all episodes for the current subgoal
        # Note: The reward data is sparse, with one point for every 3 steps.
        subgoal_dists = all_dists[:, start_idx:min(end_idx, all_dists.shape[1])]
        
        # Get the corresponding x-axis values (0, 3, 6, ...)
        x_values = np.arange(0, steps, 3)
        
        # Ensure x and y dimensions match, handling potential partial data
        if subgoal_dists.shape[1] < len(x_values):
            x_values = x_values[:subgoal_dists.shape[1]]

        for j in range(num_episodes):
            ax = axes[i]
            # Ensure the data for this episode is the correct length
            if len(subgoal_dists[j, :]) == len(x_values):
                # We need to get handles and labels for the legend
                line, = ax.plot(x_values, subgoal_dists[j, :], label=f'Episode {j+1}')
                if i == 0:  # Only add handles and labels once to avoid duplicates
                    handles.append(line)
                    labels.append(f'Episode {j+1}')

        ax.set_title(f"Subgoal {i+1} Reward Curve")
        ax.set_xlabel("Episode Steps")
        ax.set_ylabel("Negative Distance Reward")
        ax.grid(True)
        
        # REMOVE THIS BLOCK:
        # if num_episodes > 1:
        #     ax.legend()
        
        start_idx = end_idx

    for i in range(num_subgoals, len(axes)):
        fig.delaxes(axes[i])

    # ADD THIS BLOCK:
    # Create a single legend at the bottom of the figure
    fig.legend(handles, labels, loc='lower center', ncol=num_episodes, bbox_to_anchor=(0.5, -0.05))

    plt.tight_layout()
    plt.savefig(os.path.join(save_dir, "distance_by_subgoal.png"))
    plt.close(fig)