-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathvisualizer_integration_utils.py
More file actions
2046 lines (1730 loc) · 85.1 KB
/
Copy pathvisualizer_integration_utils.py
File metadata and controls
2046 lines (1730 loc) · 85.1 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
# 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
"""Shared helpers for Cartpole visualizer integration tests.
The suite covers four visualizers: Kit, Newton, Rerun, and Viser. All visualizers
must initialize and step without visualizer-scoped log errors on both physics backends.
Kit and Newton also expose image-producing paths, so they get stronger checks:
- frames are non-flat
- frames change while simulation is playing
- frames remain stable while rendering or simulation is paused
- frames change again after play resumes
Newton has separate rendering-pause and simulation-pause controls, so those tests
also verify that physics continues during rendering pause and stays frozen during
simulation pause.
"""
from __future__ import annotations
import contextlib
import copy
import gc
import logging
import math
import os
import re
import socket
import time
from pathlib import Path
import numpy as np
import pytest
import torch
import warp as wp
from isaaclab_visualizers.kit import KitVisualizer, KitVisualizerCfg
from isaaclab_visualizers.newton import NewtonGLVisualizerCfg, NewtonVisualizer
import isaaclab.sim as sim_utils
from isaaclab.envs.utils.camera_view import camera_rgb_batch, compose_rgb_grid_tensor
from isaaclab.sim import SimulationContext
from isaaclab_tasks.core.cartpole.cartpole_direct_camera_env import CartpoleCameraEnv
from isaaclab_tasks.core.cartpole.cartpole_direct_camera_env_cfg import CartpoleCameraEnvCfg
from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import CartpolePhysicsCfg
from isaaclab_tasks.core.lift.config.franka_soft.franka_cloth_env_cfg import FrankaClothEnvCfg
from isaaclab_tasks.core.reorient.config.shadow_hand.shadow_hand_direct_env_cfg import ShadowHandEnvCfg
from isaaclab_tasks.core.reorient.reorient_direct_env import ReorientDirectEnv
from isaaclab_tasks.core.velocity.config.anymal_d.flat_env_cfg import AnymalDFlatEnvCfg
# Debugging mode configs.
_WRITE_VIS_DEBUG_FRAMES = False
"""Whether to emit visualizer debug PNGs during integration tests."""
_VIS_DEBUG_IMAGE_DIR = Path("logs/viz_integration_captures")
"""Directory for opt-in visualizer debug images emitted by integration tests."""
# When True, tests also fail on WARNING-level records from visualizer-related loggers.
ASSERT_VISUALIZER_WARNINGS = False
_NEWTON_IMGUI_BUNDLE_PRINT_WARNING = "Warning: imgui_bundle not found"
_MAX_FRAME_CHECK_STEPS = 5
"""Steps for Rerun / Viser smoke tests."""
_CARTPOLE_INTEGRATION_NUM_ENVS = 1
"""Vectorized env count for cartpole + visualizer integration tests."""
_CARTPOLE_TILED_CAMERA_INTEGRATION_NUM_ENVS = 4
"""Vectorized env count for generated visualizer tiled-camera integration tests."""
_CARTPOLE_INTEGRATION_VISUALIZER_EYE: tuple[float, float, float] = (2.25, 0.0, 3.5)
"""Passed to :class:`~isaaclab.visualizers.visualizer_cfg.VisualizerCfg` subclasses (``eye``)."""
_CARTPOLE_INTEGRATION_VISUALIZER_LOOKAT: tuple[float, float, float] = (0.0, 0.0, 2.25)
"""Passed to visualizer cfgs (``lookat``); also applied to :class:`~isaaclab.envs.common.ViewerCfg` for the env."""
_CARTPOLE_INTEGRATION_TILED_CAMERA_EYE_OFFSET: tuple[float, float, float] = tuple(
eye - lookat for eye, lookat in zip(_CARTPOLE_INTEGRATION_VISUALIZER_EYE, _CARTPOLE_INTEGRATION_VISUALIZER_LOOKAT)
)
"""Generated tiled-camera target-relative eye offset matching the shared visualizer viewing direction."""
# Resolution overrides for this test module (cartpole preset defaults: tiled camera 96×96; Kit helper was 320×240).
_CARTPOLE_KIT_INTEGRATION_RENDER_RESOLUTION: tuple[int, int] = (400, 400)
"""Kit: Replicator ``render_product`` (width, height) for viewport RGB in the motion check."""
_CARTPOLE_NEWTON_INTEGRATION_WINDOW_SIZE: tuple[int, int] = (400, 400)
"""Newton: ``NewtonGLVisualizerCfg`` framebuffer (window_width × window_height) for ``get_frame()``."""
_CARTPOLE_TILED_CAMERA_INTEGRATION_WH: tuple[int, int] = (400, 400)
"""Tiled camera per-env tile width/height (preset default is 96×96); keeps ``observation_space`` consistent."""
_CARTPOLE_VISUALIZER_TILED_CAMERA_NUM_TILES = 4
"""Number of generated visualizer camera tiles exercised by tiled-camera integration tests."""
_CARTPOLE_VISUALIZER_TILED_CAMERA_TARGET_PRIM_PATH = "/World/envs/*/Robot"
"""Cartpole articulation root prim followed by generated visualizer tiled cameras."""
_START_BUFFER_STEPS = 20
"""Warmup physics steps before capturing the first debug frame."""
_INTEGRATION_MOTION_BUFFER_STEPS = 10
"""Warmup physics steps before motion checking in integration tests."""
_KIT_RTX_RENDER_PRODUCT_WARMUP_STEPS = 20
"""Render/app updates after creating a Kit RTX render product before sampling RGB."""
_NEWTON_VIEWER_WARMUP_FRAMES = 20
"""Viewer-only updates after physics warmup before sampling Newton RGB."""
_TILED_CAMERA_SENSOR_WARMUP_UPDATES = 20
"""Extra ``camera_sensor.update()`` calls before reading tiled RGB.
NewtonVisualizer.step() skips ``_log_camera_sensor_image()`` when the Newton state
is unavailable (e.g. PhysX backend), so owned tiled cameras may have received zero
renderer updates during physics warmup. Repeating the update here gives every tile
enough frames to produce a valid image before sampling.
"""
_VISUALIZER_STARTUP_DRAIN_UPDATES = 20
"""Kit app updates before each flaky retry to let the GPU sync pending Fabric work."""
_VISUALIZER_SHUTDOWN_DRAIN_UPDATES = 20
"""Kit app updates after each flaky retry to flush GPU work before the next stage."""
_KIT_APP_DRAIN_SLEEP_SECONDS = 0.01
"""Short sleep between app updates while draining startup/shutdown work."""
_WARMUP_MAX_FRAMES = 50
"""Hard cap on render frames pumped during convergence-based warmup."""
_FRANKA_CLOTH_KIT_VIEWPORT_WARMUP_FRAMES = 20
"""Franka cloth kit-viewport warmup uses lightweight ``app.update()`` ticks
(not ``env.sim.render()``). Each ``env.sim.render()`` call for the VBD cloth
scene blocks in the Newton Fabric sync path (the VBD cloth solver never sets
``NewtonManager._newton_fabric_ready``), causing hangs on some GPU/driver
combinations. 20 ``app.update()`` ticks drive RTX TAA accumulation without
triggering the Fabric sync, producing an acceptable frame within the
loose 12% / SSIM-0.85 thresholds."""
_WARMUP_STABLE_DIFF_PCT = 0.5
"""Fraction of pixels (%) with inter-frame L2 > 1.0 below which two consecutive frames are
considered stable (renderer TAA has converged). Used by :func:`_frames_converged`."""
PLAY_VIZ_N_STEP = 20
"""Steps to run for each motion or resumed-play segment."""
PAUSE_VIZ_N_STEP = 5
"""Steps to run for each paused visualization segment."""
# Integration tests force a minimum initial pole displacement so the cartpole is guaranteed to produce
# enough pixel motion in PLAY_VIZ_N_STEP steps regardless of the random seed. Without this, a near-
# equilibrium start (angle ≈ 0, velocity ≈ 0) produces fewer than _FRAME_MOTION_MIN_DIFFERING_PIXELS
# pixel changes, causing the frozen-body frame checks to fail intermittently.
_INTEGRATION_TEST_POLE_ANGLE_RANGE: tuple[float, float] = (0.15 * math.pi, 0.25 * math.pi)
"""Minimum initial pole angle [rad] for integration motion tests — ensures visible motion."""
_INTEGRATION_TEST_POLE_VELOCITY_RANGE: tuple[float, float] = (0.1 * math.pi, 0.25 * math.pi)
"""Minimum initial pole angular velocity [rad/s] for integration motion tests."""
# Early vs late frame motion: void background stays similar; only count *strongly* differing pixels.
_FRAME_MOTION_CHANNEL_DIFF_THRESHOLD = 50
"""A pixel counts as differing if max(|ΔR|, |ΔG|, |ΔB|) >= this (0–255 space)."""
_FRAME_MOTION_MIN_DIFFERING_PIXELS = 100
"""Minimum number of such pixels between early and late frames (stale/frozen viz should be near zero)."""
_TILED_CAMERA_MOTION_CHANNEL_DIFF_THRESHOLD = 5
"""Lower per-channel threshold for Cartpole's fixed tiled camera view, where motion is more subtle."""
_TILED_CAMERA_MOTION_MIN_DIFFERING_PIXELS = 25
"""Minimum differing pixels for tiled camera motion checks."""
# NVBUG 6570125 — Remove these overrides once it ships the fix and paused frames are stable again.
_KIT_PAUSED_VIEWPORT_CHANNEL_DIFF_THRESHOLD = 80
"""Per-channel threshold for paused Kit viewport comparisons (0–255 space)."""
_KIT_PAUSED_TILED_CAMERA_NEWTON_CHANNEL_DIFF_THRESHOLD = 160
"""Per-channel threshold for paused Kit tiled camera comparisons on Newton (0–255 space)."""
_KIT_PAUSED_TILED_CAMERA_PHYSX_CHANNEL_DIFF_THRESHOLD = 80
"""Per-channel threshold for paused Kit tiled camera comparisons on PhysX (0–255 space).
Matches the viewport value but is kept separate: this cell measures 103 differing pixels at the
default threshold, so it needs its own floor rather than tracking whatever the viewport uses.
"""
_FRAME_MIN_CHANNEL_RANGE = 10
"""Minimum per-frame channel range to reject all-one-color images."""
_BODY_STATE_STABLE_MAX_DELTA = 1.0e-6
"""Maximum body-state delta allowed while simulation is paused."""
_BODY_STATE_MOTION_MIN_DELTA = 1.0e-5
"""Minimum body-state delta expected while physics continues to advance."""
_VIS_LOGGER_PREFIXES = (
"isaaclab.visualizers",
"isaaclab_visualizers",
"isaaclab.sim.simulation_context",
)
_PYTEST_CURRENT_TEST_SUFFIX_PATTERN = re.compile(r"\s+\((setup|call|teardown)\)$")
_VIS_DEBUG_TEST_ID_OVERRIDE_ENV = "ISAACLAB_VISUALIZER_DEBUG_TEST_ID"
_DEBUG_TEST_DIR_PREFIXES = {
"test_cartpole_env_visualizers_motion_with_play_pause_physx": "visualizers_physx",
"test_cartpole_env_visualizers_motion_with_play_pause_newton": "visualizers_newton",
"test_visualizer_tiled_integration_physx": "visualizers_physx",
"test_visualizer_tiled_integration_newton": "visualizers_newton",
}
_DEBUG_TEST_TILED_SUFFIXES = {
"test_visualizer_tiled_integration_physx",
"test_visualizer_tiled_integration_newton",
}
_BACKEND_DISPLAY_NAMES = {
"physx": "PhysX",
"newton": "Newton MJWarp",
}
_VISUALIZER_DISPLAY_NAMES = {
"kit": "Kit Visualizer",
"newton": "Newton Visualizer",
"rerun": "Rerun Visualizer",
"viser": "Viser Visualizer",
}
_SIMULATION_APP = None
def set_visualizer_integration_simulation_app(simulation_app) -> None:
"""Register the Kit app launched by a backend-specific test module."""
global _SIMULATION_APP
_SIMULATION_APP = simulation_app
def _visualizer_case_label(viz_kind: str, physics_kind: str) -> str:
visualizer = _VISUALIZER_DISPLAY_NAMES.get(viz_kind, f"{viz_kind.title()} Visualizer")
backend = _BACKEND_DISPLAY_NAMES.get(physics_kind, physics_kind)
return f"{visualizer} on {backend}"
def _logger_name_matches_visualizer_scope(logger_name: str) -> bool:
"""Return True if *logger_name* is a visualizer / SimulationContext visualizer path."""
return any(logger_name.startswith(prefix) for prefix in _VIS_LOGGER_PREFIXES)
def _assert_no_visualizer_log_issues(caplog: pytest.LogCaptureFixture, *, fail_on_warnings: bool | None = None) -> None:
"""Fail if captured records include ERROR/CRITICAL (always) or WARNING (if *fail_on_warnings*).
*fail_on_warnings* defaults to :data:`ASSERT_VISUALIZER_WARNINGS`.
"""
if fail_on_warnings is None:
fail_on_warnings = ASSERT_VISUALIZER_WARNINGS
error_logs = [
r for r in caplog.records if r.levelno >= logging.ERROR and _logger_name_matches_visualizer_scope(r.name)
]
assert not error_logs, "Visualizer-related error logs: " + "; ".join(
f"{r.name}: {r.getMessage()}" for r in error_logs
)
if fail_on_warnings:
warning_logs = [
r for r in caplog.records if r.levelno == logging.WARNING and _logger_name_matches_visualizer_scope(r.name)
]
assert not warning_logs, "Visualizer-related warning logs: " + "; ".join(
f"{r.name}: {r.getMessage()}" for r in warning_logs
)
def assert_no_newton_imgui_bundle_warning(capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture) -> None:
"""Fail when Newton reports that its imgui HUD dependency is missing."""
captured = capsys.readouterr()
captured_output = captured.out + captured.err
printed_warning = _NEWTON_IMGUI_BUNDLE_PRINT_WARNING in captured_output
logged_warnings = [record for record in caplog.records if _NEWTON_IMGUI_BUNDLE_PRINT_WARNING in record.getMessage()]
assert not printed_warning and not logged_warnings, (
"Newton viewer reported that imgui_bundle could not be imported, which disables HUD controls. "
f"Captured output: {captured_output!r}. "
"Captured logs: " + "; ".join(f"{record.name}: {record.getMessage()}" for record in logged_warnings)
)
def _configure_sim_for_visualizer_test(env: CartpoleCameraEnv) -> None:
"""Set ``/isaaclab/render/rtx_sensors`` True so the sim takes the RTX-sensor render path."""
env.sim.set_setting("/isaaclab/render/rtx_sensors", True)
env.sim._app_control_on_stop_handle = None # type: ignore[attr-defined]
def _find_free_tcp_port(host: str = "127.0.0.1") -> int:
"""Ask OS for a currently free local TCP port."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((host, 0))
return int(sock.getsockname()[1])
def _allocate_rerun_test_ports(host: str = "127.0.0.1") -> tuple[int, int]:
"""Allocate distinct free ports for rerun web and gRPC endpoints."""
grpc_port = _find_free_tcp_port(host)
web_port = _find_free_tcp_port(host)
while web_port == grpc_port:
web_port = _find_free_tcp_port(host)
return web_port, grpc_port
def _cartpole_integration_visualizer_camera_kwargs() -> dict[str, tuple[float, float, float]]:
"""Eye/lookat for all :class:`~isaaclab.visualizers.visualizer_cfg.VisualizerCfg` subclasses in these tests."""
return {
"eye": _CARTPOLE_INTEGRATION_VISUALIZER_EYE,
"lookat": _CARTPOLE_INTEGRATION_VISUALIZER_LOOKAT,
}
def _get_visualizer_cfg(visualizer_kind: str, *, tiled_camera: bool = False):
"""Return (visualizer_cfg, expected_visualizer_cls) for the given visualizer kind."""
cam = _cartpole_integration_visualizer_camera_kwargs()
tiled_cam = (
{
"streaming_view": True,
"streaming_envs": _CARTPOLE_VISUALIZER_TILED_CAMERA_NUM_TILES,
"streaming_sensor_prim_path": None,
"streaming_cam_eye": _CARTPOLE_INTEGRATION_TILED_CAMERA_EYE_OFFSET,
"streaming_cam_target_prim_path": _CARTPOLE_VISUALIZER_TILED_CAMERA_TARGET_PRIM_PATH,
}
if tiled_camera
else {}
)
if visualizer_kind == "newton":
__import__("newton")
nw, nh = _CARTPOLE_NEWTON_INTEGRATION_WINDOW_SIZE
return (
NewtonGLVisualizerCfg(
headless=True,
window_width=nw,
window_height=nh,
randomly_sample_visible_envs=False,
**tiled_cam,
**cam,
),
NewtonVisualizer,
)
if visualizer_kind == "viser":
__import__("newton")
__import__("viser")
from isaaclab_visualizers.viser import ViserVisualizer, ViserVisualizerCfg
port = _find_free_tcp_port(host="127.0.0.1")
return (
ViserVisualizerCfg(open_browser=False, port=port, randomly_sample_visible_envs=False, **cam),
ViserVisualizer,
)
if visualizer_kind == "rerun":
__import__("newton")
from isaaclab_visualizers.rerun import RerunVisualizer, RerunVisualizerCfg
web_port, grpc_port = _allocate_rerun_test_ports(host="127.0.0.1")
return (
RerunVisualizerCfg(
bind_address="127.0.0.1",
open_browser=False,
web_port=web_port,
grpc_port=grpc_port,
randomly_sample_visible_envs=False,
**cam,
),
RerunVisualizer,
)
return (
KitVisualizerCfg(
window_width=_CARTPOLE_KIT_INTEGRATION_RENDER_RESOLUTION[0],
window_height=_CARTPOLE_KIT_INTEGRATION_RENDER_RESOLUTION[1],
randomly_sample_visible_envs=False,
**tiled_cam,
**cam,
),
KitVisualizer,
)
def _get_physics_cfg(backend_kind: str):
"""Return physics config and expected backend substring for the given backend kind."""
if backend_kind == "physx":
__import__("isaaclab_physx")
preset = CartpolePhysicsCfg()
physics_cfg = getattr(preset, "physx", None)
if physics_cfg is None:
from isaaclab_physx.physics import PhysxCfg
physics_cfg = PhysxCfg()
return physics_cfg, "physx"
if backend_kind == "newton":
__import__("newton")
__import__("isaaclab_newton")
preset = CartpolePhysicsCfg()
physics_cfg = getattr(preset, "newton_mjwarp", None)
if physics_cfg is None:
from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg
physics_cfg = NewtonCfg(
solver_cfg=MJWarpSolverCfg(
njmax=5,
nconmax=3,
cone="pyramidal",
impratio=1,
integrator="implicitfast",
),
num_substeps=1,
debug_mode=False,
use_cuda_graph=True,
)
return physics_cfg, "newton"
raise ValueError(f"Unknown backend: {backend_kind!r}")
def _frame_to_numpy(frame) -> np.ndarray:
"""Convert viewer ``get_frame()`` output (numpy, torch, or Warp array) to host ``numpy.ndarray``.
``np.asarray(wp.array)`` is unsafe: NumPy can trigger Warp indexing that raises at dimension edges.
"""
if isinstance(frame, np.ndarray):
return frame
if torch.is_tensor(frame):
return frame.detach().cpu().numpy()
if isinstance(frame, wp.array):
return wp.to_torch(frame).detach().cpu().numpy()
return np.asarray(frame)
def _assert_non_flat_frame_array(frame) -> None:
"""Assert viewer-captured frame has non-flat content."""
frame_arr = _frame_to_numpy(frame)
assert frame_arr.size > 0, "Viewer returned an empty frame."
if frame_arr.ndim != 2:
assert frame_arr.shape[-1] >= 3, f"Expected at least 3 channels, got shape {frame_arr.shape}."
rgb = _frame_rgb_255_space(frame)
channel_range = float(np.max(rgb) - np.min(rgb))
assert channel_range >= _FRAME_MIN_CHANNEL_RANGE, (
f"Viewer frame appears flat / single-color (channel range {channel_range:.3f} < {_FRAME_MIN_CHANNEL_RANGE})."
)
def _frame_rgb_255_space(frame) -> np.ndarray:
"""Return HxWx3 float in ~0–255 space for per-channel differencing."""
arr = _frame_to_numpy(frame)
if arr.ndim == 2:
rgb = np.stack([arr, arr, arr], axis=-1)
else:
rgb = arr[..., :3]
rgb = np.asarray(rgb, dtype=np.float64)
# Normalized HDR buffers: scale so threshold matches (0,255) semantics.
if rgb.size > 0 and float(np.nanmax(rgb)) <= 1.0 + 1e-6:
rgb = rgb * 255.0
return rgb
def _current_visualizer_debug_dir() -> Path:
override_test_id = os.environ.get(_VIS_DEBUG_TEST_ID_OVERRIDE_ENV)
if override_test_id:
safe_override_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", override_test_id).strip("_").lower()
return _VIS_DEBUG_IMAGE_DIR / (safe_override_id or "manual_run")
current_test = os.environ.get("PYTEST_CURRENT_TEST", "manual_run")
test_id = _PYTEST_CURRENT_TEST_SUFFIX_PATTERN.sub("", current_test).split("::")[-1]
is_tiled_test = False
match = re.fullmatch(r"(?P<test_name>[^\[]+)(?:\[(?P<backend>[^\]]+)\])?", test_id)
if match:
test_name = match.group("test_name")
prefix = _DEBUG_TEST_DIR_PREFIXES.get(test_name, test_name)
backend = match.group("backend")
if backend:
test_id = f"{prefix}_{backend}"
else:
test_id = prefix
is_tiled_test = test_name in _DEBUG_TEST_TILED_SUFFIXES
if is_tiled_test:
test_id = f"{test_id}_tiled"
safe_test_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", test_id).strip("_").lower() or "manual_run"
return _VIS_DEBUG_IMAGE_DIR / safe_test_id
@contextlib.contextmanager
def _visualizer_debug_case(viz_kind: str, physics_kind: str, *, tiled: bool = False):
"""Route debug PNGs to the same per-visualizer folders even in combined tests."""
previous = os.environ.get(_VIS_DEBUG_TEST_ID_OVERRIDE_ENV)
test_id = f"{viz_kind}_viz_{physics_kind}"
if tiled:
test_id = f"{test_id}_tiled"
os.environ[_VIS_DEBUG_TEST_ID_OVERRIDE_ENV] = test_id
try:
yield
finally:
if previous is None:
os.environ.pop(_VIS_DEBUG_TEST_ID_OVERRIDE_ENV, None)
else:
os.environ[_VIS_DEBUG_TEST_ID_OVERRIDE_ENV] = previous
def _save_visualizer_debug_image(frame, file_name: str) -> None:
"""Save a visualizer frame to a clearly named PNG for pause/motion debugging."""
if not _WRITE_VIS_DEBUG_FRAMES:
return
from PIL import Image
rgb = np.clip(_frame_rgb_255_space(frame), 0, 255).astype(np.uint8)
debug_dir = _current_visualizer_debug_dir()
debug_dir.mkdir(parents=True, exist_ok=True)
Image.fromarray(rgb).save(debug_dir / file_name)
def _save_visualizer_debug_delta(frame_a, frame_b, file_name: str) -> None:
"""Save an amplified absolute-difference image for a start/end frame pair."""
if not _WRITE_VIS_DEBUG_FRAMES:
return
from PIL import Image
a = _frame_rgb_255_space(frame_a)
b = _frame_rgb_255_space(frame_b)
assert a.shape == b.shape, f"Frame shape mismatch for delta image: {a.shape} vs {b.shape}."
delta = np.clip(np.abs(a - b) * 4.0, 0, 255).astype(np.uint8)
debug_dir = _current_visualizer_debug_dir()
debug_dir.mkdir(parents=True, exist_ok=True)
Image.fromarray(delta).save(debug_dir / file_name)
def _save_visualizer_debug_phase_images(
frame_a,
frame_b,
*,
prefix: str,
phase: str,
frame_start_idx: int,
frame_end_idx: int,
) -> None:
"""Save start/end/delta PNGs for one visualizer test phase."""
_save_visualizer_debug_image(frame_a, f"{prefix}a_{phase}_frame_{frame_start_idx:02d}.png")
_save_visualizer_debug_image(frame_b, f"{prefix}b_{phase}_frame_{frame_end_idx:02d}.png")
_save_visualizer_debug_delta(
frame_a,
frame_b,
f"{prefix}c_{phase}_frame_{frame_start_idx:02d}_{frame_end_idx:02d}_delta.png",
)
def _clear_visualizer_debug_frames() -> None:
if not _WRITE_VIS_DEBUG_FRAMES:
return
debug_dir = _current_visualizer_debug_dir()
debug_dir.mkdir(parents=True, exist_ok=True)
for path in debug_dir.glob("*.png"):
path.unlink()
def _count_significantly_differing_pixels(
frame_a,
frame_b,
*,
channel_diff_threshold: float = _FRAME_MOTION_CHANNEL_DIFF_THRESHOLD,
) -> int:
"""Count pixels where max(|ΔR|, |ΔG|, |ΔB|) >= *channel_diff_threshold* (0–255 space)."""
a = _frame_rgb_255_space(frame_a)
b = _frame_rgb_255_space(frame_b)
assert a.shape == b.shape, f"Frame shape mismatch for motion check: {a.shape} vs {b.shape}."
per_pixel_max = np.max(np.abs(a - b), axis=-1)
return int(np.count_nonzero(per_pixel_max >= channel_diff_threshold))
def _frame_shape_for_message(frame) -> tuple[int, ...]:
return tuple(_frame_rgb_255_space(frame).shape)
def _assert_frames_remain_stable(
frame_a,
frame_b,
*,
case_label: str,
phase: str,
debug_phase: str,
max_differing_pixels: int = 100,
channel_diff_threshold: float = _FRAME_MOTION_CHANNEL_DIFF_THRESHOLD,
) -> None:
"""Assert two viewport frames are effectively unchanged while simulation is paused."""
n_diff = _count_significantly_differing_pixels(frame_a, frame_b, channel_diff_threshold=channel_diff_threshold)
assert n_diff <= max_differing_pixels, (
f"{case_label} failed to pause during {phase}: {n_diff} pixels differed, expected at most "
f"{max_differing_pixels} with per-channel threshold {channel_diff_threshold} in 0-255 space. "
f"Frame shape={_frame_shape_for_message(frame_a)}. "
f"Debug frames: {_current_visualizer_debug_dir()}/*{debug_phase}*.png."
)
def _assert_frames_differ(
frame_a,
frame_b,
*,
case_label: str,
phase: str,
debug_phase: str,
channel_diff_threshold: float = _FRAME_MOTION_CHANNEL_DIFF_THRESHOLD,
min_differing_pixels: int = _FRAME_MOTION_MIN_DIFFERING_PIXELS,
) -> None:
"""Fail if two frames lack enough strongly differing pixels (stale/frozen bodies)."""
n_diff = _count_significantly_differing_pixels(frame_a, frame_b, channel_diff_threshold=channel_diff_threshold)
assert n_diff >= min_differing_pixels, (
f"{case_label} is frozen during {phase}: {n_diff} pixels differed, expected at least "
f"{min_differing_pixels} with per-channel threshold {channel_diff_threshold} in 0-255 space. "
)
def _assert_tiled_camera_frames_differ(frame_a, frame_b, *, case_label: str, phase: str, debug_phase: str) -> None:
"""Fail if tiled camera frames lack enough motion for the fixed Cartpole camera view."""
_assert_frames_differ(
frame_a,
frame_b,
case_label=case_label,
phase=phase,
debug_phase=debug_phase,
channel_diff_threshold=_TILED_CAMERA_MOTION_CHANNEL_DIFF_THRESHOLD,
min_differing_pixels=_TILED_CAMERA_MOTION_MIN_DIFFERING_PIXELS,
)
def _cartpole_body_state(env) -> torch.Tensor:
"""Return a compact body transform state for cartpole motion/stability checks."""
cartpole = env.scene.articulations["cartpole"]
pos = cartpole.data.body_pos_w.torch
quat = cartpole.data.body_quat_w.torch
return torch.cat((pos.reshape(-1), quat.reshape(-1))).detach().clone()
def _body_state_delta(state_a: torch.Tensor, state_b: torch.Tensor) -> float:
"""Return max absolute body-state delta."""
assert state_a.shape == state_b.shape, f"Body state shape mismatch: {state_a.shape} vs {state_b.shape}."
return float(torch.max(torch.abs(state_a - state_b)).item())
def _assert_body_state_changed(
state_a: torch.Tensor,
state_b: torch.Tensor,
*,
case_label: str,
phase: str,
min_delta: float = _BODY_STATE_MOTION_MIN_DELTA,
) -> None:
delta = _body_state_delta(state_a, state_b)
assert delta >= min_delta, (
f"{case_label} physics/body state did not advance during {phase}: max body-state delta {delta:.6g}, "
f"expected at least {min_delta:.6g}."
)
def _assert_body_state_stable(
state_a: torch.Tensor,
state_b: torch.Tensor,
*,
case_label: str,
phase: str,
max_delta: float = _BODY_STATE_STABLE_MAX_DELTA,
) -> None:
delta = _body_state_delta(state_a, state_b)
assert delta <= max_delta, (
f"{case_label} physics/body state changed during {phase}: max body-state delta {delta:.6g}, "
f"expected at most {max_delta:.6g}."
)
def _select_newton_training_control_button(viewer, target_label: str) -> None:
"""Trigger one Newton visualizer training-control button by label."""
class _FakeImgui:
def separator(self):
pass
def text(self, _text):
pass
def button(self, label):
return label == target_label
def slider_int(self, _label, value, _min_value, _max_value, _format):
return False, value
def is_item_hovered(self):
return False
def set_tooltip(self, _text):
pass
viewer._render_training_controls(_FakeImgui())
def _select_newton_pause_simulation_button(viewer) -> None:
"""Trigger the Newton visualizer's Pause/Resume Simulation UI button."""
label = "Resume Simulation" if viewer.is_training_paused() else "Pause Simulation"
_select_newton_training_control_button(viewer, label)
def _set_newton_simulation_paused(viewer, paused: bool) -> None:
"""Put Newton visualizer simulation pause control into a desired state."""
if viewer.is_training_paused() != paused:
_select_newton_pause_simulation_button(viewer)
def _select_newton_pause_rendering_button(viewer) -> None:
"""Trigger the Newton visualizer's Pause/Resume Rendering UI button."""
label = "Resume Rendering" if viewer.is_rendering_paused() else "Pause Rendering"
_select_newton_training_control_button(viewer, label)
def _set_newton_rendering_paused(viewer, paused: bool) -> None:
"""Put Newton visualizer rendering pause control into a desired state."""
if viewer.is_rendering_paused() != paused:
_select_newton_pause_rendering_button(viewer)
def _warm_newton_viewer(visualizer: NewtonVisualizer) -> None:
"""Pump Newton viewer frames before sampling ``get_frame()`` after cold starts.
Exits early once two consecutive frames converge; always stops after
``_NEWTON_VIEWER_WARMUP_FRAMES`` steps regardless of convergence so the
warmup cannot block indefinitely in CI environments.
"""
prev: np.ndarray | None = None
for i in range(_NEWTON_VIEWER_WARMUP_FRAMES):
visualizer.step(0.0)
with contextlib.suppress(Exception):
curr_raw = visualizer.render_rgb_array()
if curr_raw is not None:
curr = _frame_to_numpy(curr_raw)
if prev is not None and i >= 2 and _frames_converged(prev, curr):
return
prev = curr
def _run_newton_viewer_frame_motion_test(
env,
viewer,
*,
visualizer: NewtonVisualizer,
step_hook,
get_physics_step_count,
physics_kind: str,
viz_kind: str = "newton",
) -> None:
"""Check Newton viewer motion, rendering pause, simulation pause, and resumed motion."""
_clear_visualizer_debug_frames()
case_label = _visualizer_case_label(viz_kind, physics_kind)
for _ in range(_INTEGRATION_MOTION_BUFFER_STEPS):
step_hook()
_warm_newton_viewer(visualizer)
motion_start_frame = visualizer.render_rgb_array()
for _ in range(PLAY_VIZ_N_STEP):
step_hook()
play_end_idx = PLAY_VIZ_N_STEP
_flush_newton_render_for_motion_capture(visualizer)
motion_end_frame = visualizer.render_rgb_array()
_save_visualizer_debug_phase_images(
motion_start_frame,
motion_end_frame,
prefix="1",
phase="playing",
frame_start_idx=0,
frame_end_idx=play_end_idx,
)
_assert_non_flat_frame_array(motion_end_frame)
_assert_frames_differ(
motion_start_frame,
motion_end_frame,
case_label=case_label,
phase="playing",
debug_phase="playing",
)
rendering_pause_start_idx = play_end_idx
rendering_pause_end_idx = rendering_pause_start_idx + PAUSE_VIZ_N_STEP
def _attempt_rendering_pause():
_set_newton_rendering_paused(viewer, True)
rendering_paused_start_frame = visualizer.render_rgb_array()
rendering_pause_start_state = _cartpole_body_state(env)
physics_step_before_render_pause = get_physics_step_count()
for _ in range(PAUSE_VIZ_N_STEP):
step_hook()
rendering_pause_end_state = _cartpole_body_state(env)
rendering_paused_end_frame = visualizer.render_rgb_array()
_save_visualizer_debug_phase_images(
rendering_paused_start_frame,
rendering_paused_end_frame,
prefix="2",
phase="pausing_rendering",
frame_start_idx=rendering_pause_start_idx,
frame_end_idx=rendering_pause_end_idx,
)
_assert_frames_remain_stable(
rendering_paused_start_frame,
rendering_paused_end_frame,
case_label=case_label,
phase="pausing_rendering",
debug_phase="pausing_rendering",
)
return physics_step_before_render_pause, rendering_pause_start_state, rendering_pause_end_state
physics_step_before_render_pause, rendering_pause_start_state, rendering_pause_end_state = (
_attempt_rendering_pause()
)
assert get_physics_step_count() > physics_step_before_render_pause, (
f"{case_label} physics step count did not advance during pausing_rendering."
)
_assert_body_state_changed(
rendering_pause_start_state,
rendering_pause_end_state,
case_label=case_label,
phase="pausing_rendering",
)
rendering_play_start_idx = rendering_pause_end_idx
rendering_play_end_idx = rendering_play_start_idx + PLAY_VIZ_N_STEP
def _attempt_rendering_play():
_set_newton_rendering_paused(viewer, False)
rendering_play_start_frame = visualizer.render_rgb_array()
for _ in range(PLAY_VIZ_N_STEP):
step_hook()
_flush_newton_render_for_motion_capture(visualizer)
rendering_play_end_frame = visualizer.render_rgb_array()
_save_visualizer_debug_phase_images(
rendering_play_start_frame,
rendering_play_end_frame,
prefix="3",
phase="playing",
frame_start_idx=rendering_play_start_idx,
frame_end_idx=rendering_play_end_idx,
)
_assert_non_flat_frame_array(rendering_play_end_frame)
_assert_frames_differ(
rendering_play_start_frame,
rendering_play_end_frame,
case_label=case_label,
phase="playing after rendering pause",
debug_phase="playing",
)
_attempt_rendering_play()
simulation_pause_start_idx = rendering_play_end_idx
simulation_pause_end_idx = simulation_pause_start_idx + PAUSE_VIZ_N_STEP
def _attempt_simulation_pause():
_set_newton_simulation_paused(viewer, True)
simulation_paused_start_frame = visualizer.render_rgb_array()
simulation_pause_start_state = _cartpole_body_state(env)
physics_step_before_simulation_pause = get_physics_step_count()
for _ in range(PAUSE_VIZ_N_STEP):
visualizer.step(0.0)
simulation_pause_end_state = _cartpole_body_state(env)
simulation_paused_end_frame = visualizer.render_rgb_array()
_save_visualizer_debug_phase_images(
simulation_paused_start_frame,
simulation_paused_end_frame,
prefix="4",
phase="pausing_simulation",
frame_start_idx=simulation_pause_start_idx,
frame_end_idx=simulation_pause_end_idx,
)
_assert_frames_remain_stable(
simulation_paused_start_frame,
simulation_paused_end_frame,
case_label=case_label,
phase="pausing_simulation",
debug_phase="pausing_simulation",
)
return physics_step_before_simulation_pause, simulation_pause_start_state, simulation_pause_end_state
physics_step_before_simulation_pause, simulation_pause_start_state, simulation_pause_end_state = (
_attempt_simulation_pause()
)
assert get_physics_step_count() == physics_step_before_simulation_pause, (
f"{case_label} physics step count advanced during pausing_simulation."
)
_assert_body_state_stable(
simulation_pause_start_state,
simulation_pause_end_state,
case_label=case_label,
phase="pausing_simulation",
)
simulation_play_start_idx = simulation_pause_end_idx
simulation_play_end_idx = simulation_play_start_idx + PLAY_VIZ_N_STEP
def _attempt_simulation_play():
_set_newton_simulation_paused(viewer, False)
simulation_play_start_frame = visualizer.render_rgb_array()
for _ in range(PLAY_VIZ_N_STEP):
step_hook()
_flush_newton_render_for_motion_capture(visualizer)
simulation_play_end_frame = visualizer.render_rgb_array()
_save_visualizer_debug_phase_images(
simulation_play_start_frame,
simulation_play_end_frame,
prefix="5",
phase="playing",
frame_start_idx=simulation_play_start_idx,
frame_end_idx=simulation_play_end_idx,
)
_assert_non_flat_frame_array(simulation_play_end_frame)
_assert_frames_differ(
simulation_play_start_frame,
simulation_play_end_frame,
case_label=case_label,
phase="playing after simulation pause",
debug_phase="playing",
)
_attempt_simulation_play()
def _step_env_without_frame_check(env, actions: torch.Tensor, *, max_steps: int = _MAX_FRAME_CHECK_STEPS) -> None:
"""Step the env to exercise visualizers that do not implement ``get_frame`` (e.g. Rerun, Viser)."""
for _ in range(max_steps):
env.step(action=actions)
def _set_kit_simulation_paused(env, paused: bool) -> None:
"""Put Kit simulation play/pause state into a desired state."""
if paused:
env.sim.pause()
else:
env.sim.play()
def _build_rgb_annotator_for_camera(
camera_path: str,
*,
resolution: tuple[int, int] | None = None,
):
"""Create CPU RGB annotator attached to a camera render product."""
import omni.replicator.core as rep
if resolution is None:
resolution = _CARTPOLE_KIT_INTEGRATION_RENDER_RESOLUTION
render_product = rep.create.render_product(camera_path, resolution=resolution)
annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu")
annotator.attach([render_product])
return annotator, render_product
def _annotator_rgb_to_numpy(rgb_data) -> np.ndarray:
"""Convert replicator annotator output to HxWx3 uint8 numpy array."""
rgb_array = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape)
if rgb_array.size == 0:
return np.zeros((1, 1, 3), dtype=np.uint8)
return rgb_array[:, :, :3].copy()
def _update_active_simulation_app() -> None:
"""Pump the active Kit app launched by the backend test module."""
if _SIMULATION_APP is not None:
_SIMULATION_APP.update()
return
from isaacsim import SimulationApp
sim_app = None
if hasattr(SimulationApp, "_instance") and SimulationApp._instance is not None:
sim_app = SimulationApp._instance
elif hasattr(SimulationApp, "instance") and callable(SimulationApp.instance):
sim_app = SimulationApp.instance()
assert sim_app is not None, "Isaac Sim app is not running."
sim_app.update()
def _drain_kit_app_updates(num_updates: int) -> None:
"""Let Kit process pending renderer/extension work between retry attempts."""
for _ in range(max(0, int(num_updates))):
with contextlib.suppress(Exception):
_update_active_simulation_app()
time.sleep(_KIT_APP_DRAIN_SLEEP_SECONDS)
def _frames_converged(frame_a: np.ndarray, frame_b: np.ndarray) -> bool:
"""Return True when fewer than :data:`_WARMUP_STABLE_DIFF_PCT` % of pixels differ by L2 > 1."""
diff_l2 = np.linalg.norm(frame_a.astype(np.float32) - frame_b.astype(np.float32), axis=2)
return float(100.0 * np.mean(diff_l2 > 1.0)) < _WARMUP_STABLE_DIFF_PCT
def _flush_kit_render_for_motion_capture(env) -> None:
"""Flush the Kit RTX pipeline so the annotator reads the current physics frame.
Kit's RTX renderer is asynchronous: ``app.update()`` queues work but does not block
until the GPU finishes. Calling ``sim.render()`` followed by one extra app update
gives the pipeline enough time to commit the frame, avoiding stale annotator reads
at the end of a motion-check step loop.
"""