File size: 9,719 Bytes
b62ef52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import click
import zarr
from diffusion_policy.common.replay_buffer import ReplayBuffer
from diffusion_policy.env.pusht.pusht_keypoints_env import PushTKeypointsEnv
import pygame

# --- Mixed-mode controlled collection ---
# Seed parity determines mode: even = LEFT, odd = RIGHT.
# After each saved episode, the integer mode (0=LEFT, 1=RIGHT) and the final
# coverage are appended to meta/episode_modes and meta/episode_coverages in
# the zarr, alongside the standard meta/episode_ends.
MODE_NAMES = {0: 'LEFT', 1: 'RIGHT'}
MODE_COLORS = {0: (220, 30, 30), 1: (30, 80, 220)}  # red for LEFT, blue for RIGHT
SUCCESS_THRESHOLD = 0.95  # matches PushTEnv.success_threshold

_FONT_CACHE = {}


def _font(size, bold=False):
    key = (size, bold)
    if key not in _FONT_CACHE:
        if not pygame.font.get_init():
            pygame.font.init()
        _FONT_CACHE[key] = pygame.font.SysFont(None, size, bold=bold)
    return _FONT_CACHE[key]


def draw_overlay(mode_int, seed, coverage):
    """Blit mode label + live coverage bar over the env render and flip."""
    screen = pygame.display.get_surface()
    if screen is None:
        return
    w = screen.get_width()
    color = MODE_COLORS[mode_int]
    name = MODE_NAMES[mode_int]
    pad = 6

    # Mode label: large text top-left with translucent backdrop
    mode_font = _font(56, bold=True)
    mode_surf = mode_font.render(name, True, color)
    mode_rect = mode_surf.get_rect(topleft=(10, 6))
    bg = pygame.Surface((mode_rect.width + pad * 2, mode_rect.height + pad * 2),
                        pygame.SRCALPHA)
    bg.fill((255, 255, 255, 200))
    screen.blit(bg, (mode_rect.x - pad, mode_rect.y - pad))
    screen.blit(mode_surf, mode_rect)

    # Seed number under the mode label
    seed_font = _font(20)
    seed_surf = seed_font.render(f'seed {seed}', True, (40, 40, 40))
    seed_rect = seed_surf.get_rect(topleft=(10, mode_rect.bottom + 4))
    sbg = pygame.Surface((seed_rect.width + pad * 2, seed_rect.height + pad),
                         pygame.SRCALPHA)
    sbg.fill((255, 255, 255, 180))
    screen.blit(sbg, (seed_rect.x - pad, seed_rect.y - pad // 2))
    screen.blit(seed_surf, seed_rect)

    # Coverage bar across the top-right: shows current IoU coverage out of 95%
    bar_w = 200
    bar_h = 18
    bar_x = w - bar_w - 10
    bar_y = 12
    pygame.draw.rect(screen, (255, 255, 255), (bar_x, bar_y, bar_w, bar_h))
    pygame.draw.rect(screen, (60, 60, 60), (bar_x, bar_y, bar_w, bar_h), 1)
    cov_frac = float(min(coverage, SUCCESS_THRESHOLD)) / SUCCESS_THRESHOLD
    fill_w = int(bar_w * cov_frac)
    if cov_frac < 0.6:
        bar_color = (180, 40, 40)
    elif cov_frac < 0.9:
        bar_color = (200, 150, 30)
    else:
        bar_color = (40, 170, 60)
    pygame.draw.rect(screen, bar_color, (bar_x, bar_y, fill_w, bar_h))

    cov_pct = coverage * 100.0
    cov_font = _font(18, bold=True)
    cov_surf = cov_font.render(f'IoU {cov_pct:5.1f}% / 95%', True, (20, 20, 20))
    cov_rect = cov_surf.get_rect(topright=(w - 10, bar_y + bar_h + 4))
    cbg = pygame.Surface((cov_rect.width + pad * 2, cov_rect.height + pad),
                         pygame.SRCALPHA)
    cbg.fill((255, 255, 255, 200))
    screen.blit(cbg, (cov_rect.x - pad, cov_rect.y - pad // 2))
    screen.blit(cov_surf, cov_rect)

    # Keybinding hint at the bottom
    hint_font = _font(16)
    hint_surf = hint_font.render('S save  C cancel  R retry  Q quit',
                                 True, (30, 30, 30))
    hint_rect = hint_surf.get_rect(midbottom=(w // 2, screen.get_height() - 4))
    hbg = pygame.Surface((hint_rect.width + pad * 2, hint_rect.height + pad),
                         pygame.SRCALPHA)
    hbg.fill((255, 255, 255, 200))
    screen.blit(hbg, (hint_rect.x - pad, hint_rect.y - pad // 2))
    screen.blit(hint_surf, hint_rect)

    pygame.display.flip()


def append_episode_metadata(zarr_path, mode_int, coverage):
    """Append (mode, coverage) to meta/episode_modes and meta/episode_coverages."""
    root = zarr.open(zarr_path, mode='a')
    meta = root.require_group('meta')
    if 'episode_modes' in meta:
        arr = meta['episode_modes']
        arr.resize((arr.shape[0] + 1,))
        arr[-1] = mode_int
    else:
        meta.create_dataset(
            'episode_modes',
            data=np.array([mode_int], dtype='i1'),
            chunks=(64,), dtype='i1',
        )
    if 'episode_coverages' in meta:
        arr = meta['episode_coverages']
        arr.resize((arr.shape[0] + 1,))
        arr[-1] = float(coverage)
    else:
        meta.create_dataset(
            'episode_coverages',
            data=np.array([coverage], dtype='f4'),
            chunks=(64,), dtype='f4',
        )


@click.command()
@click.option('-o', '--output', required=True)
@click.option('-rs', '--render_size', default=96, type=int)
@click.option('-hz', '--control_hz', default=10, type=int)
def main(output, render_size, control_hz):
    """
    Mixed-mode Push-T teleop with controlled init.

    Mode auto-assigned by seed parity:
        seed even = LEFT  (wrap T from upper-left side, red label)
        seed odd  = RIGHT (wrap T from lower-right side, blue label)

    Saved per episode in the zarr:
        data/{state,action,img,keypoint,n_contacts}
        meta/episode_ends           (standard DP layout)
        meta/episode_modes          (int8: 0=LEFT, 1=RIGHT)
        meta/episode_coverages      (float32: final IoU coverage, 0..1)

    Keys:
        S = save current episode now (no need to reach 95% IoU)
        C = cancel current episode and restart same seed
        R = same as C (retry)
        Q = quit (script exits; saved episodes persist)
        Space = pause
    """
    replay_buffer = ReplayBuffer.create_from_path(output, mode='a')

    kp_kwargs = PushTKeypointsEnv.genenerate_keypoint_manager_params()
    env = PushTKeypointsEnv(render_size=render_size, render_action=False, **kp_kwargs)
    agent = env.teleop_agent()
    clock = pygame.time.Clock()

    while True:
        episode = list()
        seed = replay_buffer.n_episodes
        mode_int = seed % 2
        mode_name = MODE_NAMES[mode_int]
        print(f'starting seed {seed}  mode={mode_name}', flush=True)

        # --- Controlled init: T fixed on 45-deg symmetry axis through goal,
        #     agent perturbed +/- 15 px around (327, 185).
        T_INIT_XY = np.array([185.0, 327.0])
        T_INIT_ANG = np.pi / 4
        AGENT_NOMINAL = np.array([327.0, 185.0])

        np.random.seed(seed)
        agent_xy = AGENT_NOMINAL + np.random.uniform(-15, 15, size=2)
        init_state = np.array(
            [agent_xy[0], agent_xy[1], T_INIT_XY[0], T_INIT_XY[1], T_INIT_ANG],
            dtype=np.float64,
        )
        env.reset_to_state = init_state
        env.seed(seed)
        # --- end controlled init

        obs = env.reset()
        info = env._get_info()
        img = env.render(mode='human')

        retry = False
        force_save = False
        pause = False
        done = False
        coverage = 0.0
        pygame.display.set_caption(
            f'[{mode_name}] seed {seed}  IoU {coverage*100:.1f}% / 95%')
        draw_overlay(mode_int, seed, coverage)

        while not (done or force_save or retry):
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        pause = True
                    elif event.key in (pygame.K_r, pygame.K_c):
                        retry = True
                    elif event.key == pygame.K_s:
                        force_save = True
                    elif event.key == pygame.K_q:
                        exit(0)
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                        pause = False

            if retry or force_save:
                break
            if pause:
                continue

            act = agent.act(obs)
            if act is not None:
                state = np.concatenate([info['pos_agent'], info['block_pose']])
                keypoint = obs.reshape(2, -1)[0].reshape(-1, 2)[:9]
                data = {
                    'img': img,
                    'state': np.float32(state),
                    'keypoint': np.float32(keypoint),
                    'action': np.float32(act),
                    'n_contacts': np.float32([info['n_contacts']]),
                }
                episode.append(data)

            obs, reward, done, info = env.step(act)
            # reward = clip(coverage / 0.95, 0, 1) per PushTEnv.step
            coverage = float(reward) * SUCCESS_THRESHOLD
            img = env.render(mode='human')
            pygame.display.set_caption(
                f'[{mode_name}] seed {seed}  IoU {coverage*100:.1f}% / 95%')
            draw_overlay(mode_int, seed, coverage)

            clock.tick(control_hz)

        if retry:
            print(f'cancel seed {seed}  mode={mode_name}', flush=True)
            continue

        if not episode:
            print(f'skip seed {seed}  (no teleop data — mouse never engaged)',
                  flush=True)
            continue

        data_dict = dict()
        for key in episode[0].keys():
            data_dict[key] = np.stack([x[key] for x in episode])
        replay_buffer.add_episode(data_dict, compressors='disk')
        append_episode_metadata(output, mode_int, coverage)
        suffix = ' [PARTIAL]' if force_save and not done else ''
        print(f'saved seed {seed}  mode={mode_name}  '
              f'IoU={coverage*100:.1f}%{suffix}  '
              f'(total {replay_buffer.n_episodes} episodes)', flush=True)


if __name__ == "__main__":
    main()