"""Seeded, temporally continuous RGB-only illumination, bounded by +/-4 EV.""" from functools import lru_cache from pathlib import Path import json import os import numpy as np CAMERAS = ('top', 'left_wrist', 'right_wrist') CATEGORIES = ('low', 'strong', 'direction', 'moving_shadow_flicker', 'asymmetric') RANGES = ((0.25, 1.0), (1.0, 2.5), (2.5, 4.0)) RGB = np.arange(256, dtype=np.float32) / 255 LINEAR = np.where(RGB <= .04045, RGB / 12.92, ((RGB + .055) / 1.055) ** 2.4) @lru_cache(maxsize=24) def coordinates(h, w): return np.meshgrid(np.linspace(0, 1, w, dtype=np.float32), np.linspace(0, 1, h, dtype=np.float32)) @lru_cache(maxsize=512) def parameters(category, tier, seed): if category not in CATEGORIES or tier not in (0, 1, 2): raise ValueError('Invalid lighting identity') rng = np.random.default_rng(seed) return dict(level=float(rng.uniform(*RANGES[tier])), angle=float(rng.uniform(0, 2*np.pi)), sigma=float(rng.uniform(.1, .35)), period=float(rng.uniform(1, 3)), phase=float(rng.uniform(0, 2*np.pi)), cameras=tuple(int(i) for i in rng.permutation(3)), variant=int(rng.integers(2)), sign=int(rng.choice([-1, 1]))) def ev_maps(category, tier, seed, time_s, shape): p = parameters(category, tier, seed) level, phase = p['level'], 2*np.pi*float(time_s)/p['period'] + p['phase'] x, y = coordinates(*shape) axis = (x-.5)*np.cos(p['angle']) + (y-.5)*np.sin(p['angle']) center = .25*np.sin(phase) zero = np.zeros(shape, dtype=np.float32) if category in ('low', 'strong'): ev = level * (-1 if category == 'low' else 1) maps = [np.full(shape, ev, np.float32) if p['variant'] == 0 or i == p['cameras'][0] else zero.copy() for i in range(3)] elif category == 'direction': if p['variant'] == 0: ev = level*np.tanh(3*(axis-center)) else: cx, cy = .5+.25*np.sin(phase), .5+.25*np.cos(phase) ev = level*(np.exp(-((x-cx)**2+(y-cy)**2)/(2*p['sigma']**2))-.25) maps = [ev.copy() for _ in range(3)] elif category == 'moving_shadow_flicker': ev = (-level*np.exp(-.5*((axis-center)/p['sigma'])**2) if p['variant'] == 0 else level*np.sin(phase)*np.ones(shape, np.float32)) maps = [ev.copy() for _ in range(3)] else: maps = [zero.copy() for _ in range(3)] maps[p['cameras'][0]] = np.full(shape, p['sign']*level, np.float32) if p['variant']: maps[p['cameras'][1]] = np.full(shape, -p['sign']*level, np.float32) return [np.asarray(np.clip(ev, -4, 4), np.float32) for ev in maps] def expose(image, ev): if image.dtype != np.uint8 or image.ndim != 3 or image.shape[2] != 3: raise ValueError('Expected uint8 RGB') linear = np.clip(LINEAR[image] * np.exp2(ev)[..., None], 0, 1) srgb = np.where(linear <= .0031308, 12.92*linear, 1.055*linear**(1/2.4)-.055) output = np.rint(srgb*255).astype(np.uint8) if np.all(output == 0) or np.all(output == 255): raise ValueError('Solid black/white view rejected; no blank image enters training') return output @lru_cache(maxsize=1) def timestamps_and_origins(): data = Path(os.environ['DENSE_DATA_DIR']) split = json.loads(Path(os.environ['DENSE_SPLIT']).read_text()) stamps = np.load(data/'frame_cache/timestamp.npy', mmap_mode='r') origins = {} for ep, entry in split['episodes'].items(): value = float(stamps[entry['global_start']]) origins[entry['source']] = min(origins.get(entry['source'], value), value) return stamps, {int(ep): origins[e['source']] for ep,e in split['episodes'].items()} def apply_at_time(raw, recipe, time_s): category, tier, seed = recipe if category == 'standard': return dict(raw) result = dict(raw) for i, camera in enumerate(CAMERAS): key = 'observation.images.' + camera image = raw[key] ev = ev_maps(category, int(tier), int(seed), time_s, image.shape[:2])[i] result[key] = expose(image, ev) return result def apply(raw, recipe, frame): if recipe[0] == 'standard': return dict(raw) stamps, origins = timestamps_and_origins() t = float(stamps[int(raw['sample_global_index'])]) - origins[int(raw['sample_episode_index'])] if not np.isfinite(t) or t < 0: raise ValueError('Invalid original source timestamp') return apply_at_time(raw, recipe, t)