Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitmodules
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[submodule "submodules/IsaacLab-Arena"]
path = submodules/IsaacLab-Arena
url = git@github.com:isaac-sim/IsaacLab-Arena.git
url = https://github.com/isaac-sim/IsaacLab-Arena.git
branch = main
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,14 @@ Choose **one** installation method: [Docker (recommended)](#docker-installation-
Clone the repository with its nested Isaac Lab-Arena and Isaac Lab submodules, then pull the example datasets:
Comment thread
bokalnv marked this conversation as resolved.
Resolved

```bash
git clone --recurse-submodules git@github.com:isaac-sim/AutoData.git
git clone --recurse-submodules https://github.com/isaac-sim/AutoData.git
cd AutoData
git lfs install
git lfs pull
```

Isaac Lab-Arena's own submodules use SSH URLs, so the recursive clone needs an SSH key for GitHub.

#### Docker installation (recommended)

This method requires [Docker](https://docs.docker.com/engine/install/), the
Expand Down
10 changes: 8 additions & 2 deletions autodata_metrics/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ def read_run(
return result, None, warnings
text = _read_text(attempts_path)
attempts = None
if text is not None:
if text is None:
warnings.append(f"{attempts_path} does not exist")
else:
attempts = [
parse(_json(line, attempts_path), ATTEMPT, f"{attempts_path} line {number}")
for number, line in enumerate(text.splitlines(), start=1)
Expand Down Expand Up @@ -497,7 +499,11 @@ def _not_computed_because(row: Mapping[str, Any], inputs: Mapping[str, Any]) ->
if missing.startswith("source."):
return "needs a --source annotated with --record_metric_inputs"
if missing == "attempts" or missing.startswith("run."):
return "needs --result_file" if inputs["result_file"] is None else "needs --record_metric_inputs"
if inputs["result_file"] is None:
return "needs --result_file"
if inputs["run_id"] is None:
return "needs --record_metric_inputs"
return "needs the run's attempt log" if missing == "attempts" else "needs the result file of a completed run"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a result json is present but misses an optional field, this tells the user to supply the same result file they just provided. Would probably be good here to keep this warning only for a missing or mismatched result.

if missing.startswith("attempts.extras."):
return "not reported by this algorithm"
if missing.startswith(_METRIC_INPUT_KEYS):
Expand Down
11 changes: 6 additions & 5 deletions autodata_metrics/validity.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ def _rotation_errors(poses: np.ndarray) -> np.ndarray:

@check("valid_rotations")
def valid_rotations(episode: Episode, ev: Evidence) -> str | None:
"""Fails an episode with an observed pose rotation that is not a proper rotation, a root quaternion that is not
unit, or a pose array not shaped ``(steps, 4, 4)`` or ``(steps, 7)``.
"""Fails an episode with an observed pose array not shaped ``(steps, 4, 4)`` or a root pose array not shaped
``(steps, 7)``. Also fails an episode with an observed pose rotation that is not proper, or a root quaternion
that is not unit, by more than :data:`ROTATION_TOLERANCE`.

Both tests hold for either quaternion order, so the check needs no convention.
"""
Expand Down Expand Up @@ -147,7 +148,7 @@ def one_frame_per_step(episode: Episode, ev: Evidence) -> str | None:

@check("no_black_frames", group="image")
def no_black_frames(episode: Episode, ev: Evidence) -> str | None:
"""Fails an episode with a camera frame whose mean pixel value is below :data:`BLACK_FRAME_MEAN`."""
"""Fails an episode with a camera frame whose mean pixel value, from 0 to 255, is below :data:`BLACK_FRAME_MEAN`."""
for path, dataset in _image_streams(episode, ev).items():
for start in range(0, len(dataset), FRAME_CHUNK):
means = dataset[start : start + FRAME_CHUNK].mean(axis=(1, 2, 3))
Expand All @@ -158,7 +159,7 @@ def no_black_frames(episode: Episode, ev: Evidence) -> str | None:

@check("no_frozen_frames", group="image", requires=["env_args.sim_args.dt", "env_args.sim_args.decimation"])
def no_frozen_frames(episode: Episode, ev: Evidence) -> str | None:
"""Fails an episode whose camera repeats one frame for :data:`FROZEN_SECONDS`; needs the recorded control step."""
"""Fails an episode whose camera repeats one frame for :data:`FROZEN_SECONDS` seconds; needs the control step."""
streams = _image_streams(episode, ev)
step = ev.env_args["sim_args"]["dt"] * ev.env_args["sim_args"]["decimation"]
frozen_frames = max(2, math.ceil(FROZEN_SECONDS / step))
Expand Down Expand Up @@ -344,7 +345,7 @@ def motion_smoothness(ev: Evidence) -> Value:
baseline=True,
)
def joint_limit_ratio(ev: Evidence) -> Value:
"""Share of episodes that reach ``NEAR_LIMIT`` of a datasheet velocity or acceleration limit."""
"""Share of episodes in which a joint reaches :data:`NEAR_LIMIT` of its datasheet limit, for each kind of limit."""
joints, datasheet = ev.entry["joints"], ev.entry.get("hardware_limits", {})
limits = {kind: _datasheet(joints["names"], datasheet.get(kind, {})) for kind in ("velocity", "acceleration")}
limits = {kind: limit for kind, limit in limits.items() if np.isfinite(limit).any()}
Expand Down
2 changes: 1 addition & 1 deletion autodata_metrics/viability.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def demos_per_gpu_hour(ev: Evidence) -> Value:
version=2,
)
def time_to_dataset(ev: Evidence) -> Value:
"""Wall time of the automated steps, each process timed from its start: annotating the source and generating.
"""Wall time of generating and, when ``--source`` records it, of annotating the source, each timed from its start.

Annotation that was manual, or recorded without its mode, is reported in ``uncounted_annotation_s`` instead.
"""
Expand Down
16 changes: 15 additions & 1 deletion autodata_tests/metrics/test_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ def test_console_summary_marks_the_gate_and_says_how_to_compute_the_rest(tmp_pat
"rate": _spec("rate", lambda ev: Value(0.25, n=4)),
"held": _spec("held", lambda ev: Value(1.0, n=1), ("step_success",)),
"planned": _spec("planned", lambda ev: Value(1.0, n=1), ("attempts.extras.planning_time_s",)),
"timed": _spec("timed", lambda ev: Value(1.0, n=1), ("run.generation_time_s",)),
}
report = build_report(_dataset(tmp_path / "d.hdf5"), metrics=metrics)
gate = tmp_path / "gate.yaml"
Expand All @@ -207,7 +208,20 @@ def test_console_summary_marks_the_gate_and_says_how_to_compute_the_rest(tmp_pat
assert "gate failed on 1 of 1" in summary
assert re.search(r"✗ rate +25% +4 samples", summary)
assert "needs --record_metric_inputs: held" in summary
assert "needs --result_file: planned" in summary
assert "needs --result_file: planned, timed" in summary

plain_result = tmp_path / "plain.json"
plain_result.write_text(json.dumps({"num_success": 1, "num_attempts": 1}))
summary = format_report(build_report(str(tmp_path / "d.hdf5"), result_file=str(plain_result), metrics=metrics))

assert "needs --record_metric_inputs: held, planned, timed" in summary

dataset = _dataset(tmp_path / "run.hdf5", entry={"run_id": "run-b", "exported_episodes": 1})
summary = format_report(build_report(dataset, result_file=_run(tmp_path, "run-a"), metrics=metrics))

assert "needs the run's attempt log: planned" in summary
assert "needs the result file of a completed run: timed" in summary
assert "result.run-b.attempts.jsonl does not exist" in summary


def test_degenerate_inputs_are_reported_without_breaking_the_summary_or_json(tmp_path):
Expand Down
23 changes: 15 additions & 8 deletions autodata_tests/utils/test_generation_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,28 @@
"""Tests for structured data-generation result files."""

import json
import os
import stat
from pathlib import Path

from autodata_utils.generation_result import AttemptLog, attempts_file_for, code_revision, write_generation_result


def test_write_generation_result_writes_completed_stats_atomically(tmp_path):
def test_write_generation_result_writes_completed_stats_atomically_with_the_umask_mode(tmp_path):
result_file = tmp_path / "results" / "generation_result.json"

write_generation_result(
result_file=str(result_file),
algorithm="mimicgen",
requested_trials=10,
stats={"num_success": 8, "num_failures": 2, "num_attempts": 10},
)

umask = os.umask(0o007)
try:
write_generation_result(
result_file=str(result_file),
algorithm="mimicgen",
requested_trials=10,
stats={"num_success": 8, "num_failures": 2, "num_attempts": 10},
)
finally:
os.umask(umask)

assert stat.S_IMODE(result_file.stat().st_mode) == 0o660
with result_file.open(encoding="utf-8") as result_handle:
result = json.load(result_handle)
assert result == {
Expand Down
3 changes: 3 additions & 0 deletions autodata_tests/utils/test_validate_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@ def test_main_returns_zero_for_valid_dataset(tmp_path: Path) -> None:

dataset_path = tmp_path / "valid.hdf5"
_create_dataset(dataset_path)
report_file = tmp_path / "reports" / "report.json"

assert validate_dataset.main([str(dataset_path)]) == 0
assert validate_dataset.main([str(dataset_path), "--report"]) == 0
assert validate_dataset.main([str(dataset_path), "--report", "--report_file", str(report_file)]) == 0
assert report_file.is_file()


def test_main_returns_nonzero_for_invalid_dataset_by_default(tmp_path: Path) -> None:
Expand Down
1 change: 0 additions & 1 deletion autodata_tests/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,6 @@ def _export_benchmark_files(source_dir: str, name: str) -> None:
for file_name in os.listdir(source_dir):
path = os.path.join(source_dir, file_name)
if os.path.isfile(path) and not file_name.endswith(".hdf5"):
# copyfile, not copy2: the result file is written 0600, and another user may upload the copy.
shutil.copyfile(path, os.path.join(export_dir, file_name))


Expand Down
12 changes: 6 additions & 6 deletions autodata_utils/generation_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import os
import shutil
import subprocess
import tempfile
import uuid
from collections.abc import Mapping
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -60,19 +60,19 @@ def write_generation_result(
if run_metadata is not None:
result["run"] = dict(run_metadata)

file_descriptor, temporary_file_name = tempfile.mkstemp(
prefix=f".{result_path.name}.", suffix=".tmp", dir=result_path.parent, text=True
)
# The result follows the umask, like the dataset and the attempt log, so that other users can read it.
temporary_path = result_path.with_name(f".{result_path.name}.{uuid.uuid4().hex}.tmp")
file_descriptor = os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666)
try:
with os.fdopen(file_descriptor, "w", encoding="utf-8") as result_handle:
json.dump(result, result_handle, indent=2, sort_keys=True)
result_handle.write("\n")
result_handle.flush()
os.fsync(result_handle.fileno())
os.replace(temporary_file_name, result_path)
os.replace(temporary_path, result_path)
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink(temporary_file_name)
os.unlink(temporary_path)


def attempts_file_for(result_file: str, run_id: str) -> str:
Expand Down
47 changes: 37 additions & 10 deletions docs/_ext/autodata_doc_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import ast
import re
from contextlib import suppress
from pathlib import Path
from textwrap import indent
from typing import Any
Expand Down Expand Up @@ -120,29 +121,54 @@ def run(self) -> list[nodes.Node]:
return self.parse_text_to_nodes(_runtime_tabs(docker, uv))


def _module_constants(module: ast.Module) -> dict[str, Any]:
"""Each module-level name that a plain assignment gives a literal value, with that value."""
constants = {}
for node in module.body:
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
with suppress(ValueError):
constants[node.targets[0].id] = ast.literal_eval(node.value)
return constants


def _role_as_literal(constants: dict[str, Any], match: re.Match) -> str:
role, target = match.group("role"), match.group("target")
if role == "data" and target in constants:
return f"``{target} = {constants[target]!r}``"
return f"``{target}``"


def _declarations(app: Sphinx, decorator: str) -> list[tuple[str, dict[str, Any], str]]:
"""Name, options and summary line of every function in ``autodata_metrics/`` registered with ``decorator``.
"""Name, options and summary of every function in ``autodata_metrics/`` registered with ``decorator``.

The declarations are parsed instead of imported, so the docs build needs none of the metrics' dependencies and
the tables cannot drift from the code. In the summary, Sphinx roles become literals that need no reference
target, and pipes are escaped so they do not read as substitutions.
the tables cannot drift from the code. The summary is the first paragraph of the docstring. In it, a ``:data:``
role that names a literal constant of the same module shows the constant's value, other Sphinx roles become
literals that need no reference target, and pipes are escaped so they do not read as substitutions.
"""
found = []
for path in sorted((Path(app.confdir).parent / "autodata_metrics").glob("*.py")):
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
module = ast.parse(path.read_text(encoding="utf-8"))
constants = _module_constants(module)
for node in ast.walk(module):
if not isinstance(node, ast.FunctionDef):
continue
for call in node.decorator_list:
if isinstance(call, ast.Call) and getattr(call.func, "id", None) == decorator:
options = {keyword.arg: ast.literal_eval(keyword.value) for keyword in call.keywords}
summary = (ast.get_docstring(node) or "").split("\n")[0]
summary = re.sub(r":\w+:`~?([^`]+)`", r"``\1``", summary).replace("|", "\\|")
summary = " ".join((ast.get_docstring(node) or "").split("\n\n")[0].split())
summary = re.sub(
r":(?P<role>\w+):`~?(?P<target>[^`]+)`",
lambda match: _role_as_literal(constants, match),
summary,
).replace("|", "\\|")
found.append((ast.literal_eval(call.args[0]), options, summary))
return found


def _list_table(widths: str, header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
lines = [".. list-table::", " :header-rows: 1", f" :widths: {widths}", ""]
def _list_table(widths: str, header: tuple[str, ...], rows: list[tuple[str, ...]], css_class: str = "") -> str:
lines = [".. list-table::", " :header-rows: 1", f" :widths: {widths}"]
lines += [f" :class: {css_class}", ""] if css_class else [""]
lines += [" * - " + "\n - ".join(row) for row in [header, *rows]]
return "\n".join(lines) + "\n"

Expand All @@ -156,12 +182,13 @@ def autodata_metrics_table(app: Sphinx, _: Any, source: list[str]) -> None:
f"``{name}``",
options["area"],
options["unit"].replace("|", "\\|"),
", ".join(f"``{key}``" for key in options.get("requires", ())) or "none",
summary,
", ".join(f"``{key}``" for key in options.get("requires", ())) or "none",
)
for name, options, summary in sorted(_declarations(app, "metric"), key=lambda item: (item[1]["area"], item[0]))
]
table = _list_table("20 12 14 26 28", ("Metric", "Area", "Unit", "Requires", "Definition"), rows)
header = ("Metric", "Area", "Unit", "Definition", "Requires")
table = _list_table("20 12 14 28 26", header, rows, css_class="autodata-metrics")
source[0] = source[0].replace(":autodata_metrics_table:", table)


Expand Down
6 changes: 6 additions & 0 deletions docs/_static/custom.css
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ table.gallery img {
border-radius: 4px;
}

/* Metric names and evidence keys are long literals. Let them wrap so that the definitions stay in view. */
table.autodata-metrics code.literal span.pre {
white-space: normal;
overflow-wrap: anywhere;
}

/* Remove border and box-shadow from gallery table */
table.gallery,
table.gallery td,
Expand Down
6 changes: 3 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@

autodata_docs_config = {
"released": released,
"internal_git_url": "git@github.com:isaac-sim/AutoData.git",
"external_git_url": "UNDECIDED",
"internal_git_url": "https://github.com/isaac-sim/AutoData.git",
"external_git_url": "https://github.com/isaac-sim/AutoData.git",
"internal_code_link_base_url": "https://github.com/isaac-sim/AutoData/blob/main",
"external_code_link_base_url": "UNDECIDED",
"external_code_link_base_url": "https://github.com/isaac-sim/AutoData/blob/main",
}
2 changes: 2 additions & 0 deletions docs/pages/quickstart/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ Isaac Lab and Isaac Lab-Arena are nested git submodules, so clone recursively:

:autodata_git_clone_code_block:

Isaac Lab-Arena's own submodules use SSH URLs, so the recursive clone needs an SSH key for GitHub.

If you already cloned without ``--recurse-submodules``, run:

.. code-block:: bash
Expand Down
3 changes: 3 additions & 0 deletions docs/pages/quickstart/support_matrix.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ Isaac Lab or Isaac Lab-Arena revisions.
* - Conda installation
- Optional: Python 3.12, conda, uv >= 0.12.21, CMake, and a C++ compiler;
``conda_installer.sh`` installs Arena's locked environment. See :doc:`installation`.
* - Metrics only
- Python 3.12 with h5py, NumPy, and PyYAML; no GPU, Isaac Sim, or submodules.
See :doc:`../references/metrics`.
* - Isaac Sim
- ``isaacsim==6.1.0.0`` for native installs; Docker reuses Sim from ``nvcr.io/nvidia/isaac-sim:6.1.0``.
* - Isaac Lab
Expand Down
Loading
Loading