forked from isaac-sim/IsaacLab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager_live_visualizer.py
More file actions
424 lines (343 loc) · 16.8 KB
/
Copy pathmanager_live_visualizer.py
File metadata and controls
424 lines (343 loc) · 16.8 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
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import logging
from dataclasses import MISSING
from typing import TYPE_CHECKING
import numpy
from isaaclab.managers import ManagerBase
from isaaclab.sim import SimulationContext
from isaaclab.ui.live_plots.manager_live_plots import DirectScalarLivePlots, ManagerLivePlots
from isaaclab.utils.configclass import configclass
from .image_plot import ImagePlot
from .line_plot import LiveLinePlot
from .ui_visualizer_base import UiVisualizerBase
if TYPE_CHECKING:
import omni.ui
# import logger
logger = logging.getLogger(__name__)
@configclass
class ManagerLiveVisualizerCfg:
"""Configuration for the :class:`ManagerLiveVisualizer` class."""
debug_vis: bool = False
"""Flag used to set status of the live visualizers on startup. Defaults to False, which means closed."""
manager_name: str = MISSING
"""Manager name that corresponds to the manager of interest in the ManagerBasedEnv and ManagerBasedRLEnv"""
term_names: list[str] | dict[str, list[str]] | None = None
"""Specific term names specified in a Manager config that are chosen to be plotted. Defaults to None.
If None all terms will be plotted. For managers that utilize Groups (i.e. ObservationGroup) use a dictionary of
{group_names: [term_names]}.
"""
class ManagerLiveVisualizer(UiVisualizerBase):
"""A interface object used to transfer data from a manager to a UI widget.
This class handles the creation of UI Widgets for selected terms given a :class:`ManagerLiveVisualizerCfg`.
It iterates through the terms of the manager and creates a visualizer for each term. If the term is a single
variable or a multi-variable signal, it creates a :class:`LiveLinePlot`. If the term is an image (2D or RGB),
it creates an :class:`ImagePlot`. The visualizer can be toggled on and off using the
:attr:`ManagerLiveVisualizerCfg.debug_vis` flag in the configuration.
"""
def __init__(self, manager: ManagerBase, cfg: ManagerLiveVisualizerCfg = ManagerLiveVisualizerCfg()):
"""Initialize ManagerLiveVisualizer.
Args:
manager: The manager with terms to be plotted. The manager must have a
:meth:`~isaaclab.managers.manager_base.ManagerBase.get_active_iterable_terms` method.
cfg: The configuration file used to select desired manager terms to be plotted.
"""
self._manager = manager
self.debug_vis = cfg.debug_vis
self._env_idx: int = 0
self.cfg = cfg
self._viewer_env_idx = 0
self._vis_frame: omni.ui.Frame
self._vis_window: omni.ui.Window
self._live_plots: ManagerLivePlots | None = None
# evaluate chosen terms if no terms provided use all available.
self.term_names = []
if self.cfg.term_names is not None:
# extract chosen terms
if isinstance(self.cfg.term_names, list):
for term_name in self.cfg.term_names:
if term_name in self._manager.active_terms:
self.term_names.append(term_name)
else:
logger.error(
f"ManagerVisualizer Failure: ManagerTerm ({term_name}) does not exist in"
f" Manager({self.cfg.manager_name})"
)
# extract chosen group-terms
elif isinstance(self.cfg.term_names, dict):
# if manager is using groups and terms are saved as a dictionary
if isinstance(self._manager.active_terms, dict):
for group, terms in self.cfg.term_names:
if group in self._manager.active_terms.keys():
for term_name in terms:
if term_name in self._manager.active_terms[group]:
self.term_names.append(f"{group}-{term_name}")
else:
logger.error(
f"ManagerVisualizer Failure: ManagerTerm ({term_name}) does not exist in"
f" Group({group})"
)
else:
logger.error(
f"ManagerVisualizer Failure: Group ({group}) does not exist in"
f" Manager({self.cfg.manager_name})"
)
else:
logger.error(
f"ManagerVisualizer Failure: Manager({self.cfg.manager_name}) does not utilize grouping of"
" terms."
)
#
# Implementation checks
#
@property
def get_vis_frame(self) -> omni.ui.Frame:
"""Returns the UI Frame object tied to this visualizer."""
return self._vis_frame
@property
def get_vis_window(self) -> omni.ui.Window:
"""Returns the UI Window object tied to this visualizer."""
return self._vis_window
#
# Setters
#
@property
def has_content(self) -> bool:
"""Whether the manager has at least one active term to plot."""
terms = self._manager.active_terms
if isinstance(terms, dict):
return any(len(v) > 0 for v in terms.values())
return len(terms) > 0
def set_debug_vis(self, debug_vis: bool):
"""Set the debug visualization external facing function.
Args:
debug_vis: Whether to enable or disable the debug visualization.
"""
self._set_debug_vis_impl(debug_vis)
#
# Implementations
#
def _set_env_selection_impl(self, env_idx: int):
"""Update the index of the selected environment to display.
Args:
env_idx: The index of the selected environment.
"""
if env_idx > 0 and env_idx < self._manager.num_envs:
self._env_idx = env_idx
else:
logger.warning(f"Environment index is out of range (0, {self._manager.num_envs - 1})")
def _set_vis_frame_impl(self, frame: omni.ui.Frame):
"""Updates the assigned frame that can be used for visualizations.
Args:
frame: The debug visualization frame.
"""
self._vis_frame = frame
def _debug_vis_callback(self, event):
"""Callback for the debug visualization event."""
if not SimulationContext.instance().is_playing():
# Visualizers have not been created yet.
return
if self._live_plots is None:
return
# Collect scalar and image data through the shared ManagerLivePlots collector.
scalar_data = self._live_plots.collect(env_idx=self._env_idx)
image_data = self._live_plots.collect_images(env_idx=self._env_idx)
all_data = {**scalar_data, **image_data}
for vis, term_name in zip(self._term_visualizers, self._term_visualizer_names):
values = all_data.get(term_name)
if values is None:
continue
if isinstance(vis, LiveLinePlot):
vis.add_datapoint(values if not isinstance(values, numpy.ndarray) else values.flatten().tolist())
elif isinstance(vis, ImagePlot):
vis.update_image(numpy.array(values))
def _set_debug_vis_impl(self, debug_vis: bool):
"""Set the debug visualization implementation.
Args:
debug_vis: Whether to enable or disable debug visualization.
"""
import omni.kit.app
import omni.ui
if not hasattr(self, "_vis_frame"):
raise RuntimeError("No frame set for debug visualization.")
# Build or rebuild the shared data collector, respecting any term filter.
allowed = self.term_names if self.term_names else None
self._live_plots = ManagerLivePlots(
manager_name=self.cfg.manager_name,
manager=self._manager,
term_names=allowed,
)
# Clear internal visualizers
self._term_visualizers = []
self._term_visualizer_names = []
self._vis_frame.clear()
if debug_vis:
# if enabled create a subscriber for the post update event if it doesn't exist
if not hasattr(self, "_debug_vis_handle") or self._debug_vis_handle is None:
sim_ctx = SimulationContext.instance()
if sim_ctx is not None:
self._debug_vis_handle = sim_ctx.vis_marker_registry.add_debug_vis_callback(self)
else:
# if disabled remove the subscriber if it exists
sim_ctx = SimulationContext.instance()
if sim_ctx is not None:
sim_ctx.vis_marker_registry.clear_debug_vis_callback(self)
else:
self._debug_vis_handle = None
self._vis_frame.visible = False
return
self._vis_frame.visible = True
with self._vis_frame:
with omni.ui.VStack():
# Add a plot in a collapsible frame for each term available
for name, term in self._manager.get_active_iterable_terms(env_idx=self._env_idx):
if name in self.term_names or len(self.term_names) == 0:
frame = omni.ui.CollapsableFrame(
name,
collapsed=False,
style={"border_color": 0xFF8A8777, "padding": 4},
)
with frame:
# create line plot for single or multi-variable signals
len_term_shape = len(numpy.array(term).shape)
if len_term_shape <= 2:
plot = LiveLinePlot(y_data=[[elem] for elem in term], plot_height=150, show_legend=True)
self._term_visualizers.append(plot)
self._term_visualizer_names.append(name)
# create an image plot for 2d and greater data (i.e. mono and rgb images)
elif len_term_shape == 3:
image = ImagePlot(image=numpy.array(term), label=name)
self._term_visualizers.append(image)
self._term_visualizer_names.append(name)
else:
logger.warning(
f"ManagerLiveVisualizer: Term ({name}) is not a supported data type for"
" visualization."
)
frame.collapsed = True
self._debug_vis = debug_vis
@configclass
class DefaultManagerBasedEnvLiveVisCfg:
"""Default configuration to use for the ManagerBasedEnv. Each chosen manager assumes all terms will be plotted."""
action_live_vis = ManagerLiveVisualizerCfg(manager_name="action_manager")
observation_live_vis = ManagerLiveVisualizerCfg(manager_name="observation_manager")
@configclass
class DefaultManagerBasedRLEnvLiveVisCfg(DefaultManagerBasedEnvLiveVisCfg):
"""Default configuration to use for the ManagerBasedRLEnv. Each chosen manager assumes all terms will be plotted."""
curriculum_live_vis = ManagerLiveVisualizerCfg(manager_name="curriculum_manager")
command_live_vis = ManagerLiveVisualizerCfg(manager_name="command_manager")
reward_live_vis = ManagerLiveVisualizerCfg(manager_name="reward_manager")
termination_live_vis = ManagerLiveVisualizerCfg(manager_name="termination_manager")
class EnvLiveVisualizer:
"""A class to handle all ManagerLiveVisualizers used in an Environment."""
def __init__(self, cfg: object, managers: dict[str, ManagerBase]):
"""Initialize the EnvLiveVisualizer.
Args:
cfg: The configuration file containing terms of ManagerLiveVisualizers.
managers: A dictionary of labeled managers. i.e. {"manager_name",manager}.
"""
self.cfg = cfg
self.managers = managers
self._prepare_terms()
def _prepare_terms(self):
self._manager_visualizers: dict[str, ManagerLiveVisualizer] = dict()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
for term_name, term_cfg in cfg_items:
# check if term config is None
if term_cfg is None:
continue
# check if term config is viable
if isinstance(term_cfg, ManagerLiveVisualizerCfg):
# find appropriate manager name
manager = self.managers[term_cfg.manager_name]
self._manager_visualizers[term_cfg.manager_name] = ManagerLiveVisualizer(manager=manager, cfg=term_cfg)
else:
raise TypeError(
f"Provided EnvLiveVisualizer term: '{term_name}' is not of type ManagerLiveVisualizerCfg"
)
@property
def manager_visualizers(self) -> dict[str, ManagerLiveVisualizer]:
"""A dictionary of labeled ManagerLiveVisualizers associated manager name as key."""
return self._manager_visualizers
class DirectScalarLiveVisualizer(UiVisualizerBase):
"""Visualizer for direct scalar groups (e.g. episode metrics) in the Kit omni.ui panel.
Wraps a :class:`~isaaclab.ui.live_plots.manager_live_plots.DirectScalarLivePlots` source
and implements the :class:`UiVisualizerBase` interface so that scalar groups can be
registered alongside manager-based visualizers in :attr:`kit_manager_visualizers`.
"""
def __init__(self, source: DirectScalarLivePlots):
"""Initialize the visualizer.
Args:
source: The scalar data source to read from on each frame update.
"""
self._source = source
self._debug_vis_handle = None
self._term_visualizers: list[LiveLinePlot] = []
self._term_visualizer_names: list[str] = []
@property
def has_content(self) -> bool:
"""Whether the scalar group has at least one metric to plot."""
return len(self._source._scalars) > 0
def set_debug_vis(self, debug_vis: bool):
"""Toggle the live scalar plots on or off.
Args:
debug_vis: Whether to enable the visualization.
"""
self._set_debug_vis_impl(debug_vis)
def _set_env_selection_impl(self, env_idx: int):
pass # scalars are env-averaged; env selection has no effect
def _set_vis_frame_impl(self, frame):
self._vis_frame = frame
def _debug_vis_callback(self, event):
"""Per-frame callback: collect scalars and push to line plots."""
if not SimulationContext.instance().is_playing():
return
data = self._source.collect(env_idx=0)
for vis, name in zip(self._term_visualizers, self._term_visualizer_names):
values = data.get(name)
if values is not None:
vis.add_datapoint(values)
def _set_debug_vis_impl(self, debug_vis: bool):
"""Build or tear down the omni.ui scalar plot widgets."""
import omni.kit.app
import omni.ui
if not hasattr(self, "_vis_frame"):
raise RuntimeError("No frame set for debug visualization.")
self._term_visualizers = []
self._term_visualizer_names = []
self._vis_frame.clear()
if debug_vis:
if not hasattr(self, "_debug_vis_handle") or self._debug_vis_handle is None:
sim_ctx = SimulationContext.instance()
if sim_ctx is not None:
self._debug_vis_handle = sim_ctx.vis_marker_registry.add_debug_vis_callback(self)
else:
sim_ctx = SimulationContext.instance()
if sim_ctx is not None:
sim_ctx.vis_marker_registry.clear_debug_vis_callback(self)
else:
self._debug_vis_handle = None
self._vis_frame.visible = False
return
self._vis_frame.visible = True
initial_data = self._source.collect(env_idx=0)
with self._vis_frame:
with omni.ui.VStack():
for name, values in initial_data.items():
frame = omni.ui.CollapsableFrame(
name,
collapsed=True,
style={"border_color": 0xFF8A8777, "padding": 4},
)
with frame:
plot = LiveLinePlot(y_data=[[v] for v in values], plot_height=150, show_legend=True)
self._term_visualizers.append(plot)
self._term_visualizer_names.append(name)
self._debug_vis = debug_vis