forked from isaac-sim/IsaacLab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrendering_test_utils.py
More file actions
2029 lines (1675 loc) · 88.5 KB
/
Copy pathrendering_test_utils.py
File metadata and controls
2029 lines (1675 loc) · 88.5 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 rendering correctness tests."""
import logging
import os
import re
import tempfile
from datetime import datetime
from html import escape
from typing import TYPE_CHECKING, Any
import numpy as np
import pytest
import torch
from PIL import Image, ImageChops
from isaaclab.utils.images import make_camera_output_grid, normalize_camera_output_for_display
from isaaclab.utils.warp import ProxyArray
if TYPE_CHECKING:
from pxr import Sdf
from isaaclab.sensors.camera import CameraData
logger = logging.getLogger(__name__)
# Directory containing golden images.
_GOLDEN_IMAGES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "golden_images")
# Directory containing golden USD stage files.
_GOLDEN_STAGES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "golden_stages")
# Pixel L2 norm difference threshold. L2 norm difference is the Euclidean distance between two pixels:
#
# d = sqrt((R1 - R2)^2 + (G1 - G2)^2 + (B1 - B2)^2)
#
# If the difference between two pixels is less than this threshold, consider them "equal" (i.e. within the tolerance).
#
_PIXEL_L2_NORM_DIFFERENCE_THRESHOLD = 10.0
# The max percentage of pixels allowed to differ. If the percentage exceeds this value, the test will fail.
# The value is set case by case based on the screen space taken up by the env in camera output images. It
# needs to be large enough to tolerate minor rendering noise while small enough to catch unexpected changes.
MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME = {
# RTX anti-aliasing along the ground-plane edges varies slightly across GPU and driver environments.
"cartpole": 1.5,
# Aliasing artifacts of shadow on the table.
"franka_cloth": 8.0,
"franka_soft": 8.0,
"franka_cable": 8.0,
# Shadow-hand renderings (incl. ``Isaac-Reorient-Cube-Shadow-Camera-Direct``) show up to
# ~3.28 % per-pixel diff from anti-aliasing noise along the many finger/cube edges. 5.0 gives
# headroom above that without masking real regressions, which the SSIM gate still catches.
"shadow_hand": 5.0,
# Texture aliasing artifacts on the ground (NVBUG#6116767)
"lift_kuka_homo": 8.0,
"lift_kuka_hetero": 8.0,
}
# OVRTX 0.4.1 rendering fixes allow a tighter tolerance for data types that
# are not dominated by scale-sensitive depth normalization.
_OVRTX_MAX_DIFFERENT_PIXELS_PERCENTAGE = 3.0
_OVRTX_SCALE_SENSITIVE_DATA_TYPES = {"depth", "distance_to_camera", "distance_to_image_plane"}
def _max_different_pixels_percentage(env_name: str, renderer: str, data_type: str) -> float:
"""Return the image-difference tolerance for an environment and renderer."""
threshold = MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME[env_name]
if renderer == "ovrtx_renderer" and data_type not in _OVRTX_SCALE_SENSITIVE_DATA_TYPES:
return min(threshold, _OVRTX_MAX_DIFFERENT_PIXELS_PERCENTAGE)
return threshold
# Minimum SSIM score below which two images are considered structurally different. SSIM is a perceptual metric
# robust to uniform per-pixel noise that penalises structural changes (geometry shifts, swapped colours, missing
# materials, etc.), so it complements the per-pixel L2 gate by catching regressions that survive a loosened pixel
# threshold.
_SSIM_THRESHOLD = 0.985
# Per-env SSIM overrides. Envs not listed fall back to ``_SSIM_THRESHOLD``. Loosened individually
# (not globally) to keep the strict gate active everywhere it already passes.
_SSIM_THRESHOLD_BY_ENV_NAME = {
# Texture aliasing artifacts on the ground (NVBUG#6116767)
"lift_kuka_homo": 0.95,
"lift_kuka_hetero": 0.95,
}
# Data types for which the SSIM gate is not enforced. SSIM assumes natural-image statistics and is unreliable on
# outputs where the per-pixel value distribution is highly non-uniform after normalisation (e.g. depth, where we
# divide by the max value so tiny absolute differences near the far plane dominate windowed variance). For these
# data types we still compute SSIM for reporting, but only the per-pixel L2 gate is used to decide pass/fail.
# ``motion_vectors`` is included for the same reason: per-pixel (u, v) offsets are normalized by their max
# magnitude, so small absolute differences in near-static regions can dominate windowed variance.
_SSIM_DISABLED_DATA_TYPES: set[str] = {
"depth",
"distance_to_camera",
"distance_to_image_plane",
"instance_segmentation",
"instance_id_segmentation_fast",
"motion_vectors",
}
# Directory for comparison images saved during the test session.
# Located under the pytest output root so it gets copied alongside test reports.
_COMPARISON_IMAGES_DIR = os.path.join(os.getcwd(), "tests", "comparison-images")
_COMPARISON_IMAGE_SUBDIR = "images"
_COPY_ICON_SVG = (
'<svg class="copy-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"'
' stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
'<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/>'
'<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>'
"</svg>"
)
_CHECK_ICON_SVG = (
'<svg class="check-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"'
' stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
'<path d="M20 6 9 17l-5-5"/>'
"</svg>"
)
# ---------------------------------------------------------------------------
# Parametrization: (physics_backend, renderer, data_type)
# ---------------------------------------------------------------------------
# Low-resolution camera outputs from RTX renderers are not deterministic enough to pass golden image testing
# on every CI run. (NVBUG#6152566)
_FLAKY_MARK = pytest.mark.flaky(max_runs=3, min_passes=1)
# Expand this tuple to test additional camera sensor data types
_DEFAULT_SENSOR_DATA_TYPES = (
"rgb",
"albedo",
"simple_shading_constant_diffuse",
"simple_shading_diffuse_mdl",
"simple_shading_full_mdl",
"semantic_segmentation",
"depth",
"distance_to_camera",
"distance_to_image_plane",
"normals",
"instance_segmentation",
"instance_id_segmentation_fast",
"motion_vectors",
)
# Data types the Newton Warp renderer (``newton_renderer``) supports. Expand this tuple as the
# renderer gains support for additional output types.
_NEWTON_WARP_DATA_TYPES = (
"rgb",
"depth",
"distance_to_camera",
"distance_to_image_plane",
"normals",
"semantic_segmentation",
"instance_segmentation",
)
# Data types the OVRTX renderer supports. ``instance_id_segmentation_fast`` is intentionally
# excluded: it has no real-world sensor equivalent, so the OVRTX integration does not support it.
# Users should use ``instance_segmentation`` or ``semantic_segmentation`` instead.
_OVRTX_DATA_TYPES = tuple(dt for dt in _DEFAULT_SENSOR_DATA_TYPES if dt != "instance_id_segmentation_fast")
_KITLESS_STAGE_VARIANTS = ("legacy", "ovstage")
def make_xfail_rendering_params(
params: list[pytest.param],
expected_failures: dict[tuple[str, ...], str],
) -> list[pytest.param]:
"""Mark selected rendering parameter combinations as expected failures.
Args:
params: Rendering parameters containing physics backend, renderer, and data type values.
expected_failures: Mapping from parameter value tuples to expected-failure reasons.
Returns:
Rendering parameters with non-strict ``xfail`` marks applied to matching combinations.
"""
marked_params = []
for param in params:
reason = expected_failures.get(tuple(param.values))
if reason is None:
marked_params.append(param)
continue
# Expected failures should run once and carry one unambiguous reason.
marks = [mark for mark in param.marks if mark.name not in ("flaky", "xfail")]
marked_params.append(
pytest.param(
*param.values,
id=param.id,
marks=[*marks, pytest.mark.xfail(reason=reason, strict=False)],
)
)
return marked_params
def make_skip_rendering_params(
params: list[pytest.param],
expected_skips: dict[tuple[str, ...], str],
) -> list[pytest.param]:
"""Mark selected rendering parameter combinations as skipped.
Args:
params: Rendering parameters to mark.
expected_skips: Mapping from parameter value tuples to skip reasons.
Returns:
Rendering parameters with ``skip`` marks applied to matching combinations.
"""
marked_params = []
for param in params:
reason = expected_skips.get(tuple(param.values))
if reason is None:
marked_params.append(param)
continue
# A native crash or timeout cannot be handled by xfail. Ensure skip takes precedence
# and does not retain retry or expected-failure marks inherited from the shared matrix.
marks = [mark for mark in param.marks if mark.name not in ("flaky", "skip", "xfail")]
marked_params.append(
pytest.param(
*param.values,
id=param.id,
marks=[*marks, pytest.mark.skip(reason=reason)],
)
)
return marked_params
def make_kitless_rendering_params(params: list[pytest.param]) -> list[pytest.param]:
"""Expand kitless rendering parameters across applicable OVRTX stage paths.
OVRTX runs through both the legacy renderer-owned stage path and the OVStage
path. The Newton Warp renderer does not use OVStage, so it is emitted only in
the legacy lane.
Args:
params: Rendering parameters containing physics backend, renderer, and data type values.
Returns:
Rendering parameters prefixed with the applicable stage variant.
"""
expanded_params = []
for param in params:
renderer = param.values[1]
variants = _KITLESS_STAGE_VARIANTS if renderer == "ovrtx_renderer" else (_KITLESS_STAGE_VARIANTS[0],)
for variant in variants:
expanded_params.append(
pytest.param(
variant,
*param.values,
id=f"{variant}-{param.id}",
marks=param.marks,
)
)
return expanded_params
def _make_sensor_data_type_params(
physics_backend: str,
renderer: str,
sensor_data_types: list[str] | None = None,
*,
flaky: bool = True,
renderer_label: str | None = None,
) -> list[pytest.param]:
"""Create golden-image parameter entries for the given data types.
Args:
physics_backend: Physics backend label (e.g. ``"physx"``, ``"newton"``, ``"ovphysx"``).
renderer: Renderer nickname; the camera renderer argument becomes ``f"{renderer}_renderer"``.
sensor_data_types: Data types to parametrize. Defaults to :data:`_DEFAULT_SENSOR_DATA_TYPES`.
flaky: Whether to apply the retry mark. RTX renderers are non-deterministic and need it; the
deterministic Warp rasterizer does not.
renderer_label: Overrides the renderer segment of the test id. Defaults to ``renderer``; used
to keep the ``newton_warp`` id distinct from its ``newton_renderer`` argument.
"""
sensor_data_types = list(sensor_data_types or _DEFAULT_SENSOR_DATA_TYPES)
label = renderer_label or renderer
marks = _FLAKY_MARK if flaky else ()
return [
pytest.param(
physics_backend,
f"{renderer}_renderer",
data_type,
id=f"{physics_backend}-{label}-{data_type}",
marks=marks,
)
for data_type in sensor_data_types
]
PHYSICS_RENDERER_AOV_COMBINATIONS = [
*_make_sensor_data_type_params("physx", "isaacsim_rtx"),
*_make_sensor_data_type_params("newton", "isaacsim_rtx"),
*_make_sensor_data_type_params(
"physx", "newton", _NEWTON_WARP_DATA_TYPES, flaky=False, renderer_label="newton_warp"
),
]
KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS = [
*_make_sensor_data_type_params("ovphysx", "ovrtx", _OVRTX_DATA_TYPES),
*_make_sensor_data_type_params("newton", "ovrtx", _OVRTX_DATA_TYPES),
*_make_sensor_data_type_params(
"ovphysx", "newton", _NEWTON_WARP_DATA_TYPES, flaky=False, renderer_label="newton_warp"
),
*_make_sensor_data_type_params(
"newton", "newton", _NEWTON_WARP_DATA_TYPES, flaky=False, renderer_label="newton_warp"
),
]
def make_kitless_rendering_params_lift() -> list[pytest.param]:
"""Create kitless Lift rendering parameters."""
return make_kitless_rendering_params(KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS)
def make_kitless_rendering_params_franka() -> list[pytest.param]:
"""Create kitless Franka rendering parameters."""
return make_kitless_rendering_params(KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS)
# Tolerances for the numeric transform comparison. Transform entries mix unit-scale rotation
# components with translations in metres, so a small absolute floor plus a relative term absorbs
# per-platform / per-Kit-build float noise while still catching real pose changes.
_STAGE_TRANSFORM_RTOL = 1e-4
_STAGE_TRANSFORM_ATOL = 1e-5
# Cap on the number of reported stage differences so a large regression stays readable.
_MAX_STAGE_DIFF_LINES = 80
_HYDRA_TEXTURES_PATH_PREFIX = "/Render/OmniverseKit/HydraTextures/"
_VOLATILE_RENDER_PRODUCT_SEGMENT_RE = re.compile(r"^(?:Replicator|rp_[0-9a-f]{32})$")
def _is_volatile_render_product_segment(segment: str) -> bool:
"""Return True when *segment* is a legacy or UUID Isaac RTX tiled render-product name."""
return _VOLATILE_RENDER_PRODUCT_SEGMENT_RE.match(segment) is not None
def _collect_volatile_render_product_segments(paths: set[str] | dict[str, Any]) -> set[str]:
"""Collect direct HydraTextures child names that denote volatile render products."""
volatile_segments: set[str] = set()
for path in paths:
if _HYDRA_TEXTURES_PATH_PREFIX not in path:
continue
parts = path.split("/")
try:
hydra_idx = parts.index("HydraTextures")
except ValueError:
continue
if hydra_idx + 1 >= len(parts):
continue
segment = parts[hydra_idx + 1]
if _is_volatile_render_product_segment(segment):
volatile_segments.add(segment)
return volatile_segments
def _canonicalize_volatile_render_product_paths(
structure: dict[str, str],
transforms: dict[str, np.ndarray],
) -> tuple[dict[str, str], dict[str, np.ndarray]]:
"""Rewrite legacy ``Replicator`` and UUID ``rp_<hex>`` render-product paths to stable tokens.
Isaac RTX tiled render products are named ``rp_{uuid4.hex}`` at runtime, while older golden
stages still use the fixed ``Replicator`` prim. Canonicalizing both to ``rp_canonical_N`` keeps
golden stage comparison stable without reverting production UUID naming.
"""
volatile_segments = _collect_volatile_render_product_segments(set(structure))
canonical_map = {segment: f"rp_canonical_{index}" for index, segment in enumerate(sorted(volatile_segments))}
if not canonical_map:
return structure, transforms
def _rewrite_path(path: str) -> str:
parts = path.split("/")
try:
hydra_idx = parts.index("HydraTextures")
except ValueError:
return path
if hydra_idx + 1 >= len(parts):
return path
segment = parts[hydra_idx + 1]
if segment in canonical_map:
parts[hydra_idx + 1] = canonical_map[segment]
return "/".join(parts)
return path
canonical_structure = {_rewrite_path(path): type_name for path, type_name in structure.items()}
canonical_transforms = {_rewrite_path(path): matrix for path, matrix in transforms.items()}
return canonical_structure, canonical_transforms
def extract_stage_structure_and_transforms(usd_path: str) -> tuple[dict[str, str], dict[str, np.ndarray]]:
"""Open a USD stage and return its prim structure and per-prim world transforms.
Args:
usd_path: Path to a ``.usda``/``.usd`` file to open and compose.
Returns:
A ``(structure, transforms)`` pair. ``structure`` maps every prim path to its type name.
``transforms`` maps each :class:`~pxr.UsdGeom.Xformable` prim path to its 4x4 local-to-world
transform as a ``float64`` array.
"""
from pxr import Usd, UsdGeom # noqa: PLC0415
stage = Usd.Stage.Open(usd_path)
if stage is None:
raise RuntimeError(f"Failed to open USD stage at {usd_path}.")
structure: dict[str, str] = {}
transforms: dict[str, np.ndarray] = {}
xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default())
for prim in stage.Traverse():
path = str(prim.GetPath())
structure[path] = str(prim.GetTypeName())
if UsdGeom.Xformable(prim):
matrix = xform_cache.GetLocalToWorldTransform(prim)
transforms[path] = np.array([[matrix[row][col] for col in range(4)] for row in range(4)], dtype=np.float64)
return structure, transforms
def compare_golden_stage(golden_path: str, result_path: str) -> list[str]:
"""Compare two USD stages by prim structure (exact) and world transforms (``allclose``).
Prim structure — the set of prim paths and their type names — must match exactly. Transforms of
prims present in both stages are compared with :func:`numpy.allclose` so per-platform float noise
does not trip the comparison. Returns a list of human-readable difference descriptions (empty
when the stages match).
"""
golden_structure, golden_transforms = extract_stage_structure_and_transforms(golden_path)
result_structure, result_transforms = extract_stage_structure_and_transforms(result_path)
golden_structure, golden_transforms = _canonicalize_volatile_render_product_paths(
golden_structure, golden_transforms
)
result_structure, result_transforms = _canonicalize_volatile_render_product_paths(
result_structure, result_transforms
)
problems: list[str] = []
golden_paths, result_paths = set(golden_structure), set(result_structure)
for path in sorted(result_paths - golden_paths):
problems.append(f"+ added prim {path} ({result_structure[path]})")
for path in sorted(golden_paths - result_paths):
problems.append(f"- removed prim {path} ({golden_structure[path]})")
for path in sorted(golden_paths & result_paths):
if golden_structure[path] != result_structure[path]:
problems.append(f"~ type changed {path}: {golden_structure[path]} -> {result_structure[path]}")
for path in sorted(set(golden_transforms) & set(result_transforms)):
golden_matrix, result_matrix = golden_transforms[path], result_transforms[path]
if not np.allclose(golden_matrix, result_matrix, rtol=_STAGE_TRANSFORM_RTOL, atol=_STAGE_TRANSFORM_ATOL):
max_diff = float(np.max(np.abs(golden_matrix - result_matrix)))
problems.append(f"~ transform {path}: max abs diff {max_diff:.3e} exceeds tolerance")
return problems
def _sanitize_golden_stage_text(text: str) -> str:
"""Strip machine-specific provenance from a flattened golden so it commits reproducibly.
Blanks the volatile ``doc`` provenance block (which embeds the generating host's temp path) and
masks absolute filesystem asset paths left in material/texture attributes. Neither is consulted
by the structure/transform comparison, so masking keeps the committed baseline free of local,
host-specific paths without affecting correctness. Portable asset tokens (e.g. ``@OmniPBR.mdl@``)
have no leading drive/slash and are left untouched.
"""
text = re.sub(r'doc = """.*?"""', 'doc = """"""', text, flags=re.DOTALL)
text = re.sub(r"@(?:[A-Za-z]:)?[\\/][^@\n]*@", "@<MASKED_ASSET_PATH>@", text)
# Ensure a single trailing newline so regeneration stays clean under the end-of-file hook.
return text.rstrip("\n") + "\n"
def _restore_remote_asset_paths(layer: "Sdf.Layer") -> None:
"""Point cached asset paths in ``layer`` back at the URLs they were downloaded from.
Remote USD assets are referenced through a local cache copy, so flattening resolves the
textures and materials they carry into absolute cache paths that exist only on the machine
that ran the test. Locally authored paths are left untouched.
"""
from pxr import UsdUtils # noqa: PLC0415
from isaaclab.utils.assets import unmirror_file_path # noqa: PLC0415
UsdUtils.ModifyAssetPaths(layer, lambda asset_path: unmirror_file_path(asset_path) or asset_path)
def maybe_save_stage(
test_name: str,
physics_backend: str,
renderer: str,
data_type: str,
*,
compare_golden: bool = False,
) -> None:
"""Dump the current USD stage and optionally compare it against a golden USDA file.
When ``ISAAC_LAB_SAVE_STAGES`` is set, the stage is written to that directory. When
``compare_golden`` is True, the exported stage is validated against
``golden_stages/<test_name>/<physics_backend>-<renderer>-<data_type>.usda`` by opening both
stages and comparing prim structure exactly and world transforms with :func:`numpy.allclose`
(see :func:`compare_golden_stage`). A missing baseline is bootstrapped and the test fails.
"""
out_dir = os.environ.get("ISAAC_LAB_SAVE_STAGES")
if not out_dir and not compare_golden:
return
import isaaclab.sim as sim_utils
safe_test_name = test_name.replace("/", "_")
stage_basename = f"{safe_test_name}-{physics_backend}-{renderer}-{data_type}.usda"
with tempfile.NamedTemporaryFile(suffix=".usda", delete=False) as tmp_file:
stage_path = tmp_file.name
try:
if not sim_utils.save_stage(stage_path, save_and_reload_in_place=False):
pytest.fail(f"save_stage reported failure while writing the USD stage to {stage_path}.")
from pxr import Usd # noqa: PLC0415
# Flatten the saved stage to inline sublayer references and resolve asset paths.
opened_stage = Usd.Stage.Open(stage_path)
if opened_stage is None:
pytest.fail(f"Could not open the saved stage at {stage_path} to flatten.")
flat_layer = opened_stage.Flatten()
if flat_layer is None:
pytest.fail(f"Could not flatten the saved stage at {stage_path}.")
_restore_remote_asset_paths(flat_layer)
if out_dir:
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, stage_basename)
if not flat_layer.Export(out_path):
pytest.fail(f"Failed to export the flattened stage to {out_path}.")
logger.info("[ISAAC_LAB_SAVE_STAGES] wrote %s", out_path)
if compare_golden:
golden_dir = os.path.join(_GOLDEN_STAGES_DIRECTORY, safe_test_name)
os.makedirs(golden_dir, exist_ok=True)
golden_path = os.path.join(golden_dir, f"{physics_backend}-{renderer}-{data_type}.usda")
if not os.path.exists(golden_path):
if not flat_layer.Export(golden_path):
pytest.fail(f"Failed to export the flattened golden baseline to {golden_path}.")
# Strip host-specific provenance/paths so the committed baseline is reproducible.
with open(golden_path, encoding="utf-8") as file:
golden_text = file.read()
with open(golden_path, "w", encoding="utf-8", newline="\n") as file:
file.write(_sanitize_golden_stage_text(golden_text))
pytest.fail(f"Golden stage not found at {golden_path}. A new baseline was written.")
# Write the flattened result to a temp file so both sides of the comparison use
# the same representation as the bootstrap wrote for the golden.
with tempfile.NamedTemporaryFile(suffix=".usda", delete=False) as flat_tmp:
flat_stage_path = flat_tmp.name
try:
if not flat_layer.Export(flat_stage_path):
pytest.fail("Failed to write flattened result stage for comparison.")
problems = compare_golden_stage(golden_path, flat_stage_path)
finally:
if os.path.exists(flat_stage_path):
os.unlink(flat_stage_path)
if problems:
diff_summary = "\n".join(problems[:_MAX_STAGE_DIFF_LINES])
if len(problems) > _MAX_STAGE_DIFF_LINES:
diff_summary += f"\n... ({len(problems) - _MAX_STAGE_DIFF_LINES} more differences)"
pytest.fail(
f"{test_name} (physics={physics_backend}, renderer={renderer}, data_type={data_type}) "
f"USD stage mismatch:\n{diff_summary}"
)
finally:
if os.path.exists(stage_path):
os.unlink(stage_path)
def _apply_overrides_to_env_cfg(env_cfg: Any, override_args: list[str]) -> Any:
"""Apply override args to env_cfg using parse_overrides and apply_overrides."""
from isaaclab_tasks.utils.hydra import apply_overrides, collect_presets, parse_overrides
presets = {"env": collect_presets(env_cfg)}
global_presets, preset_sel, preset_scalar, _ = parse_overrides(override_args, presets)
hydra_cfg = {"env": env_cfg.to_dict()}
env_cfg, _ = apply_overrides(env_cfg, None, hydra_cfg, global_presets, preset_sel, preset_scalar, presets)
return env_cfg
def _maybe_enable_physx_determinism_for_motion(env_cfg: Any, physics_backend: str, data_type: str) -> None:
"""Trade PhysX solver performance for determinism/accuracy when testing ``motion_vectors``.
PhysX's default TGS solver settings produce noisy per-step velocities (see the "TGS solver ... may
cause noisy velocities" warning logged by ``physx_manager``), and ``motion_vectors`` encodes velocity
directly. That noise differs run-to-run, making golden-image comparisons for this AOV flaky on CI.
Applies to both PhysX backends (``"physx"`` and ``"ovphysx"``, which share the same underlying PhysX
solver). No-op for any other ``(physics_backend, data_type)`` combination.
Args:
env_cfg: The resolved environment config, exposing ``sim.physics`` as a
:class:`~isaaclab_physx.physics.PhysxCfg` when ``physics_backend == "physx"``, or an
:class:`~isaaclab_ov.physics.OvPhysxCfg` when ``physics_backend == "ovphysx"``.
physics_backend: The physics backend under test (``"physx"``, ``"newton"``, or ``"ovphysx"``).
data_type: The camera data type under test.
"""
if physics_backend not in ("physx", "ovphysx") or data_type != "motion_vectors":
return
env_cfg.sim.physics.enable_enhanced_determinism = True
env_cfg.sim.physics.enable_external_forces_every_iteration = True
def _skip_if_newton_motion_vectors(physics_backend: str, data_type: str) -> None:
"""Skip ``motion_vectors`` golden-image tests running on the Newton physics backend.
Newton is not yet deterministic enough for the ``motion_vectors`` AOV: per-pixel (u, v) offsets
encode sub-step body motion, which varies run-to-run under the Newton solver, so golden-image
comparison is unreliable. No-op for any other ``(physics_backend, data_type)`` combination.
Args:
physics_backend: The physics backend under test (``"physx"``, ``"newton"``, or ``"ovphysx"``).
data_type: The camera data type under test.
"""
if physics_backend == "newton" and data_type == "motion_vectors":
pytest.skip("Newton physics is not deterministic enough for motion_vectors golden-image testing.")
def _physics_preset_name(physics_backend: str) -> str:
"""Translate the historical ``"newton"`` backend label (still used by golden-image
filenames and ``pytest.param`` IDs) to the renamed Hydra preset
``"newton_mjwarp"``. Other labels (``"physx"`` etc.) pass through unchanged.
"""
return "newton_mjwarp" if physics_backend == "newton" else physics_backend
def _physics_preset_name_deformable(physics_backend: str) -> str:
"""Map deformable-test physics labels to Hydra preset names."""
return "newton_mjwarp_vbd_proxy" if physics_backend == "newton" else physics_backend
def _skip_if_physics_preset_unsupported(env_cfg: Any, physics_preset_name: str) -> None:
"""Skip the test when the env does not support the given physics preset.
An env cfg may intentionally support only a subset of the physics presets - newton, physx, ovphysx.
Rather than hard-coding the unsupported-backend list per test, this inspects the resolved
``env_cfg.sim.physics`` :class:`~isaaclab_tasks.utils.PresetCfg` and skips any backend whose
Hydra preset name is not declared as a field.
Args:
env_cfg: The environment config, exposing its physics presets at ``sim.physics``.
physics_preset_name: The physics preset name (e.g. ``"newton_mjwarp"``).
"""
from isaaclab_tasks.utils import PresetCfg
physics_cfg = getattr(getattr(env_cfg, "sim", None), "physics", None)
if not isinstance(physics_cfg, PresetCfg):
return
# Preset variants are declared as annotated fields; aliases such as ``default`` are not.
supported_physics_preset_names = set(getattr(type(physics_cfg), "__dataclass_fields__", {}))
if physics_preset_name not in supported_physics_preset_names:
pytest.skip(f"{type(env_cfg).__name__} does not support '{physics_preset_name}'.")
def _save_comparison_image(img: Image.Image, filename: str) -> str:
"""Save a PIL image under the comparison images directory."""
path = os.path.join(_COMPARISON_IMAGES_DIR, _COMPARISON_IMAGE_SUBDIR, filename)
os.makedirs(os.path.dirname(path), exist_ok=True)
img.save(path, format="PNG")
return path
def _rendering_gif_step_count() -> int | None:
"""Return the GIF capture step count when ``ISAAC_LAB_SAVE_RENDERING_GIF`` enables recording.
Unset, empty, or ``0`` disables recording. A positive integer is used as the step count; any
other non-empty value falls back to 60 steps.
"""
raw = os.environ.get("ISAAC_LAB_SAVE_RENDERING_GIF")
if raw is None:
return None
stripped = raw.strip()
if stripped == "" or stripped == "0":
return None
try:
steps = int(stripped)
except ValueError:
return 60
return steps if steps > 0 else None
def _camera_outputs_to_pil_image(camera_outputs: dict[str, ProxyArray]) -> Image.Image:
"""Convert camera AOVs to an RGB PIL image using the same display path as golden validation."""
assert len(camera_outputs) > 0, "No camera outputs available for GIF capture."
data_type, output = next(iter(camera_outputs.items()))
tensor = output if isinstance(output, torch.Tensor) else output.torch
condition = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor))
corrected = torch.where(condition, torch.zeros_like(tensor), tensor)
normalized = normalize_camera_output_for_display(corrected, data_type)
grid = make_camera_output_grid(normalized)
ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
return Image.fromarray(ndarr).convert("RGB")
def save_rendering_gif(
frames: list[Image.Image],
test_name: str,
physics_backend: str,
renderer: str,
data_type: str,
) -> str:
"""Write captured camera frames as a GIF in the current working directory."""
if not frames:
raise ValueError("Cannot write a rendering GIF with no captured frames.")
safe_test_name = test_name.replace("/", "_")
out_path = os.path.join(
os.getcwd(),
f"{safe_test_name}-{physics_backend}-{renderer}-{data_type}.gif",
)
frames[0].save(
out_path,
format="GIF",
save_all=True,
append_images=frames[1:],
duration=50,
loop=0,
)
logger.info("[ISAAC_LAB_SAVE_RENDERING_GIF] wrote %s (%d frames)", out_path, len(frames))
return out_path
def _format_bcompare_command(actual_path: str, golden_path: str) -> str:
"""Build a shell command that opens actual and golden images in Beyond Compare."""
return f"bcompare \\\n {actual_path} \\\n {golden_path}"
def generate_html_report(comparison_scores: list[dict], report_filename: str) -> None:
"""Generate and save an HTML report of comparison scores."""
if not comparison_scores:
return
os.makedirs(_COMPARISON_IMAGES_DIR, exist_ok=True)
report_path = os.path.join(_COMPARISON_IMAGES_DIR, report_filename)
sorted_scores = sorted(
comparison_scores, key=lambda entry: (0 if entry.get("xfail_reason") else 1, -entry["diff_pct"])
)
rows = []
for entry in sorted_scores:
xfail_reason = entry.get("xfail_reason") or ""
if xfail_reason:
if entry.get("xfail_observed", not entry["passed"]):
status_class = "unreliable"
status_text = "UNRELIABLE (XFAIL)"
else:
status_class = "xpass"
status_text = "XPASS (REVIEW XFAIL)"
else:
status_class = "pass" if entry["passed"] else "fail"
status_text = status_class.upper()
reason = escape(xfail_reason)
actual_img_html = ""
golden_img_html = ""
compare_html = ""
if entry.get("img_result_path"):
actual_fname = os.path.relpath(entry["img_result_path"], _COMPARISON_IMAGES_DIR)
golden_fname = os.path.relpath(entry["img_golden_path"], _COMPARISON_IMAGES_DIR)
actual_img_html = f'<a href="{actual_fname}"><img src="{actual_fname}" width="120" loading="lazy"></a>'
golden_img_html = f'<a href="{golden_fname}"><img src="{golden_fname}" width="120" loading="lazy"></a>'
compare_cmd = _format_bcompare_command(actual_fname, golden_fname)
compare_html = (
'<div class="compare-cmd-wrap">'
f'<code class="compare-cmd">{compare_cmd}</code>'
'<button type="button" class="copy-btn" title="Copy command" aria-label="Copy command"'
f' onclick="copyCompareCmd(this)">{_COPY_ICON_SVG}{_CHECK_ICON_SVG}</button>'
"</div>"
)
ssim_checked = entry.get("ssim_checked", True)
ssim_cell_class = "" if ssim_checked else ' class="ssim-disabled"'
entry_ssim_threshold = entry.get("ssim_threshold", _SSIM_THRESHOLD)
ssim_threshold_cell = f"{entry_ssim_threshold:.4f}" if ssim_checked else "N/A"
ssim_title = "" if ssim_checked else ' title="SSIM gate disabled for this data type; score is informational."'
rows.append(
f'<tr class="{status_class}">'
f"<td>{entry['test']}</td>"
f"<td>{entry['backend']}</td>"
f"<td>{entry['renderer']}</td>"
f"<td>{entry.get('ovstage_variant', 'No')}</td>"
f"<td>{entry['aov']}</td>"
f"<td>{entry['diff_pct']:.2f}</td>"
f"<td>{entry['threshold']:.1f}</td>"
f"<td{ssim_cell_class}{ssim_title}>{entry['ssim']:.4f}</td>"
f"<td{ssim_cell_class}{ssim_title}>{ssim_threshold_cell}</td>"
f'<td class="status-{status_class}">{status_text}</td>'
f"<td>{reason}</td>"
f"<td>{actual_img_html}</td>"
f"<td>{golden_img_html}</td>"
f'<td class="compare-cell">{compare_html}</td>'
"</tr>"
)
report_html = (
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
'<meta charset="utf-8">\n'
"<title>Rendering Correctness - Image Comparison Report</title>\n"
"<style>\n"
" body { font-family: sans-serif; font-size: 13px; margin: 16px; }\n"
" h1 { font-size: 1.3em; margin-bottom: 4px; }\n"
" p { margin-top: 4px; color: #555; }\n"
" table { border-collapse: collapse; width: 100%; }\n"
" th, td { border: 1px solid #ccc; padding: 4px 8px; text-align: left; vertical-align: middle; }\n"
" th { background: #f0f0f0; white-space: nowrap; }\n"
" tr.fail { background: #fff0f0; }\n"
" tr.unreliable { background: #fff8e1; }\n"
" tr.xpass { background: #eef5ff; }\n"
" tr.pass:hover, tr.fail:hover, tr.unreliable:hover, tr.xpass:hover { filter: brightness(0.96); }\n"
" .status-pass { color: #2a7a2a; font-weight: bold; }\n"
" .status-fail { color: #cc0000; font-weight: bold; }\n"
" .status-unreliable { color: #a15c00; font-weight: bold; }\n"
" .status-xpass { color: #0969da; font-weight: bold; }\n"
" .ssim-disabled { color: #999; font-style: italic; }\n"
" img { display: block; max-width: 120px; height: auto; }\n"
" .compare-cell { max-width: 420px; }\n"
" .compare-cmd-wrap { position: relative; }\n"
" .compare-cmd { display: block; font-size: 11px; white-space: pre-wrap; word-break: break-all;"
" background: #f8f8f8; padding: 4px 28px 4px 6px; border: 1px solid #ddd; border-radius: 3px;"
" user-select: all; }\n"
" .copy-btn { position: absolute; top: 4px; right: 4px; width: 22px; height: 22px; padding: 0;"
" border: none; border-radius: 4px; background: transparent; color: #666; cursor: pointer; }\n"
" .copy-btn:hover { background: #e8e8e8; color: #333; }\n"
" .copy-btn svg { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"
" width: 14px; height: 14px; }\n"
" .copy-btn .check-icon { display: none; }\n"
" .copy-btn.copied .copy-icon { display: none; }\n"
" .copy-btn.copied .check-icon { display: block; }\n"
"</style>\n"
"<script>\n"
"function copyCompareCmd(btn) {\n"
" const text = btn.previousElementSibling.textContent;\n"
" navigator.clipboard.writeText(text).then(() => {\n"
" btn.classList.add('copied');\n"
" btn.title = 'Copied!';\n"
" setTimeout(() => {\n"
" btn.classList.remove('copied');\n"
" btn.title = 'Copy command';\n"
" }, 1500);\n"
" });\n"
"}\n"
"</script>\n"
"</head>\n"
"<body>\n"
"<h1>Rendering Correctness - Image Comparison Report</h1>\n"
f"<p>Sorted by PixelDiff % (desc) - {len(sorted_scores)} total.</p>\n"
"<table>\n"
"<thead><tr>"
"<th>Test</th>"
"<th>Backend</th>"
"<th>Renderer</th>"
"<th>OVStage</th>"
"<th>AOV</th>"
"<th>PixelDiff %</th>"
"<th>PixelDiff Threshold %</th>"
"<th>SSIM</th>"
"<th>SSIM Threshold</th>"
"<th>Status</th>"
"<th>Reason</th>"
"<th>ACTUAL</th>"
"<th>GOLDEN</th>"
"<th>Beyond Compare Command</th>"
"</tr></thead>\n"
"<tbody>\n" + "\n".join(rows) + "\n</tbody>\n</table>\n"
f"<p>Generated: {datetime.now().astimezone().isoformat(timespec='seconds')}.</p>\n"
"</body>\n"
"</html>\n"
)
with open(report_path, "w", encoding="utf-8") as file:
file.write(report_html)
def attach_comparison_properties(
request: pytest.FixtureRequest, comparison_scores: list[dict], initial_count: int
) -> None:
"""Annotate expected HTML outcomes and attach comparison properties to JUnit XML."""
xfail_marker = request.node.get_closest_marker("xfail")
xfail_reason = xfail_marker.kwargs.get("reason") if xfail_marker is not None else None
entries = comparison_scores[initial_count:]
xfail_observed = any(not entry["passed"] for entry in entries)
for entry in entries:
if xfail_reason:
entry["xfail_reason"] = xfail_reason
entry["xfail_observed"] = xfail_observed
label = f"{entry['backend']}-{entry['renderer']}-{entry['aov']}"
request.node.user_properties.append((f"diff_pct:{label}", f"{entry['diff_pct']:.2f}"))
ssim_value = f"{entry['ssim']:.4f}" if entry.get("ssim_checked", True) else f"{entry['ssim']:.4f} (N/A)"
request.node.user_properties.append((f"ssim:{label}", ssim_value))
request.node.user_properties.append((f"threshold:{label}", f"{entry['threshold']:.1f}"))
if entry.get("img_result_path"):
request.node.user_properties.append((f"img_result:{label}", entry["img_result_path"]))
request.node.user_properties.append((f"img_golden:{label}", entry["img_golden_path"]))
def make_determinism_fixture():
"""Create an autouse fixture that enables determinism for each test."""
@pytest.fixture(autouse=True)
def _determinism_fixture():
"""Enable determinism for each test."""
from isaaclab.utils.seed import configure_seed
configure_seed(42, torch_deterministic=True)
yield
from isaaclab.sim import SimulationContext
SimulationContext.clear_instance()
return _determinism_fixture
def make_generate_html_report_fixture(comparison_scores: list[dict], report_filename: str):
"""Create a session fixture that writes the HTML report for one module.
Args:
comparison_scores: Module-local comparison score storage.
report_filename: Output report filename.
"""
@pytest.fixture(scope="session", autouse=True)
def _generate_html_report():
"""Generate an HTML comparison report after all tests in the session complete."""
yield
generate_html_report(comparison_scores, report_filename)
return _generate_html_report
def make_attach_comparison_properties_fixture(comparison_scores: list[dict]):
"""Create a fixture that annotates HTML outcomes and attaches JUnit properties.
Args:
comparison_scores: Module-local comparison score storage.
"""
@pytest.fixture(autouse=True)
def _attach_comparison_properties(request):
"""Annotate expected HTML outcomes and attach image-comparison properties."""
initial_count = len(comparison_scores)
yield
# Function-scoped teardown runs before the session-scoped HTML report is generated.
attach_comparison_properties(request, comparison_scores, initial_count)
return _attach_comparison_properties
def make_require_ovlibs_install_fixture():
"""Create an autouse fixture that fails fast when OV libraries are required but not installed.
Only parametrized cases with ``renderer == "ovrtx_renderer"`` or ``physics_backend == "ovphysx"`` are checked.
Install with ``./isaaclab.sh -i 'ov[all]'`` (or the equivalent in your environment).
"""
@pytest.fixture(autouse=True)
def _require_ovlibs_install(request, monkeypatch: pytest.MonkeyPatch):
# TODO: Remove once usd-core>=26.5 is the minimum - that release fixes the race condition.
# Limit OpenUSD's work-thread pool to one thread to avoid race condition in usd-core<26.5
monkeypatch.setenv("PXR_WORK_THREAD_LIMIT", "1")
callspec = getattr(request.node, "callspec", None)
if callspec is None:
return
if callspec.params.get("renderer") == "ovrtx_renderer":
try:
import ovrtx
print(f"ovrtx version: {ovrtx.__version__}")
except ImportError as exc:
pytest.fail(
"Kitless OVRTX rendering tests require the optional dependency ov[ovrtx]. "
"Install with: ./isaaclab.sh -i 'ov[ovrtx]'\n"
f"ImportError: {exc}"
)
if callspec.params.get("physics_backend") == "ovphysx":
try:
import ovphysx
print(f"ovphysx version: {ovphysx.__version__}")