diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 9156d1b..be8cb95 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -8,7 +8,7 @@ on: jobs: lint: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 strategy: matrix: python-version: ["3.8", "3.9"] @@ -55,7 +55,7 @@ jobs: continue-on-error: true type-check: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@v4 @@ -76,7 +76,7 @@ jobs: continue-on-error: true markdown-lint: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@v4 @@ -89,7 +89,7 @@ jobs: continue-on-error: true check-dependencies: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@v4 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index aa6b9e9..22b1d11 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,7 +9,7 @@ on: jobs: syntax-check: name: Python Syntax Check - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 strategy: matrix: python-version: ["3.8", "3.9"] @@ -30,7 +30,7 @@ jobs: import-check: name: Import Check - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@v4 @@ -54,7 +54,7 @@ jobs: # This is a placeholder for future integration with self-hosted runners integration-tests: name: Integration Tests (Placeholder) - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@v4 @@ -74,7 +74,7 @@ jobs: documentation-build: name: Check Documentation - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@v4 diff --git a/README.md b/README.md index a743776..595f1a6 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ - [Deep Dive by Module](#deep-dive-by-module) - [SimEngine - Photorealistic Closed-Loop Simulation](#simengine---photorealistic-closed-loop-simulation) - [AlgEngine - End-to-End Model Training \& Fine-Tuning](#algengine---end-to-end-model-training--fine-tuning) + - [Behavior World Model (BWM)](#behavior-world-model-bwm) - [Scene Reconstruction - 3D Gaussian Splatting-based method, MTGS](#scene-reconstruction---3d-gaussian-splatting-based-method-mtgs) - [Citation](#citation) - [Contributing](#contributing) @@ -138,13 +139,14 @@ Zero disengagements in 200 km on-road testing on a mass-produced ADAS platform. ## System Architecture -WorldEngine consists of two tightly coupled subsystems: +WorldEngine consists of three tightly coupled core modules: | Module | Function | Core Technology | |--------|----------|----------------| -| **[SimEngine](docs/WE_simulation.md)** | Closed-loop simulation with ego & agents | Hydra, Ray, rendering | -| **[AlgEngine](docs/AlgEngine.md)** | End-to-end model training & evaluation | MMDetection3D, UniAD/VADv2/HydraMDP | +| **[SimEngine](docs/simengine_usage.md)** | Closed-loop simulation with ego & agents | Hydra, Ray, rendering | +| **[AlgEngine](docs/algengine_usage.md)** | End-to-end model training & evaluation | MMDetection3D, UniAD/VADv2/HydraMDP | +| **[Behavior World Model](docs/bwm_usage.md)** | Behavior-driven scenario generation and publication | PyTorch, diffusion modeling, Hydra | ## Roadmap @@ -157,7 +159,7 @@ WorldEngine consists of two tightly coupled subsystems: - [x] Open-source release (code, data, early pre-trained models) - [x] arXiv preprint - [x] Stable pre-trained models -- [ ] Behavior World Model integration +- [x] Behavior World Model integration ## Getting Started @@ -168,15 +170,16 @@ WorldEngine provides comprehensive guides for each stage of your workflow: | Guide | Purpose | Key Topics | |-------|---------|------------| -| **[Installation](docs/installation.md)** | Set up both conda environments | Two-environment setup (simengine + algengine), dependencies, troubleshooting | +| **[Installation](docs/installation.md)** | Set up module environments | SimEngine, AlgEngine, and BWM environments, dependencies, troubleshooting | | **[Data Organization](docs/data_organization.md)** | Prepare datasets and checkpoints | Data structure, Hugging Face/ModelScope downloads, symlinks | | **[Quick Start](docs/quick_start.md)** | Run your first experiment in 5 min | Quick test tutorial, understanding results, complete pipeline | | **[SimEngine Usage](docs/simengine_usage.md)** | Master closed-loop simulation | Rollout scripts, distributed testing, configuration, metrics | | **[AlgEngine Usage](docs/algengine_usage.md)** | Train and fine-tune models | Training from scratch, evaluation, rare case extraction, RL fine-tuning | +| **[BWM Usage](docs/bwm_usage.md)** | Generate augmented scenarios | Layered config, inference, quality gates, SimEngine publication | ### Installation -WorldEngine requires **two separate conda environments** due to different Python requirements. +WorldEngine uses **three separate conda environments** for SimEngine, AlgEngine, and BWM. **Full installation guide:** [docs/installation.md](docs/installation.md) @@ -231,6 +234,18 @@ Learn how to train models, extract rare cases, and fine-tune: **[AlgEngine Usage Guide](docs/algengine_usage.md)** +#### Behavior World Model (BWM) + +Generate behaviorally varied scenarios from selected nuPlan scenes and +publish them for SimEngine: + +- **Layered configuration** shared with AlgEngine SceneFilter selections +- **Pre-trained inference** in the dedicated `bwm` environment +- **Quality-gated generation** using trajectory, collision, and drivable-area checks +- **Atomic publication** to `data/sim_engine/scenarios/augmented/` + +**[BWM Usage Guide](docs/bwm_usage.md)** + #### Scene Reconstruction - 3D Gaussian Splatting-based method, MTGS WorldEngine's simulation environments are powered by 3D Gaussian Splatting (MTGS): diff --git a/docs/algengine_usage.md b/docs/algengine_usage.md index 427f513..c941be0 100644 --- a/docs/algengine_usage.md +++ b/docs/algengine_usage.md @@ -351,143 +351,216 @@ head -20 configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pc ## Fine-Tuning -Fine-tune a trained model on rare cases using reinforcement learning. +Choose a fine-tuning config for the data you want to use: + +| Config suffix | Training data | Preparation | +|---------------|---------------|-------------| +| `_rlft_rare_log` | Original rare-case logs | Extract rare-case SceneFilters; no new rollout is required. | +| `_rlft_rare_rollout` | Exported SimEngine rollouts | Run rollout, verify export, and set the exported dataset names. | +| `_rlft_rare_rollout_bwm` | Exported rollouts from BWM-generated scenarios, optionally mixed with original-scenario rollouts | Generate and publish BWM scenarios, run NR rollout, and set the exported dataset names. | + +The example below follows the rollout-based path. Set the repository root +once; all commands use it explicitly: + +```bash +export WORLDENGINE_ROOT=/path/to/WorldEngine +``` ### Prerequisites: Generating Rollouts with SimEngine -**Important:** Rare case extraction and Rollout data must be generated by SimEngine before fine-tuning. This involves: - -1. **Convert nuPlan Data to SimEngine Format** — convert rare case scenarios to SimEngine scenario format: - ```bash - conda activate simengine - - python projects/SimEngine/worldengine/utils/dataset_utils/nuplan/digitaltwin_nuplan_converter_navsim_filter.py \ - --navsim-filters $ALGENGINE_ROOT/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_collision.yaml \ - $ALGENGINE_ROOT/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yaml \ - $ALGENGINE_ROOT/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_off_road.yaml \ - --out-dir data/sim_engine/scenarios/original/navtrain_vadv2_50pct_rare \ - --num-processes 8 - ``` - **Output:** `data/sim_engine/scenarios/original/navtrain_vadv2_50pct_rare/all_scenarios.pkl` - - For full parameter reference, see [SimEngine: Convert nuPlan Data](simengine_usage.md#convert-nuplan-data-to-simengine-format). - -2. **Run SimEngine Rollout** to generate trajectory data: - ```bash - # Multi-GPU distributed rollout (recommended for large datasets) - export WORLDENGINE_ROOT=/path/to/WorldEngine - cd projects/SimEngine - bash scripts/run_ray_distributed_rollout.sh \ - $WORLDENGINE_ROOT/projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct.py \ - $WORLDENGINE_ROOT/data/alg_engine/ckpts/e2e_vadv2_50pct_ep8.pth \ - e2e_vadv2_50pct \ - navtrain_vadv2_50pct_rare \ - navtrain - ``` - -3. **Rollout Output** is saved to: - ``` - experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_NR/ - └── WE_output/ - └── openscene_format/ - ├── sensor_blobs/ # Camera images, LiDAR - ├── meta_datas/ # Per-scenario metadata - ├── pdms_pkl/ # Metric pdms pkl - └── all_scenes_pdm_averages_NR.csv - ``` - -4. **Reorganize to AlgEngine Format** (creates `openscene-synthetic` dataset): - ```bash - conda activate simengine - - cd projects/SimEngine - python scripts/export_simulation_data.py \ - --test_path experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_NR \ - --appendix 260406 # Date suffix for versioning, Default None - ``` - - **Output location:** `data/alg_engine/openscene-synthetic/` - -5. **Verify Data Structure:** - ```bash - data/alg_engine/openscene-synthetic/ - ├── sensor_blobs/ # Replayed scenario sensor data - ├── meta_datas/ # Metadata - └── pdms_pkl/ # Metric pdms pkl - ``` - -For detailed SimEngine usage, see [SimEngine Usage Guide](simengine_usage.md#rollout-scripts). +First complete [Rare Case Extraction](#rare-case-extraction) in AlgEngine. +For original scenarios, convert the selected scenes to SimEngine format: -### RL-Based Fine-Tuning +```bash +conda activate simengine +cd "$WORLDENGINE_ROOT" + +python "$WORLDENGINE_ROOT/projects/SimEngine/worldengine/utils/dataset_utils/nuplan/digitaltwin_nuplan_converter_navsim_filter.py" \ + --navsim-filters \ + "$WORLDENGINE_ROOT/projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_collision.yaml" \ + "$WORLDENGINE_ROOT/projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yaml" \ + "$WORLDENGINE_ROOT/projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_off_road.yaml" \ + --out-dir "$WORLDENGINE_ROOT/data/sim_engine/scenarios/original/navtrain_vadv2_50pct_rare" \ + --num-processes 8 +``` + +This writes `all_scenarios.pkl` under the specified output directory. See +[Convert nuPlan Data](simengine_usage.md#convert-nuplan-data-to-simengine-format) +for data and asset overrides. + +For BWM-generated scenarios, use the +[BWM generation and publication workflow](bwm_usage.md#generate-scenarios) +and [Rollouts from BWM Scenarios](simengine_usage.md#rollouts-from-bwm-scenarios) +instead of the original-scenario conversion above. After rollout, both +paths use the same export format and training setup described below. + +For the original-scenario example, run: ```bash -conda activate algengine -cd projects/AlgEngine +# The exporter expects these parent directories to exist. +mkdir -p "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/"{meta_datas,pdms_pkl,sensor_blobs} -# Fine-tune on extracted rare cases (8 GPUs) -./scripts/e2e_dist_train.sh \ - configs/worldengine/e2e_vadv2_50pct_rlft_rare_log.py \ - 8 \ - work_dirs/e2e_vadv2_50pct/epoch_20.pth +bash "$WORLDENGINE_ROOT/projects/SimEngine/scripts/run_ray_distributed_rollout.sh" \ + "$WORLDENGINE_ROOT/projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct.py" \ + "$WORLDENGINE_ROOT/data/alg_engine/ckpts/e2e_vadv2_50pct_ep8.pth" \ + e2e_vadv2_50pct \ + navtrain_vadv2_50pct_rare \ + navtrain ``` -**Arguments:** -1. Config with `_rlft_rare_log` suffix (uses rare case splits) -2. Number of GPUs -3. Base checkpoint to fine-tune from +| Argument | Example value | Controls | +|----------|---------------|----------| +| `model_name` | `e2e_vadv2_50pct` | Experiment directory and exported dataset prefix | +| `data_type` | `navtrain_vadv2_50pct_rare` | Scenario directory and rollout output name | +| `asset_name` | `navtrain` | Asset directory under `data/sim_engine/assets/` | + +The rollout directory is +`$WORLDENGINE_ROOT/experiments/closed_loop_exps//_NR/`. +For this example: + +```text +$WORLDENGINE_ROOT/experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_vadv2_50pct_rare_NR/ +├── split_0/ ... split_7/ +└── WE_output/openscene_format/ + ├── sensor_blobs/ + ├── meta_datas/ + ├── pdms_pkl/ + │ └── plan_idx.csv + └── all_scenes_pdm_averages_NR.csv +``` + +### Verify the Exported Rollout Dataset + +On successful completion, the rollout launcher **automatically merges the +splits and exports the dataset**. Continue with verification; a second +manual export is not required. + +The exported dataset name is +`__NR_`, using the system date when the +export step runs. For example, an export with suffix `261009` produces +`e2e_vadv2_50pct_navtrain_vadv2_50pct_rare_NR_261009`. + +```text +$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/ +├── meta_datas//combined.pkl +├── sensor_blobs// +└── pdms_pkl// + ├── plan_idx.csv + └── _step__scores.pkl +``` + +The three dataset directories are symlinks to the merged rollout output. +The exporter also creates `combined.pkl` with per-frame metadata and +available reward arrays. Keep the source rollout directories available. + +List the actual exported names, then check the one you plan to train on: + +```bash +ls -1 "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/meta_datas/" +# Example only: use the exact dataset name listed above. +DATA_NAME=e2e_vadv2_50pct_navtrain_vadv2_50pct_rare_NR_261009 +test -f "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/meta_datas/$DATA_NAME/combined.pkl" +test -f "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/pdms_pkl/$DATA_NAME/plan_idx.csv" +test -d "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/sensor_blobs/$DATA_NAME" +``` + +For an existing merged rollout that has not been exported, follow +[Manual Export](simengine_usage.md#export-openscene-format-data). The +current exporter refuses existing symlink destinations; repeating an export +with the same name raises `FileExistsError`. ### Fine-Tuning Configuration -The `_rlft_rare_log` config typically includes: +For the original-scenario rollout example, edit +`projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct_rlft_rare_rollout.py`. +Replace its `synthetic_folder_names` placeholders with the exported dataset +names verified above: ```python -# configs/worldengine/e2e_vadv2_50pct_rlft_rare_log.py - -# Use rare case splits -data = dict( - train=dict( - ann_file='merged_infos_navformer/nuplan_openscene_navtrain.pkl', - scenario_filter=[ - 'configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_collision.yaml', - 'configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_off_road.yaml', - 'configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yaml', - ] - ) +# Use your actual export suffix. +synthetic_folder_names = [ + "e2e_vadv2_50pct_navtrain_vadv2_50pct_rare_NR_261009", +] + +# Initial model weights for a new fine-tuning run. +load_from = os.path.join( + WORLDENGINE_ROOT, "data/alg_engine/ckpts/e2e_vadv2_50pct_ep8.pth" ) +``` + +These configs already pass `synthetic_folder_names` to +`data.train.folder_name` and use `NavSimOpenSceneE2EFineTuneSynthetic`. +Each entry is a **dataset directory name**, not an absolute path or a +scenario pickle path. The loader finds matching directories under +`openscene-synthetic/meta_datas`, `sensor_blobs`, and `pdms_pkl`. -# RL training settings -optimizer = dict(type='AdamW', lr=5e-5) # Lower learning rate -total_epochs = 8 # Fewer epochs for fine-tuning +For BWM rollouts, make the same edits in +`e2e_vadv2_50pct_rlft_rare_rollout_bwm.py`, using the actual exported names +of your augmented runs. Include original-scenario exports in the list if +you want to mix both sources; the list can contain one or more datasets. + +Also align `finetune_yaml` with the base scene selections used for generation +and rollout. The dataset skips synthetic samples whose original token is +absent from these filters. See the +[Configuration Guide](config_guide.md#rlft_rare_rollout_bwm) for variant details. + +### RL-Based Fine-Tuning + +After updating the selected config: + +```bash +conda activate algengine +cd "$WORLDENGINE_ROOT/projects/AlgEngine" + +CONFIG=configs/worldengine/e2e_vadv2_50pct_rlft_rare_rollout.py +# For BWM exports, select this instead: +# CONFIG=configs/worldengine/e2e_vadv2_50pct_rlft_rare_rollout_bwm.py + +./scripts/e2e_dist_train.sh "$CONFIG" 8 ``` +The config's `load_from` initializes a new fine-tuning run. The optional +third launcher argument is a **resume checkpoint**, forwarded as +`--resume-from`; use it only to continue an interrupted training run. +For original-log fine-tuning, select `_rlft_rare_log.py` and configure its +`finetune_yaml` directly; it does not consume the exported rollout datasets. + ### Fine-Tuning Output -``` -work_dirs/e2e_vadv2_50pct_rlft_rare_log/ -├── e2e_vadv2_50pct_rlft_rare_log.py +The launcher mirrors the config's path below `configs/` into +`$WORLDENGINE_ROOT/experiments/`, removing the `.py` extension. For the +example above: + +```text +$WORLDENGINE_ROOT/experiments/worldengine/e2e_vadv2_50pct_rlft_rare_rollout/ +├── e2e_vadv2_50pct_rlft_rare_rollout.py ├── logs/ │ └── train.* -├── epoch_1.pth -... └── epoch_8.pth ``` +The supplied rollout configs keep only the latest epoch checkpoint. With +the BWM config selected, the directory name ends in `_rare_rollout_bwm`. + ### Evaluate Fine-Tuned Model +Continue with the same `CONFIG` selected for training: + ```bash -cd projects/AlgEngine +conda activate algengine +cd "$WORLDENGINE_ROOT/projects/AlgEngine" +CONFIG_NAME=$(basename "$CONFIG" .py) +FINETUNE_CKPT="$WORLDENGINE_ROOT/experiments/worldengine/$CONFIG_NAME/epoch_8.pth" + # Open-loop evaluation -./scripts/e2e_dist_eval.sh \ - configs/worldengine/e2e_vadv2_50pct_rlft_rare_log.py \ - work_dirs/e2e_vadv2_50pct_rlft_rare_log/epoch_8.pth \ - 8 +./scripts/e2e_dist_eval.sh "$CONFIG" "$FINETUNE_CKPT" 8 # Closed-loop evaluation -bash scripts/run_ray_distributed_testing.sh \ - $WORLDENGINE_ROOT/projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct_rlft_rare_log.py \ - $WORLDENGINE_ROOT/projects/AlgEngine/work_dirs/e2e_vadv2_50pct_rlft_rare_log/epoch_8.pth \ - e2e_vadv2_50pct_rlft \ +bash "$WORLDENGINE_ROOT/projects/SimEngine/scripts/run_ray_distributed_testing.sh" \ + "$WORLDENGINE_ROOT/projects/AlgEngine/$CONFIG" \ + "$FINETUNE_CKPT" \ + "$CONFIG_NAME" \ navtest_failures \ NR ``` diff --git a/docs/bwm_usage.md b/docs/bwm_usage.md new file mode 100644 index 0000000..3e57801 --- /dev/null +++ b/docs/bwm_usage.md @@ -0,0 +1,581 @@ +# Behavior World Model Usage Guide + +Behavior World Model (BWM) expands selected nuPlan scenes into behaviorally +varied scenarios for SimEngine. The public BWM module is inference-only: +users load the provided checkpoint, generate validated scenario candidates, +and explicitly publish them in the SimEngine scenario format. + +Run all commands below from the WorldEngine repository root. + +## Table of Contents + +- [Prerequisites](#prerequisites) +- [Configuration Model](#configuration-model) +- [Validate Before Generation](#validate-before-generation) +- [Generate Scenarios](#generate-scenarios) +- [Publish for SimEngine](#publish-for-simengine) +- [Output Contract](#output-contract) +- [Scene Quality Filtering](#scene-quality-filtering) +- [Troubleshooting](#troubleshooting) + +## Prerequisites + +Create the `bwm` environment by following the +[Installation Guide](installation.md#environment-3-behavior-world-model-bwm). +Then activate it: + +```bash +conda activate bwm +``` + +Download the [BWM checkpoint](https://huggingface.co/datasets/OpenDriveLab/WorldEngine/blob/main/data/alg_engine/ckpts/nuplan.ckpt) +to `data/alg_engine/ckpts/nuplan.ckpt` under the repository root. +If you downloaded the WorldEngine dataset before this checkpoint was added, +fetch this file separately; you do not need to download the full dataset again. + +BWM uses data shared with the other WorldEngine modules. The default +configuration expects: + +```text +data/ +├── alg_engine/ +│ └── ckpts/ +│ └── nuplan.ckpt +├── raw/ +│ ├── nuplan/ +│ │ └── dataset/ +│ │ ├── maps/ +│ │ └── nuplan-v1.1/ +│ │ ├── trainval/ +│ │ └── sensor_blobs/ +│ └── openscene-v1.1/ +│ └── meta_datas/ +│ ├── trainval/ +│ └── test/ +└── sim_engine/ + └── assets/ + └── navtrain/ + └── assets/ + └── -/ + └── video_scene_dict.pkl +``` + +See [Data Organization](data_organization.md) for the complete repository +layout. If your data lives elsewhere, override the corresponding paths in +your BWM scenario YAML. Relative paths are resolved against the WorldEngine +repository root. + +## Configuration Model + +BWM uses two configuration layers: + +1. `projects/BWM/configs/default.yaml` owns model, runtime, data, staging, and + publication defaults. +2. A file under `projects/BWM/configs/scenarios/` identifies one generation + job and references an AlgEngine SceneFilter YAML. + +The SceneFilter remains the single source of truth for scene membership. It +provides `log_names` and/or `tokens`; do not duplicate those lists in the BWM +scenario YAML. + +Base-scene selection applies these rules: + +| SceneFilter selection | Eligible scenes | +|-----------------------|-----------------| +| Both `log_names` and `tokens` | The log and token must each belong to their respective list. | +| Only `log_names` | Scenes belonging to those logs. | +| Only `tokens` | Scenes with those tokens. | +| Either list explicitly set to `[]` | No scenes. | +| Both fields omitted or `null` | Configuration error. | + +An omitted or `null` field imposes no restriction on that field. The lists +are independent allowlists, not pairs matched by list position. A selected +scene must have `-/video_scene_dict.pkl` under +`digitaltwin_data_root`; scenes without this asset are skipped. Existing +canonical staging outputs are also skipped during generation. + +The included scenario config is: + +```yaml +# projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml +scenario_name: navtrain_50pct_ep_1pct +data_type: navtrain_ep_per1 +scene_filter_path: projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yaml +``` + +To create a new generation job, add a similarly small file: + +```yaml +# projects/BWM/configs/scenarios/my_scenario.yaml +scenario_name: my_scenario +data_type: navtrain +scene_filter_path: projects/AlgEngine/configs/path/to/my_scene_filter.yaml +``` + +Use a safe, unique `scenario_name`. It becomes both the staging directory +name and the published SimEngine scenario directory name. + +### Generation Budgets + +The default config runs two tasks for each selected base scene, in this order: + +| Task | Maximum attempts | Maximum accepted scenarios | +|------|------------------|----------------------------| +| `goal_conditional_copy_with_noise` | 30 | 7 | +| `intent_attack_with_goal_selection` | 20 | 3 | + +Each task stops when it reaches either limit. An attempt includes candidates +that cannot be generated, fail quality checks, or encounter a recoverable +error; accepted scenarios have passed motion validation and NC/DAC checks. Defaults +therefore allow up to 50 attempts and 10 accepted scenarios per base scene, +but do not guarantee 10 successes. The budgets reset for each base scene. + +For a normal run, inherit these defaults without adding any fields. To +change a budget, add only the desired overrides to your **BWM scenario +YAML**. For example, append: + +```yaml +generation: + tasks: + goal_conditional_copy_with_noise: + max_attempts: 10 + max_success: 2 +``` + +This changes the first task to 10 attempts and 2 accepted scenarios. The +second task still inherits 20 and 3. Task execution order is fixed regardless +of YAML key order. Both limits must be non-negative integers; setting either +limit to `0` skips that task. Omitted values inherit from the default config. + +These settings control repeated candidate generation. `model.diffuser.steps` +controls the diffusion steps **inside one inference call** and remains 32 by +default. Generation processes scenes and tasks sequentially with one loaded +model; this entry point does not provide a worker-pool setting. + +### Saving Results + +`save_scenario_description` defaults to `true`, so accepted scenarios are +saved to the canonical staging PKL for publication and rollout. For a +diagnostic run, append this to your BWM scenario YAML: + +```yaml +save_scenario_description: false +``` + +Generation, metric checks, logs, and visualizations still run, but the final +scene PKL is not written. This option does not reduce inference work or +delete existing files. A fresh run with saving disabled produces no scene +PKLs to publish. Use a new `scenario_name` for diagnostics or changed budgets: +existing canonical staging outputs are skipped even when saving is disabled. + +### Data Paths + +Common paths that may be overridden are: + +```yaml +checkpoint: data/alg_engine/ckpts/nuplan.ckpt +digitaltwin_data_root: data/sim_engine/assets/navtrain/assets +openscene_data_root: data/raw/openscene-v1.1 + +scenario_builder: + data_root: data/raw/nuplan/dataset/nuplan-v1.1/trainval + map_root: data/raw/nuplan/dataset/maps + sensor_root: data/raw/nuplan/dataset/nuplan-v1.1/sensor_blobs +``` + +## Validate Before Generation + +Always validate a new config first: + +```bash +scripts/run_bwm.sh validate \ + --config projects/BWM/configs/scenarios/my_scenario.yaml +``` + +Validation composes both configuration layers, loads the referenced +SceneFilter, checks generation controls and required runtime inputs, anchors +repository-relative paths, and reports the selected log/token counts. +Inspect the effective budgets and saving flag before generation. With +defaults, the summary includes: + +```text +generation_execution: sequential +generation.tasks.goal_conditional_copy_with_noise: max_attempts=30, max_success=7 +generation.tasks.intent_attack_with_goal_selection: max_attempts=20, max_success=3 +save_scenario_description: true +runtime_unset: none +``` + +Validation does not load the model or generate files. Invalid budget values, +unknown task names, and non-boolean saving flags are rejected before model +loading. The same effective settings are printed when generation starts. + +## Generate Scenarios + +Start generation with the same config: + +```bash +scripts/run_bwm.sh generate \ + --config projects/BWM/configs/scenarios/my_scenario.yaml +``` + +The default staging layout is: + +```text +projects/BWM/outputs/ +└── my_scenario/ + └── / + ├── .pkl + └── generated visualizations +``` + +Each canonical source file must use the exact +`/.pkl` layout. Visualizations and other files in the source +directory are not publication inputs. + +Generation applies several quality gates before accepting a candidate, +including agent temporal validity, dynamic-vehicle movement and proximity, +trajectory validity, no-collision (NC), and drivable-area compliance (DAC). +Only accepted scenarios are written to the canonical source pickle. +See [Scene Quality Filtering](#scene-quality-filtering) for the detailed +stage-by-stage rules and current thresholds. + +## Publish for SimEngine + +Generation and publication are separate operations. Publish only after +reviewing the staging output: + +```bash +scripts/run_bwm.sh publish \ + --config projects/BWM/configs/scenarios/my_scenario.yaml +``` + +The publisher discovers immediate canonical source files, validates their +pickle mappings and required SimEngine fields, rejects duplicate scenario +IDs, and writes: + +```text +data/sim_engine/scenarios/augmented/ +└── my_scenario/ + └── all_scenarios.pkl +``` + +Publication is atomic and refuses to replace an existing +`all_scenarios.pkl` by default. To intentionally replace it: + +```bash +scripts/run_bwm.sh publish \ + --config projects/BWM/configs/scenarios/my_scenario.yaml \ + --overwrite +``` + +The destination pickle is a mapping from scenario ID to scenario +description. It can be loaded with standard Python: + +```python +import pickle +from pathlib import Path + +path = Path( + "data/sim_engine/scenarios/augmented/" + "my_scenario/all_scenarios.pkl" +) +with path.open("rb") as stream: + scenarios = pickle.load(stream) + +print(f"Loaded {len(scenarios)} BWM scenarios") +``` + +Next, follow [Rollouts from BWM Scenarios](simengine_usage.md#rollouts-from-bwm-scenarios) +to select the published `augmented` input and run NR rollout with the base +scene assets. After automatic rollout export, follow +[AlgEngine dataset verification](algengine_usage.md#verify-the-exported-rollout-dataset) +and [fine-tuning configuration](algengine_usage.md#fine-tuning-configuration) +to train on the generated observations and rewards. + +## Output Contract + +Every published scenario contains the fields required by SimEngine: + +```text +id, name, token, dataset, map, log_length, sample_rate, base_timestamp, +metadata, cameras, lidar, object_track, sdc_id, map_features, +dynamic_map_states +``` + +The top-level mapping key must match the scenario's `id` and `name`. BWM +outputs use the dataset identifier `bwm.nuplan`. + +The 2 Hz OpenScene sequence is exported with `sample_rate: 10`: SimEngine +interprets this field as a stride relative to nuPlan's 20 Hz, so each step +advances by `10 * 0.05 = 0.5` seconds. + +BWM ego features use the nuPlan rear-axle position. On export, ego positions +are converted to vehicle centers, matching SimEngine's `object_track` +convention. Ego, other agents, and map features share one local origin; +subtract `metadata.old_origin_in_current_coordinate` to recover global +positions. SimEngine converts ego centers back to rear-axle poses before +rendering. NC/DAC evaluation uses the exported vehicle centers directly. + +BWM model inputs use lane and lane-connector centerlines, matching the +training feature builder. Stop lines and crosswalks use polygon outlines. +The exported scenario retains lane topology in `map_features`. DAC uses the +complete nuPlan `DRIVABLE_AREA` stored as GeoJSON in +`metadata.drivable_area`, including road segments, intersections, generic +drivable areas, and car parks. The geometry retains polygon holes and uses +global coordinates; the metric converter applies +`metadata.old_origin_in_current_coordinate` to align it with local tracks. + +Use a new `scenario_name` when changing generation settings or updating BWM, +then generate and publish the new output. Generation skips existing canonical +source files; republishing alone does not recompute trajectories or metadata. + +## Scene Quality Filtering + +The SceneFilter selects the base scenes for a generation job. The following +checks filter agents before inference and validate generated candidates +before they are written to staging. + +```text +Feature extraction + → Agent temporal validity + → Dynamic vehicle selection + → Spatial proximity (skip inference if no candidates remain) + → Direction-compatible lane goal selection (attack task) + → Diffusion inference and successful dynamics optimization + → Motion continuity and velocity consistency + → Trajectory valid point check + → No collision (NC) and drivable-area compliance (DAC) + → Final acceptance gate + → Write accepted scenarios to staging +``` + +### Stage 1: Agent Temporal Validity + +During feature extraction, vehicles, pedestrians, and cyclists with fewer +than **5 valid frames** are excluded from the scene tensor. + +Implementation: `compute_features()` in +[feature_processor.py](../projects/BWM/scripts/generation_general/processors/feature_processor.py). + +### Stage 2: Dynamic Vehicle Selection + +A vehicle is eligible for behavior modification when its cumulative +displacement across valid positions is **greater than 3.0 m**. Displacement +is the sum of Euclidean distances between successive valid positions; +vehicles with fewer than two valid positions are excluded. + +If no vehicle passes this check, the task sets `scenario_valid=False` and +skips inference. + +Implementation: `is_vehicle_moving()` in +[nuplan_utils.py](../projects/BWM/scripts/generation_general/utils/nuplan_utils.py). + +### Stage 3: Spatial Proximity + +Dynamic candidates must be valid at the fifth frame and satisfy both +distance limits in the ego vehicle's coordinate frame at that frame: + +| Distance from ego | Maximum absolute distance | +|-------------------|---------------------------| +| Lateral | 5.0 m | +| Longitudinal | 15.0 m | + +If no candidate remains, the task sets `scenario_valid=False` and skips +inference. + +Implementation: `filter_nearby_vehicles()` in +[scene_generator_v2.py](../projects/BWM/scripts/generation_general/processors/scene_generator_v2.py). + +For attack generation, candidates must additionally have all five historical +frames present and finite. The attacker is sampled from the four closest +**filtered candidates**, ranked at the fifth (current) frame. Other vehicles +stay in log replay. Attack generation may extend an incomplete future track; +it does not manufacture missing history. + +### Attack Goals and Optimizer Failures + +Attack goals use valid, non-degenerate `LANE` / `LANE_CONNECTOR` centerline +segments. Stop-line and crosswalk outlines are not driving goals. A goal must: + +- Lie within 15 degrees of the current heading, using wrapped angle differences. +- Be at a distance between `speed * (horizon - 1)` and + `speed * (horizon + 1)`, with the lower duration clamped to zero. Speed is + the current velocity magnitude; horizon is the number of future steps + times 0.5 seconds (8 seconds by default). +- Have a lane heading within 60 degrees of both the current heading and + the displacement toward the goal. Terminal velocity follows that heading. + +The optional ego-endpoint target must pass the same geometric checks and +be within 5 m of an eligible lane point with a compatible heading. If no +goal passes, the attempt is rejected before inference; the last observed +state is not reused as a fallback goal. These are conservative geometric +screens, not a guarantee of route connectivity or dynamic feasibility. + +The sampler retains hard terminal conditions. Every invoked dynamics or +collision optimization must report success and return finite states. +Failure rejects the entire attempt and logs the optimization stage and +solver status; an unoptimized trajectory is no longer accepted as a fallback. +Fully replayed tracks skip optimization. Collision optimization is invoked +only when its collision detector identifies a conflict. These stricter +rules may reduce yield within the same attempt budget. + +### Motion Validation Before Export + +Both generation tasks screen ego and modified vehicles in native BWM +coordinates before export. Controlled tracks must have complete, finite +states and positive dimensions. Checks cover all transitions involving a +generated state, including history-to-future and penultimate-to-fixed-goal +boundaries. Fully replayed tracks and wholly historical transitions are +excluded from the motion limits. + +The provisional defaults are: + +| Setting under `motion_validation` | Default | Measurement | +|-----------------------------------|---------|-------------| +| `max_speed_mps` | 45.0 | Stored speed and displacement divided by 0.5 s | +| `max_acceleration_mps2` | 10.0 | Vector acceleration from position differences and stored velocities | +| `max_velocity_error_mps` | 5.0 | Displacement-derived velocity minus the mean of the two endpoint velocities | + +Override individual limits in the scenario YAML, for example: + +```yaml +motion_validation: + max_velocity_error_mps: 3.0 +``` + +Limits must be finite positive numbers. They are initial rejection +thresholds, not calibrated guarantees of physical realism. Review rejection +rates and retained trajectories on real generation runs before release. +Use a new `scenario_name`: existing staging files are skipped and are not +revalidated by publishing them again. + +Implementation: [motion_validation.py](../projects/BWM/scripts/generation_general/utils/motion_validation.py). + +### Stage 4: Trajectory Valid Points + +Before computing metrics for an agent, the pipeline counts its valid +trajectory points: + +| Valid points | Handling | +|--------------|----------| +| 0 | Set NC and DAC to `0.0`; skip metric computation. | +| 1–2 | Set NC and DAC to `0.1`, emit a warning, and skip metric computation. | +| 3 or more | Compute NC and DAC over continuous valid segments. | + +Zero valid points cause rejection at the final gate. The `0.1` fallback +for 1–2 points satisfies the current `> 0` acceptance threshold, so these +short trajectories can pass this metric gate in isolation. Newly generated +controlled tracks must first pass the complete-track motion validation above. + +Implementation: `calculate_metrics_for_agent_from_sd()` in +[example_usage.py](../projects/BWM/scripts/generation_general/post_processor/eval_metric/example_usage.py). + +### Stage 5: No Collision (NC) + +For trajectories with at least three valid points, metric computation uses +continuous valid segments of **at least 3 points**. If no such segment +exists, NC and DAC are both `0.0`. + +Within each segment, collision detection tests intersections between the +agent's oriented bounding box and other objects at each valid timestep. +Fault is assigned relative to the agent being evaluated: + +| Collision type | Condition | At fault | +|----------------|-----------|----------| +| Stopped track | Other object's speed is below 0.005 m/s | Yes | +| Active front | Moving object is ahead of the evaluated agent | Yes | +| Active lateral | Moving object is to the side or rear | No | + +The stopped-track condition is checked first. NC uses the lowest score +across collisions and segments: + +| Outcome | NC score | +|---------|----------| +| At-fault collision with a vehicle, cyclist, or motorcyclist | `0.0` | +| At-fault collision with another object type | `0.5` | +| No at-fault collision | `1.0` | + +Implementation: `StandaloneMetricsCalculator` in +[standalone_metrics.py](../projects/BWM/scripts/generation_general/post_processor/eval_metric/standalone_metrics.py). + +### Stage 6: Drivable-Area Compliance (DAC) + +At each valid timestep, DAC measures the fraction of the agent's bounding +box area overlapping the union of drivable-area polygons: + +| Overlap fraction | DAC score at that timestep | +|------------------|----------------------------| +| 0 (completely off-road) | `0.0` | +| Greater than 0 and below 0.8 | The overlap fraction | +| 0.8 or greater | `1.0` (no penalty) | + +The final score is the minimum across timesteps and valid segments. BWM +exports include the complete native drivable geometry for polygons +intersecting the 500 m query window around the scene origin. Empty or invalid +native geometry raises an error during export or evaluation. + +For supplied files without `metadata.drivable_area`, the metric converter +falls back to `map_features`. This can omit valid areas such as parts of +intersections; regenerate those files with BWM to include complete geometry. +In this fallback path, absent drivable-area map data defaults to `1.0`. +The no-valid-segment rejection described above still applies. + +Implementation: `StandaloneMetricsCalculator` in +[standalone_metrics.py](../projects/BWM/scripts/generation_general/post_processor/eval_metric/standalone_metrics.py). + +### Stage 7: Final Acceptance + +The pipeline checks ego and the controlled agents returned by the +generation task after the motion gate. Each checked agent must satisfy +**NC > 0 and DAC > 0**. +Checks stop at the first failure, and the entire candidate is discarded. +Passing agents receive `metric_check_passed=True` in their metadata. +Requested agents absent from `object_track` are skipped with a warning. + +The threshold permits positive partial scores, including NC `0.5`, DAC +below `0.8`, and the short-trajectory fallback of `0.1`. These are the +current acceptance rules; passing does not require NC and DAC to equal +`1.0`. + +Accepted candidates are saved in the canonical staging layout described +under [Generate Scenarios](#generate-scenarios). Use +[Publish for SimEngine](#publish-for-simengine) to assemble the final +`all_scenarios.pkl`. + +Implementation: `metric_check()` in +[pipeline_w_opt.py](../projects/BWM/scripts/generation_general/pipeline_w_opt.py). + +## Troubleshooting + +### Missing layered runtime paths + +Run `validate` and inspect every reported path. The default checkpoint, +NuPlan, OpenScene, and DigitalTwin inputs must exist before generation. + +### No canonical staging source files found + +Confirm that generation produced: + +```text +projects/BWM/outputs///.pkl +``` + +The publisher intentionally ignores arbitrary nested or differently named +pickle files. + +### Published scenario file already exists + +The publisher does not silently overwrite SimEngine inputs. Review the +existing file, then pass `--overwrite` only if replacement is intentional. + +### Duplicate scenario ID + +Two staging source files own the same scenario ID. Fix the generation output +or scenario naming; the publisher will not choose one silently. + +### CUDA out of memory + +Generation catches CUDA OOM per task and stops that task early. Free GPU +memory and retry; do not publish a partial staging directory until its +contents have been reviewed. diff --git a/docs/config_guide.md b/docs/config_guide.md index 9ede766..947f9d1 100644 --- a/docs/config_guide.md +++ b/docs/config_guide.md @@ -153,7 +153,7 @@ use_lora=True, lora_rank=16 | `rlft_common_log` | Real logs | `FineTune` | `True` | `False` (default) | - | | `rlft_rare_log` | Real logs | `FineTune` | `False` (default) | `True` | - | | `rlft_rare_rollout` | Synthetic | `FineTuneSynthetic` | - | - | `folder_name`, `customized_filter="v1"` | -| `rlft_rare_rollout_bwm` | Synthetic (multi) | `FineTuneSynthetic` | - | - | `folder_name` (4 sources), `customized_filter="v1"` | +| `rlft_rare_rollout_bwm` | BWM / mixed rollouts | `FineTuneSynthetic` | - | - | `folder_name` (4 example sources), `customized_filter="v1"` | | `rlft_rare_syn_replay` | Synthetic replay | `FineTuneSynthetic` | - | - | `customized_filter="v2"`, `include_real_failures=False` | --- @@ -184,22 +184,49 @@ Key fields: ### rlft_rare_rollout -**Purpose:** RLFT using **synthetic rollout** trajectories generated from a single source. +**Purpose:** RLFT using **synthetic rollout** trajectories. The example below +uses a single source from original-scenario rollouts. + +Both `rlft_rare_rollout` and `rlft_rare_rollout_bwm` use +`NavSimOpenSceneE2EFineTuneSynthetic`. In both configs, +`synthetic_folder_names` selects exported rollout datasets and is passed to +`data.train.folder_name`. The list can contain ordinary rollouts, BWM +rollouts, or a mixture; it can have one or more entries in either config. Key fields: + - `train_dataset_type = "NavSimOpenSceneE2EFineTuneSynthetic"` -- loads synthetic trajectory data -- `synthetic_folder_names = ["e2e_vadv2_50pct_navtrain_50pct_collision_NR_250911"]` -- single synthetic source +- `synthetic_folder_names` -- this example selects one ordinary rollout dataset: + + ```python + synthetic_folder_names = [ + "e2e_vadv2_50pct_navtrain_50pct_collision_NR_250911", + ] + ``` + - `customized_filter="v1"` -- filtering strategy for synthetic data - `folder_name=synthetic_folder_names` -- passed to dataset for loading +The distributed rollout launcher merges and exports automatically. Follow +[AlgEngine dataset verification](algengine_usage.md#verify-the-exported-rollout-dataset) +to identify the exported names before updating the config. Entries are +names under `openscene-synthetic/{meta_datas,sensor_blobs,pdms_pkl}`, not +absolute filesystem paths. +The dated names shown here are examples; use the exact names of your +existing exports, including their original suffixes. + --- ### rlft_rare_rollout_bwm -**Purpose:** Extended version of `rare_rollout` with **multiple augmented synthetic sources** (backward-masked trajectories). +**Purpose:** RLFT on rollouts from **Behavior World Model (BWM)** scenarios, +optionally mixed with rollouts from original scenarios. Key fields: -- `synthetic_folder_names` -- 4 sources covering collision, ego progress, and off-road scenarios: + +- `synthetic_folder_names` -- the following example combines four sources + covering collision, ego progress, and off-road scenarios: + ```python synthetic_folder_names = [ "e2e_vadv2_50pct_navtrain_50pct_collision_NR_250911", @@ -208,8 +235,14 @@ Key fields: "e2e_vadv2_50pct_aug_navtrain_50pct_offroad_NR_250928", ] ``` - PS: You need to produce your own rollouts and organize them into `data/alg_engine/openscene-synthetic`. See [SimEngine Usage Guide - Rollout Scripts](simengine_usage.md#rollout-scripts) for how to generate augmented rollouts. + + Replace these examples with the exact exported names from your runs. + See [Rollouts from BWM Scenarios](simengine_usage.md#rollouts-from-bwm-scenarios) + and [AlgEngine Fine-Tuning Configuration](algengine_usage.md#fine-tuning-configuration). - `customized_filter="v1"` -- same filtering as `rare_rollout` +- `folder_name=synthetic_folder_names` -- passed to the same synthetic dataset loader +- `finetune_yaml` -- include the base scene tokens used for generation; + synthetic samples outside these filters are skipped --- diff --git a/docs/data_organization.md b/docs/data_organization.md index 78025a9..10fe558 100644 --- a/docs/data_organization.md +++ b/docs/data_organization.md @@ -1,6 +1,6 @@ # Data Organization Guide -This guide explains how to organize data for WorldEngine. The platform uses a modular data structure where each subsystem (AlgEngine, SimEngine) has its own data requirements while sharing common formats. +This guide explains how to organize data for WorldEngine. The platform uses a modular data structure where AlgEngine, SimEngine, and BWM share common datasets and scenario formats. ## Quick Overview @@ -12,7 +12,8 @@ WorldEngine/ │ └── sim_engine/ # SimEngine-specific data ├── projects/ │ ├── AlgEngine/ # Algorithm training & evaluation -│ └── SimEngine/ # Closed-loop photorealistic simulation +│ ├── SimEngine/ # Closed-loop photorealistic simulation +│ └── BWM/ # Behavior world model inference ├── experiments/ # Experiment outputs └── data_output/ # Default data outputs dir ``` @@ -99,7 +100,7 @@ data/alg_engine/ │ ├── meta_datas/ │ └── pdms_pkl/ │ -├── ckpts/ # Pre-trained model checkpoints +├── ckpts/ # Pre-trained checkpoints shared with BWM │ ├── pdms_cache/ # Pre-computed PDM metrics cache │ ├── pdm_8192_gt_cache_navtrain.pkl @@ -136,14 +137,40 @@ data/sim_engine/ │ └── augmented/ # Augmented scenarios (from BWM) ├── navtrain_50pct_collision/ + │ └── all_scenarios.pkl ├── navtrain_50pct_ep_1pct/ + │ └── all_scenarios.pkl └── navtrain_50pct_offroad/ + └── all_scenarios.pkl ``` --- -### 4. Experiments Output (`experiments/`) +### 4. BWM Shared Inputs and Outputs + +BWM reuses the root WorldEngine data tree rather than introducing a separate +module data root: + +```text +data/ +├── alg_engine/ckpts/nuplan.ckpt +├── raw/ +│ ├── nuplan/dataset/ +│ └── openscene-v1.1/ +└── sim_engine/ + ├── assets/navtrain/assets/ + └── scenarios/augmented//all_scenarios.pkl +``` + +Generation first writes reviewable staging artifacts under +`projects/BWM/outputs//`. The explicit BWM publish command then +validates and atomically writes the canonical SimEngine +`all_scenarios.pkl`. See the [BWM Usage Guide](bwm_usage.md). + +--- + +### 5. Experiments Output (`experiments/`) Generated experiment results and logs. diff --git a/docs/installation.md b/docs/installation.md index 0e6f703..e9a459d 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,9 +1,11 @@ # Installation Guide -WorldEngine consists of two main subsystems that require **separate conda environments** due to different Python version requirements: +WorldEngine uses **three separate conda environments** so each module has a +reproducible dependency set: - **SimEngine** (`simengine` env, Python 3.9) - Closed-loop simulation with photorealistic rendering - **AlgEngine** (`algengine` env, Python 3.9) - End-to-end model training and evaluation +- **Behavior World Model** (`bwm` env, Python 3.9) - Pre-trained scenario generation and publication > **Note:** Scene Reconstruction uses the same environment as SimEngine since it's based on MTGS and shares dependencies. @@ -28,7 +30,8 @@ WorldEngine consists of two main subsystems that require **separate conda enviro ### Software Requirements - **OS:** Linux (Ubuntu 20.04/22.04 recommended) -- **CUDA:** 11.8 +- **CUDA:** NVIDIA driver compatible with the environment runtime + (CUDA 11.8 for SimEngine/AlgEngine and CUDA 12.1 for BWM) - **Conda/Miniconda:** Latest version --- @@ -38,7 +41,6 @@ WorldEngine consists of two main subsystems that require **separate conda enviro This environment is used for: - Closed-loop simulation - Photorealistic rendering -- Behavior world model (coming soon) ### Step-by-Step Installation @@ -194,6 +196,62 @@ print(f'✓ CUDA available: {torch.cuda.is_available()}') ``` --- +## Environment 3: Behavior World Model (`bwm`) + +This environment is used for pre-trained BWM inference and publishing +augmented scenarios for SimEngine. BWM training dependencies are not part of +the public environment. + +### Step-by-Step Installation + +#### 1. Create the Conda Environment + +From the WorldEngine repository root: + +```bash +conda env create -f projects/BWM/environment.yml +conda activate bwm +``` + +The environment file installs Python 3.9, PyTorch 2.3.0, torchvision 0.18.0, +and the CUDA 12.1 runtime. + +#### 2. Install BWM Runtime Dependencies + +```bash +python -m pip install -r projects/BWM/requirements.txt +``` + +The requirements install the official nuPlan devkit at the commit pinned by +the repository. No separate nuPlan fork or manual source checkout is needed. + +For local test development only: + +```bash +python -m pip install -r projects/BWM/requirements-dev.txt +``` + +#### 3. Verify Installation + +```bash +python -m pip check +python -c " +import torch +from omegaconf import OmegaConf +from nuplan.common.maps.maps_datatypes import SemanticMapLayer +print('✓ All BWM dependencies OK') +print(f'✓ PyTorch {torch.__version__}') +print(f'✓ CUDA available: {torch.cuda.is_available()}') +print(f'✓ nuPlan map layers: {len(list(SemanticMapLayer))}') +" +``` + +Next, follow the [BWM Usage Guide](bwm_usage.md) to prepare shared data, +validate a layered scenario config, generate candidates, and publish +`all_scenarios.pkl`. + +--- + ## Environment Variables we rely on NAVSIM devkit, please git clone and switch to `v1.1` branch: @@ -228,12 +286,10 @@ source ~/.bashrc # or source ~/.zshrc ## Environment Summary -| Feature | SimEngine (`simengine`) | AlgEngine (`algengine`) | -|---------|---------------------------|-------------------------| -| **Python Version** | 3.9 | 3.9 | -| **PyTorch** | 2.0.1+cu118 | 2.0.1+cu118 | -| **Key Libs** | gsplat, ray | MMCV, MMDet3D, MMCls | -| **Use Cases** | Simulation, Rendering, BWM | Training, Evaluation | -| **Disk Space** | ~10 GB | ~15 GB | -| **Install Time** | ~30 min | ~45 min (MMCV build) | +| Feature | SimEngine (`simengine`) | AlgEngine (`algengine`) | BWM (`bwm`) | +|---------|---------------------------|-------------------------|-------------| +| **Python Version** | 3.9 | 3.9 | 3.9 | +| **PyTorch** | 2.0.1+cu118 | 2.0.1+cu118 | 2.3.0 + CUDA 12.1 | +| **Key Libs** | gsplat, ray | MMCV, MMDet3D, MMCls | nuPlan devkit, Hydra, diffusion inference | +| **Use Cases** | Simulation, Rendering | Training, Evaluation | Scenario generation, publication | diff --git a/docs/quick_start.md b/docs/quick_start.md index 403b70c..45d82a7 100644 --- a/docs/quick_start.md +++ b/docs/quick_start.md @@ -5,7 +5,7 @@ This guide will help you run your first WorldEngine experiment in minutes. We'll ## Prerequisites Before starting, ensure you have: -- ✅ Completed [Installation](installation.md) for both environments +- ✅ Completed [Installation](installation.md) for the module environments you will use - ✅ Set up environment variables (`WORLDENGINE_ROOT`) - ✅ Downloaded pre-trained model checkpoint - ✅ Prepared scenario data (see [Data Organization](data_organization.md)) @@ -122,6 +122,7 @@ The quick test script calls `scripts/run_testing.sh` (or `run_ray_distributed_te For more details on the testing pipeline, see: - **[SimEngine Usage Guide](simengine_usage.md)** - Rollout and testing scripts - **[AlgEngine Usage Guide](algengine_usage.md)** - Model inference and evaluation +- **[BWM Usage Guide](bwm_usage.md)** - Augmented scenario generation and publication --- @@ -198,6 +199,17 @@ Learn how to: 👉 **[AlgEngine Usage Guide](algengine_usage.md)** +### Behavior World Model - Scenario Generation + +Learn how to: + +- Validate a layered scenario configuration +- Generate quality-gated scenario candidates +- Publish `all_scenarios.pkl` for SimEngine +- Diagnose staging and publication errors + +👉 **[BWM Usage Guide](bwm_usage.md)** + --- ## Complete Pipeline Example @@ -322,3 +334,4 @@ You've learned how to: **Next:** Choose your path: - 🎮 **Want to run more simulations?** → [SimEngine Usage Guide](simengine_usage.md) - 🧠 **Want to train/posttrain your own models?** → [AlgEngine Usage Guide](algengine_usage.md) +- 🌍 **Want to generate augmented scenarios?** → [BWM Usage Guide](bwm_usage.md) diff --git a/docs/simengine_usage.md b/docs/simengine_usage.md index 5364da7..0da3bb5 100644 --- a/docs/simengine_usage.md +++ b/docs/simengine_usage.md @@ -71,10 +71,12 @@ For large-scale data generation: ```bash export WORLDENGINE_ROOT=/path/to/WorldEngine -cd projects/SimEngine -bash scripts/run_ray_distributed_rollout.sh \ - $WORLDENGINE_ROOT/projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct.py \ - $WORLDENGINE_ROOT/data/alg_engine/ckpts/e2e_vadv2_50pct_ep8.pth \ +# The exporter expects these parent directories to exist. +mkdir -p "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/"{meta_datas,pdms_pkl,sensor_blobs} + +bash "$WORLDENGINE_ROOT/projects/SimEngine/scripts/run_ray_distributed_rollout.sh" \ + "$WORLDENGINE_ROOT/projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct.py" \ + "$WORLDENGINE_ROOT/data/alg_engine/ckpts/e2e_vadv2_50pct_ep8.pth" \ e2e_vadv2_50pct \ navtrain_50pct_collision \ navtrain @@ -84,15 +86,72 @@ bash scripts/run_ray_distributed_rollout.sh \ 1. ``: Model configuration file 2. ``: Trained model checkpoint 3. ``: Experiment name (creates output folder) -4. ``: Scenario split (e.g., `navtrain_50pct_collision`). Must match a directory under `data/sim_engine/scenarios/original/` +4. ``: Scenario directory name (e.g., `navtrain_50pct_collision`). The launcher reads `data/sim_engine/scenarios/original//all_scenarios.pkl` by default. For BWM inputs, see [Rollouts from BWM Scenarios](#rollouts-from-bwm-scenarios). 5. `` (optional): Asset folder name under `data/sim_engine/assets/`. Defaults to `` if not provided **Features:** - Distributes scenarios across 8 GPUs (8 splits) - Each GPU processes 1/8 of scenarios in parallel -- Auto-merges results at the end +- Automatically merges results and exports an AlgEngine dataset at the end - Resumes from previous runs (`ENABLE_RESUME=true`) +The output directory is +`$WORLDENGINE_ROOT/experiments/closed_loop_exps//_NR/`. +`asset_name` selects the rendering assets; it does not change the output name. + +After a successful run, continue with +[Verify the Exported Rollout Dataset](algengine_usage.md#verify-the-exported-rollout-dataset) +and configure fine-tuning. Manual merge and export commands below are for +processing existing results separately. Resume skips completed simulation +scenarios, but export is not idempotent: an existing export with the same +dataset name causes `FileExistsError`. + +### Rollouts from BWM Scenarios + +First [generate and publish BWM scenarios](bwm_usage.md#generate-scenarios). +For a job named `my_scenario`, the input is +`data/sim_engine/scenarios/augmented/my_scenario/all_scenarios.pkl`. + +The current rollout launcher selects `original` or `augmented` through its +`DATAFILE_FOLDER_PATH` assignment, rather than a command-line argument. +Before launching a BWM run, edit that assignment in +`projects/SimEngine/scripts/run_ray_distributed_rollout.sh` to: + +```bash +DATAFILE_FOLDER_PATH="data/sim_engine/scenarios/augmented/${DATA_TYPE}" +``` + +Then run the published scenario set with the original base scene assets: + +```bash +export WORLDENGINE_ROOT=/path/to/WorldEngine +mkdir -p "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/"{meta_datas,pdms_pkl,sensor_blobs} + +bash "$WORLDENGINE_ROOT/projects/SimEngine/scripts/run_ray_distributed_rollout.sh" \ + "$WORLDENGINE_ROOT/projects/AlgEngine/configs/worldengine/e2e_vadv2_50pct.py" \ + "$WORLDENGINE_ROOT/data/alg_engine/ckpts/e2e_vadv2_50pct_ep8.pth" \ + e2e_vadv2_50pct \ + my_scenario \ + navtrain +``` + +Here `my_scenario` is the BWM `scenario_name`, and `navtrain` selects the +base assets under `data/sim_engine/assets/navtrain/assets`. Adjust the +asset name to match the corpus used during BWM generation. + +Rollout uses NR mode: other agents follow the trajectories stored in the +input scenario, including BWM-generated trajectories, while AlgEngine +controls ego in closed loop. The launcher computes dense rewards and +automatically merges and exports results: + +- Rollout directory: `$WORLDENGINE_ROOT/experiments/closed_loop_exps/e2e_vadv2_50pct/my_scenario_NR/` +- Exported dataset name: `e2e_vadv2_50pct_my_scenario_NR_` + +Use that exported name in the BWM rollout fine-tuning config, following +[AlgEngine Fine-Tuning Configuration](algengine_usage.md#fine-tuning-configuration). +Restore the launcher's `original/${DATA_TYPE}` input path before using it +for original scenarios again. + ### Customizing Rollout Splits Edit the rollout script to change GPU count: @@ -306,28 +365,50 @@ Converted scenarios can be directly used for SimEngine simulation. ### Merge Distributed Results -After distributed simulation, merge results: -(Run Automatically) +The distributed rollout and testing launchers already merge results. Use +this command only when merging existing split outputs separately. The +example follows the scenario set used in +[AlgEngine Fine-Tuning](algengine_usage.md#prerequisites-generating-rollouts-with-simengine). + ```bash conda activate simengine +ROLLOUT_PATH="$WORLDENGINE_ROOT/experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_vadv2_50pct_rare_NR" -python projects/SimEngine/scripts/merge_simulation_results.py \ - --test_path $WORLDENGINE_ROOT/experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_ep_per1_NR \ +python "$WORLDENGINE_ROOT/projects/SimEngine/scripts/merge_simulation_results.py" \ + --test_path "$ROLLOUT_PATH" \ --react_type NR ``` ### Export OpenScene Format Data -Export simulation data for training: +The rollout launcher automatically exports after merging, with a `YYMMDD` +suffix from the system date at export time. After a successful automatic +export, proceed directly to +[dataset verification](algengine_usage.md#verify-the-exported-rollout-dataset). + +For an existing merged rollout that has not been exported, use this manual +command. Choose an unused suffix; `manual_v1` is an example: ```bash conda activate simengine +ROLLOUT_PATH="$WORLDENGINE_ROOT/experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_vadv2_50pct_rare_NR" +mkdir -p "$WORLDENGINE_ROOT/data/alg_engine/openscene-synthetic/"{meta_datas,pdms_pkl,sensor_blobs} -python projects/SimEngine/scripts/export_simulation_data.py \ - --test_path $WORLDENGINE_ROOT/experiments/closed_loop_exps/e2e_vadv2_50pct/navtrain_ep_per1_NR +python "$WORLDENGINE_ROOT/projects/SimEngine/scripts/export_simulation_data.py" \ + --test_path "$ROLLOUT_PATH" \ + --appendix manual_v1 ``` -**Output:** `data/alg_engine/openscene-synthetic/` +Pass an absolute `--test_path` without a trailing slash. The exporter uses +the path directly and derives the model and run names from its last two +components. + +The example creates dataset +`e2e_vadv2_50pct_navtrain_vadv2_50pct_rare_NR_manual_v1` under each of +`data/alg_engine/openscene-synthetic/{meta_datas,sensor_blobs,pdms_pkl}`. +Omitting `--appendix` omits the suffix; the exporter does not add a date +itself. Existing symlink destinations are not overwritten. A new suffix +creates another name for the same source rollout, not a new simulation. --- diff --git a/projects/BWM/.gitignore b/projects/BWM/.gitignore new file mode 100644 index 0000000..793c6c0 --- /dev/null +++ b/projects/BWM/.gitignore @@ -0,0 +1,214 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +!nerfstudio/scripts/downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Experiments and outputs +outputs/ +output/ +exports/ +checkpoints/ +*_report.txt +*.mp4 +*.gif +*.zip +# tensorboard log files +events.out.* + +# Data +/data + +# Misc +old/ +temp/ +tmp/ +!temporal* +.nfs* +external/ +__MACOSX/ +node_modules/ +bash/ +cache/ +package-lock.json +camera_paths/ +.DS_Store +._.DS_Store +*/**/.DS_Store +*/**/._.DS_Store +masks/ +*.sif + +data/ +debug/ + +logs/ +third_party/MTR/ +third_party/alf/ +wandb/ +third_party/scenarionet/ +third_party/metadrive/ +third_party/nuplan-devkit/ +*.bin +render/ + +arxiv/ +cache_nuplan/ +scripts/generation_general/output \ No newline at end of file diff --git a/projects/BWM/configs/default.yaml b/projects/BWM/configs/default.yaml new file mode 100644 index 0000000..74c6747 --- /dev/null +++ b/projects/BWM/configs/default.yaml @@ -0,0 +1,130 @@ +# Shared defaults for BWM scenario generation. +# Runtime inputs are relative to the WorldEngine repository root. + +output_dir: projects/BWM/outputs/${scenario_name} +log_dir: projects/BWM/logs +publish_root: data/sim_engine/scenarios/augmented +# Per-base-scene budgets. Each task stops at either limit; zero skips a task. +generation: + tasks: + goal_conditional_copy_with_noise: + max_attempts: 30 + max_success: 7 + intent_attack_with_goal_selection: + max_attempts: 20 + max_success: 3 + +# Controls final scene PKLs only; metrics and visualizations still run. +save_scenario_description: true +world_engine_compatible: true + +# Provisional motion gates; revalidate on generated data before release. +# BWM uses a fixed 0.5 s interval. These checks include the fixed goal boundary. +motion_validation: + max_speed_mps: 45.0 + max_acceleration_mps2: 10.0 + max_velocity_error_mps: 5.0 + +model: + _target_: nuplan_extent.planning.training.modeling.models.nexus_with_opt.Nexus + _convert_: all + diffuser: + _target_: nuplan_extent.planning.training.modeling.models.diffusion.scenediffusion_with_opt.simpleDiffusion + _convert_: all + pred_param: v + schedule: shifted_cosine + steps: 32 + model: + _target_: nuplan_extent.planning.training.modeling.models.diffusion.models.diffusion.Nexus + _convert_: all + nblocks: 4 + hidden_dim: 256 + scene_tensor_dim: 8 + global_encoder: + _target_: nuplan_extent.planning.training.modeling.models.encoders.perciever_context_encoder.PercieverEncoder + _convert_: all + num_latents: 128 + latent_dim: 256 + input_dim: 7 + num_blocks: 2 + render: + _target_: nuplan_extent.planning.training.modeling.models.renders.gump_render.GUMPRender + _convert_: all + postprocessor: + _target_: nuplan_extent.planning.training.modeling.models.post_processors.gump_naive_planner.GUMPNaivePlanner + _convert_: all + future_trajectory_sampling: + _target_: nuplan.planning.simulation.trajectory.trajectory_sampling.TrajectorySampling + _convert_: all + num_poses: 8 + time_horizon: 4.0 + feature_builders: + - _target_: nuplan_extent.planning.training.preprocessing.feature_builders.nexus_feature_builder.NexusFeatureBuilder + _convert_: all + agent_features: + - VEHICLE + - PEDESTRIAN + - BICYCLE + radius: 100.0 + longitudinal_offset: 0.0 + past_time_horizon: 2.0 + past_num_steps: 4 + future_time_horizon: 8.0 + future_num_steps: 16 + num_max_agents: + - 128 + - 64 + - 32 + map_features: + - LANE + - LANE_CONNECTOR + - STOP_LINE + - CROSSWALK + map_num_points_polylines: 21 + map_dim_points_polyline: 7 + map_num_max_polylines: 128 + target_builders: + - _target_: nuplan_extent.planning.training.preprocessing.feature_builders.ego_trajectory_with_past_target_builder.EgoTrajectoryWithPastTargetBuilder + _convert_: all + future_trajectory_sampling: + _target_: nuplan.planning.simulation.trajectory.trajectory_sampling.TrajectorySampling + _convert_: all + num_poses: 8 + time_horizon: 4.0 + num_paralell_scenario: 1 + downstream_task: scenario_extrapolation + +checkpoint: data/alg_engine/ckpts/nuplan.ckpt +digitaltwin_data_root: data/sim_engine/assets/navtrain/assets +openscene_data_root: data/raw/openscene-v1.1 + +# BWM temporal settings. SceneFilter temporal fields are intentionally ignored. +num_history_frames: 4 +num_future_frames: 16 + +scenario_builder: + _target_: nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario_builder.NuPlanScenarioBuilder + _convert_: all + data_root: data/raw/nuplan/dataset/nuplan-v1.1/trainval + map_root: data/raw/nuplan/dataset/maps + sensor_root: data/raw/nuplan/dataset/nuplan-v1.1/sensor_blobs + db_files: null + map_version: nuplan-maps-v1.0 + include_cameras: false + max_workers: null + verbose: false + vehicle_parameters: + _target_: nuplan.common.actor_state.vehicle_parameters.VehicleParameters + _convert_: all + width: 2.297 + front_length: 4.049 + rear_length: 1.127 + cog_position_from_rear_axle: 1.67 + height: 1.777 + wheel_base: 3.089 + vehicle_name: pacifica + vehicle_type: gen1 + scenario_mapping: + _target_: nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario_utils.ScenarioMapping + _convert_: all + subsample_ratio_override: 0.5 diff --git a/projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml b/projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml new file mode 100644 index 0000000..a711ec9 --- /dev/null +++ b/projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml @@ -0,0 +1,10 @@ +# Layered BWM scenario configuration. Generation settings are inherited from +# projects/BWM/configs/default.yaml. + +scenario_name: navtrain_50pct_ep_1pct + +# This key currently selects the DigitalTwin asset corpus used by the pipeline. +data_type: navtrain_ep_per1 + +# Scene membership is owned by AlgEngine's SceneFilter config. +scene_filter_path: projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yaml diff --git a/projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct_time_pose_fix_v1.yaml b/projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct_time_pose_fix_v1.yaml new file mode 100644 index 0000000..6370d0b --- /dev/null +++ b/projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct_time_pose_fix_v1.yaml @@ -0,0 +1,5 @@ +# Regenerate the existing selection after the time and ego-pose corrections. +# Keep a separate output directory so previous staging files are not reused. +scenario_name: navtrain_50pct_ep_1pct_time_pose_fix_v1 +data_type: navtrain_ep_per1 +scene_filter_path: projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yaml diff --git a/projects/BWM/environment.yml b/projects/BWM/environment.yml new file mode 100644 index 0000000..3aa7717 --- /dev/null +++ b/projects/BWM/environment.yml @@ -0,0 +1,13 @@ +name: bwm + +channels: + - pytorch + - nvidia + - conda-forge + +dependencies: + - python=3.9 + - pip>=24 + - pytorch=2.3.0 + - torchvision=0.18.0 + - pytorch-cuda=12.1 diff --git a/projects/BWM/nuplan_extent/__init__.py b/projects/BWM/nuplan_extent/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/common/geometry/oriented_box.py b/projects/BWM/nuplan_extent/common/geometry/oriented_box.py new file mode 100644 index 0000000..422a30a --- /dev/null +++ b/projects/BWM/nuplan_extent/common/geometry/oriented_box.py @@ -0,0 +1,159 @@ +import numpy as np +import numpy.typing as npt + + +def box_to_corners(boxes: npt.NDArray) -> npt.NDArray: + """Calculate the corners of the boxes. + + :param boxes: boxes of shape [..., 5], each box is represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + :return: corners of the boxes of shape [..., 4, 2]. The four corners are in + the order of front-left, front-right, back-right and back-left. + """ + o = boxes[..., :2] + heading = boxes[..., 2] + half_length = boxes[..., 3] + half_width = boxes[..., 4] + c = np.cos(heading) + s = np.sin(heading) + half_length_vec = half_length[..., None] * np.stack([c, s], axis=-1) + half_width_vec = half_width[..., None] * np.stack([-s, c], axis=-1) + fl = half_length_vec + half_width_vec + fr = half_length_vec - half_width_vec + corners = np.stack([fl, fr, -fl, -fr], axis=-2) # shape [..., 4, 2] + return corners + o[..., None, :] + + +def line_segment_intersected(a1: npt.NDArray, a2: npt.NDArray, b1: npt.NDArray, + b2: npt.NDArray) -> npt.NDArray[np.bool_]: + """Whether two line segments intersect. + + Whether line segment a1--a2 intersects with line segment b1--b2. + + `a1`, `a2`, `b1`, `b2` should be broadcastable. + https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line_segment + + :param a1: [..., 2] + :param a2: [..., 2] + :param b1: [..., 2] + :param b2: [..., 2] + :return: array of bool indicating whether each pair of line segments + intersect + """ + err = np.geterr() + np.seterr(all='ignore') + + da = a1 - a2 + dab = a1 - b1 + db = b1 - b2 + d = da[..., 0] * db[..., 1] - da[..., 1] * db[..., 0] + t = (dab[..., 0] * db[..., 1] - dab[..., 1] * db[..., 0]) / d + u = (dab[..., 0] * da[..., 1] - dab[..., 1] * da[..., 0]) / d + + np.seterr(**err) + return (0 <= t) & (t <= 1) & (0 <= u) & (u <= 1) + + +def to_box_frame(p: npt.NDArray, box: npt.NDArray) -> npt.NDArray: + """Transform points to the frame of the box. + + The box frame is defined as follows: + - the origin is the center of the box + - the x axis is along the heading of the box + - the y axis is perpendicular to the x axis and pointing to the left + + `p.shape[:-1]` and `box.shape[:-1]` should be broadcastable. + + :param p: a batch of points of shape [..., 2] + :param box: a batch of boxes of shape [..., 5], each box is represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + :return: x, y coordinates of the points in the frame of the box + """ + o = box[..., :2] + heading = box[..., 2] + c = np.cos(heading) + s = np.sin(heading) + q = p - o + x = q[..., 0] * c + q[..., 1] * s + y = q[..., 1] * c - q[..., 0] * s + + return x, y + + +def point_box_edge_dist(p: npt.NDArray, box: npt.NDArray) -> npt.NDArray: + """Calculate the distance between a point and the edges of a box. + + `p.shape[:-1]` and `box.shape[:-1]` should be broadcastable. + + :param p: [..., 2] + :param box: box of shape [..., 5], each box is represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + :return: distance between the point and the box + """ + x, y = to_box_frame(p, box) + + half_length = box[..., 3] + half_width = box[..., 4] + + dx = (x - np.clip(x, -half_length, half_length))**2 + dy = (y - np.clip(y, -half_width, half_width))**2 + + d1 = (x - half_length)**2 + dy + d2 = (x + half_length)**2 + dy + d3 = dx + (y - half_width)**2 + d4 = dx + (y + half_width)**2 + return np.sqrt(np.stack([d1, d2, d3, d4], axis=-1).min(axis=-1)) + + +def point_inside_box(p: npt.NDArray, + box: npt.NDArray) -> npt.NDArray[np.bool_]: + """Whether a point is inside a box. + + `p.shape[:-1]` and `box.shape[:-1]` should be broadcastable. + + :param p: a batch of points of shape [..., 2] + :param box: a batch of boxes of shape [..., 5], each box is represented by + 5 numbers: center_x, center_y, heading, half_length, half_width + :return: array of bool indicating whether each point is inside the + corresponding box + """ + x, y = to_box_frame(p, box) + half_length = box[..., 3] + half_width = box[..., 4] + return (np.abs(x) <= half_length) & (np.abs(y) <= half_width) + + +def box_box_dist(box1: npt.NDArray, box2: npt.NDArray) -> npt.NDArray: + """Calculate the distance between two boxes. + + The distance is defined as the minimum distance between any two points on + the two boxes. + + `box1.shape[:-1]` and `box2.shape[:-1]` should be broadcastable. + + :param box1: a batch of boxes of shape [..., 5], each box is represented by + 5 numbers: center_x, center_y, heading, half_length, half_width + :param box2: a batch of boxes of shape [..., 5], each box is represented by + 5 numbers: center_x, center_y, heading, half_length, half_width + :return: distances between corresponding boxes + """ + corners1 = box_to_corners(box1) + corners2 = box_to_corners(box2) + d1 = point_box_edge_dist(corners1, box2[..., None, :]) + d2 = point_box_edge_dist(corners2, box1[..., None, :]) + d = np.minimum(d1, d2).min(axis=-1) + + inside = point_inside_box(box1[..., :2], box2) + inside = inside | point_inside_box(box2[..., :2], box1) + + a1 = corners1 + a2 = a1[..., [1, 2, 3, 0], :] + b1 = corners2 + b2 = b1[..., [1, 2, 3, 0], :] + intersected = line_segment_intersected( + a1[..., None, :, :], a2[..., None, :, :], b1[..., :, None, :], + b2[..., :, None, :]) + intersected = inside | intersected.any(axis=(-2, -1)) + d[intersected] = 0 + + return d diff --git a/projects/BWM/nuplan_extent/planning/__init__.py b/projects/BWM/nuplan_extent/planning/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/scenario_builder/prepared_scenario.py b/projects/BWM/nuplan_extent/planning/scenario_builder/prepared_scenario.py new file mode 100644 index 0000000..2b83887 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/scenario_builder/prepared_scenario.py @@ -0,0 +1,713 @@ +from abc import ABC, abstractmethod +import copy +import math +import numpy as np +import torch +from typing import Any, Dict, List, Tuple + +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.common.actor_state.vehicle_parameters import VehicleParameters +from nuplan.common.actor_state.ego_state import EgoState +from nuplan.common.actor_state.state_representation import StateSE2, StateVector2D, TimePoint +from nuplan.planning.training.preprocessing.features.abstract_model_feature import AbstractModelFeature + + +class MissingFeatureAtCenterException(Exception): + pass + + +class MissingFeatureAtIterationException(Exception): + pass + + +class MissingFeatureException(Exception): + pass + + +NONEXISTENT_FEATURE = object() + +class NpAgentState(np.ndarray): + """A numpy array wrapper for other agent state.""" + dim = 8 + track_token_index = 0 + vx_index = 1 + vy_index = 2 + heading_index = 3 + width_index = 4 + length_index = 5 + x_index = 6 + y_index = 7 + + @property + def data(self): + return self + + @property + def track_token(self): + return self[..., 0] + + @property + def vx(self): + return self[..., 1] + + @property + def vy(self): + return self[..., 2] + + @property + def heading(self): + return self[..., 3] + + @property + def width(self): + return self[..., 4] + + @property + def length(self): + return self[..., 5] + + @property + def x(self): + return self[..., 6] + + @property + def y(self): + return self[..., 7] + + + def bounding_box(self): + """Get the bounding box of the ego vehicle. + + :return The bounding box of the ego vehicle, represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + """ + x = self.x + y = self.y + heading = self.heading + half_length = self.length / 2 + half_width = self.width / 2 + return np.stack([x, y, heading, half_length, half_width], axis=-1) + + def transform(self, trans, heading): + xy = np.stack([self.x, self.y], axis=-1) @ trans[:2, :2].T + trans[:2, 2] + vxy = np.stack([self.vx, self.vy], axis=-1) @ trans[:2, :2].T + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.vx_index] = vxy[..., 0] + self[..., self.vy_index] = vxy[..., 1] + self[..., self.heading_index] = self.heading - heading + + def inverse_transform(self, trans, heading): + xy = (np.stack([self.x, self.y], axis=-1) - trans[:2, 2]) @ np.linalg.inv(trans[:2, :2].T) + vxy = np.stack([self.vx, self.vy], axis=-1) @ np.linalg.inv(trans[:2, :2].T) + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.vx_index] = vxy[..., 0] + self[..., self.vy_index] = vxy[..., 1] + self[..., self.heading_index] = self.heading + heading + + +class NpEgoState(np.ndarray): + """A numpy array wrapper for ego state.""" + + dim = 17 + time_index = 0 + x_index = 1 + y_index = 2 + heading_index = 3 + vel_lon_index = 4 + vel_lat_index = 5 + acc_lon_index = 6 + acc_lat_index = 7 + tire_steering_angle_index = 8 + yaw_rate_index = 9 + yaw_acc_index = 10 + wheel_base_index = 15 + + @property + def data(self): + return self + + @property + def time(self): + # in seconds + return self[..., 0] + + @property + def x(self): + """Real axle x coordinate.""" + return self[..., 1] + + @property + def y(self): + """Real axle y coordinate.""" + return self[..., 2] + + @property + def heading(self): + return self[..., 3] + + @property + def vel_lon(self): + return self[..., 4] + + @property + def vel_lat(self): + return self[..., 5] + + @property + def acc_lon(self): + return self[..., 6] + + @property + def acc_lat(self): + return self[..., 7] + + @property + def tire_steering_angle(self): + return self[..., 8] + + @property + def yaw_rate(self): + return self[..., 9] + + @property + def yaw_acc(self): + return self[..., 10] + + @property + def width(self): + return self[..., 11] + + @property + def front_length(self): + return self[..., 12] + + @property + def rear_length(self): + return self[..., 13] + + @property + def cog_position_from_rear_axle(self): + return self[..., 14] + + @property + def wheel_base(self): + return self[..., 15] + + @property + def height(self): + return self[..., 16] + + @property + def rear_axle_pose(self): + return self[..., self.x_index:self.x_index + 3] + + @property + def rear_axle_velocity_2d(self): + return self[..., self.vel_lon_index:self.vel_lon_index + 2] + + @property + def rear_axle_acceleration_2d(self): + return self[..., self.acc_lon_index:self.acc_lon_index + 2] + + def bounding_box(self): + """Get the bounding box of the ego vehicle. + + :return The bounding box of the ego vehicle, represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + """ + heading = self.heading + c = np.cos(heading) + s = np.sin(heading) + half_length = (self.rear_length + self.front_length) / 2 + half_width = self.width / 2 + d = half_length - self.rear_length + x = self.x + d * c + y = self.y + d * s + return np.stack([x, y, heading, half_length, half_width], axis=-1) + + def to_nuplan_ego_state(self) -> EgoState: + assert self.ndim == 1, "Only support converting 1 ego state at a time" + vehicle_parameters = VehicleParameters( + width=self.width, + front_length=self.front_length, + rear_length=self.rear_length, + cog_position_from_rear_axle=self.cog_position_from_rear_axle, + wheel_base=self.wheel_base, + height=self.height if self.height == 0.0 else None, + vehicle_name="pacifica", # same as Nuplan pacifica + vehicle_type="gen1", # same as Nuplan pacifica + ) + return EgoState.build_from_rear_axle( + rear_axle_pose=StateSE2(*self.rear_axle_pose), + rear_axle_velocity_2d=StateVector2D(*self.rear_axle_velocity_2d), + rear_axle_acceleration_2d=StateVector2D(*self.rear_axle_acceleration_2d), + tire_steering_angle=self.tire_steering_angle, + time_point=TimePoint(1e6 * float(self.time)), + vehicle_parameters=vehicle_parameters, + ) + + def transform(self, trans, heading): + xy = np.stack([self.x, self.y], axis=-1) @ trans[:2, :2].T + trans[:2, 2] + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.heading_index] = self.heading - heading + + def inverse_transform(self, trans, heading): + xy = (np.stack([self.x, self.y], axis=-1) - trans[:2, 2]) @ np.linalg.inv(trans[:2, :2].T) + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.heading_index] = self.heading + heading + + def with_range(self, map_range, delta): + mask = (self.x >= (map_range[0] + delta)) & (self.x <= (map_range[1] - delta)) & (self.y >= (map_range[2] + delta)) & (self.y <= (map_range[3] - delta)) + return mask.view(np.ndarray) + + +def _radian(d): + """Convert the given radian to [-pi, pi] range.""" + pi = math.pi + if d > pi: + return d - 2 * pi + elif d < -pi: + return d + 2 * pi + else: + return d + + +def _get_ego_state(scenario: AbstractScenario, iter: int): + """Get the ego state at the given iteration. + + :param scenario: The scenario to get the ego state from. + :param iter: The iteration to get the ego state for. + """ + if iter < 0: + gen = scenario.get_ego_past_trajectory( + 0, -iter * scenario.database_interval, 1) + elif iter >= scenario.get_number_of_iterations(): + n = scenario.get_number_of_iterations() - 1 + gen = scenario.get_ego_future_trajectory( + n, (iter - n) * scenario.database_interval, 1) + else: + return scenario.get_ego_state_at_iteration(iter) + ego_states = list(gen) + if len(ego_states) == 0: + return None + else: + return ego_states[0] + + +class PreparedScenario(AbstractModelFeature): + """Prepared scenario. + + A prepared scenario stores precomputed features to facilitate faster feature + extraction during training. + + The main mechanism is "add_feature/get_feature" series of methods. + The "add_feature" methods are used to add features to the prepared scenario. + The "get_feature" methods are used to get features from the prepared scenario. + + During the stage of preparing the scenario, if a feature can be found in + the prepared scenario, there is no need to calculate it again. + """ + + def __init__(self): + self._data = {} + self._backup = {} + self._mission_goal = None + + def serialize(self) -> Dict[str, Any]: + assert self._scenario is not None, "Scenario is not prepared yet" + self._populate_yaw_rate_and_acc() + return self._data + + def _populate_yaw_rate_and_acc(self): + """Populate yaw_rate and yaw_acc for ego state.""" + ego_states = self.get_feature('ego_state') + iters = sorted(ego_states.keys()) + ego_state = ego_states[iters[0]] + prev_state: EgoState = _get_ego_state(self._scenario, iters[0] - 1) + prev_prev_state: EgoState = _get_ego_state(self._scenario, + iters[0] - 2) + if prev_state is not None: + prev_yaw = prev_state.rear_axle.heading + prev_time = prev_state.time_seconds + else: + prev_yaw = ego_state[NpEgoState.heading_index] + prev_time = ego_state[ + NpEgoState.time_index] - self._scenario.database_interval + if prev_prev_state is not None: + prev_yaw_rate = _radian( + prev_yaw - prev_prev_state.rear_axle.heading) / ( + prev_time - prev_prev_state.time_seconds) + else: + prev_yaw_rate = 0.0 + for i in iters: + ego_state = ego_states[i] + yaw = ego_state[NpEgoState.heading_index] + t = ego_state[NpEgoState.time_index] + dt = t - prev_time + yaw_rate = _radian(yaw - prev_yaw) / dt + ego_state[NpEgoState.yaw_rate_index] = yaw_rate + ego_state[NpEgoState. + yaw_acc_index] = (yaw_rate - prev_yaw_rate) / dt + prev_time = t + prev_yaw = yaw + prev_yaw_rate = yaw_rate + + @classmethod + def deserialize(cls, data: Dict[str, Any]) -> AbstractModelFeature: + scenario = PreparedScenario() + scenario._data = data + scenario._mission_goal = data['mission_goal'] + scenario._offset = data['offset'] + scenario._iteration_start = data['iteration_start'] + scenario._iteration_end = data['iteration_end'] + scenario._iteration_step = data['iteration_step'] + # the tire_steering_angle from NuPlanScenario is always zero (see + # get_ego_state_for_lidarpc_token_from_db()). So we populate it here + scenario._populate_tire_steering_angle() + return scenario + + def _populate_tire_steering_angle(self): + for ego_state in self._data['ego_state'].values(): + yaw_rate = ego_state[NpEgoState.yaw_rate_index] + v = ego_state[NpEgoState.vel_lon_index] + # the velocity can be inaccurate when it is very small + # in this case, we set the curvature to 0 + curvature = yaw_rate / v if abs(v) > 0.1 else 0 + tire_steering_angle = np.arctan( + curvature * ego_state[NpEgoState.wheel_base_index]) + ego_state[NpEgoState. + tire_steering_angle_index] = tire_steering_angle + + def to_feature_tensor(self) -> AbstractModelFeature: + raise NotImplementedError() + + def to_device(self, device: torch.device) -> AbstractModelFeature: + raise NotImplementedError() + + def unpack(self) -> List[AbstractModelFeature]: + raise NotImplementedError() + + def prepare_scenario(self, scenario: AbstractScenario, + iterations: range) -> None: + """Prepare the basic information of the scenario for the given iterations. + + :param scenario: The scenario to prepare. + :param iterations: The iterations to prepare the scenario for. + """ + self._scenario = scenario + self._mission_goal = scenario.get_mission_goal() + vp = scenario.get_ego_state_at_iteration( + 0).car_footprint.vehicle_parameters + self._vehical_parameters = [ + vp.width, vp.front_length, vp.rear_length, + vp.cog_position_from_rear_axle, vp.wheel_base, + vp.height if vp.height is not None else 0.0 + ] + timestamps = [] + for i in iterations: + ego_state = scenario.get_ego_state_at_iteration(i) + if i == iterations.start: + self._offset = ego_state.rear_axle.point.array + self._data['offset'] = self._offset + self.add_ego_state_at_iteration(ego_state, i) + timestamps.append(scenario.get_time_point(i).time_us) + + self._data['log_name'] = scenario.log_name + self._data['token'] = scenario.token + self._data['iteration_start'] = iterations.start + self._data['iteration_end'] = iterations.stop + self._data['iteration_step'] = iterations.step + self._data['timestamps'] = np.array(timestamps) + self._data['database_interval'] = scenario.database_interval + mission_goal = scenario.get_mission_goal() + if mission_goal is not None: + self._data['mission_goal'] = StateSE2( + mission_goal.x - float(self._offset[0]), + mission_goal.y - float(self._offset[1]), mission_goal.heading) + else: + # For example, P3CScenario does not have mission goal + self._data['mission_goal'] = None + self._iteration_start = iterations.start + self._iteration_end = iterations.stop + self._iteration_step = iterations.step + + def add_ego_state_at_iteration(self, ego_state: EgoState, iteration: int): + """Add ego state at the given iteration to the prepared scenario. + + :param ego_state: The scenario to prepare. + :param iteration: The iteration to prepare the scenario for. + """ + ego_state_vec = list(ego_state) + ego_state_vec[0] *= 1e-6 # convert to seconds + yaw_state = [0, 0.] # placeholder for yaw_rate and yaw_acc + ego_state = np.array(ego_state_vec + yaw_state + + self._vehical_parameters) + ego_state[NpEgoState.x_index:NpEgoState.y_index + 1] -= self._offset + self.add_feature_at_iteration("ego_state", ego_state, iteration) + + def get_offset(self) -> np.ndarray: + """"The origin of the prepared scenario in the original map coordinates. + + All the cooordinates in prepared scenario are relative to this origin. + So when adding features to the prepared scenario, the coordinates be the + original map coordinates minus this offset. + """ + return self._offset + + def get_feature(self, feature_name: str) -> Any: + """Get feature with the given name. + + :param feature_name: The name of the feature. None if the feature does + not exist. + """ + feature = self._data.get(feature_name, NONEXISTENT_FEATURE) + if feature is NONEXISTENT_FEATURE: + raise MissingFeatureException( + f"Missing feature {feature_name} for " + f"{self._data['log_name']}:{self._data['token']}") + return feature + + def feature_exists(self, feature_name: str) -> bool: + """Whether there is feature with the given name. + + :param feature_name: The name of the feature. + :return True if there is feature with the given name, False otherwise. + """ + return feature_name in self._data + + def add_feature(self, feature_name: str, feature_value: Any): + """Add feature with the given name. + + :param feature_name: The name of the feature. + :param feature_value: The value of the feature. + """ + self._data[feature_name] = feature_value + + def get_feature_at_center(self, feature_name: str, + center: Tuple[int, int]) -> Any: + """Get feature at the given discretized center. + + :param feature_name: The name of the feature. + :param center: The discritized center of the feature. + """ + if feature_name not in self._data: + raise MissingFeatureException( + f"Missing feature {feature_name} for " + f"{self._data['log_name']}:{self._data['token']}") + feature = self._data[feature_name] + f = feature.get(center, NONEXISTENT_FEATURE) + if f is NONEXISTENT_FEATURE: + raise MissingFeatureAtCenterException( + f"Missing feature {feature_name} at center {center} for " + f"{self._data['log_name']}:{self._data['token']}") + return f + + def feature_exists_at_center(self, feature_name: str, + center: Tuple[int, int]) -> bool: + """Whether there is feature at the given discretized center. + + :param feature_name: The name of the feature. + :param center: The discritized center of the feature. + :return True if there is feature at the given discretized center, False otherwise. + """ + if feature_name not in self._data: + return False + feature = self._data[feature_name] + return center in feature + + def add_feature_at_center(self, feature_name: str, feature_value, + center: Tuple[int, int]): + """Add feature at the given discretized center. + + :param feature_name: The name of the feature. + :param feature_value: The value of the feature. + :param center: The discritized center of the feature. + """ + if feature_name not in self._data: + self._data[feature_name] = {} + feature = self._data[feature_name] + else: + feature = self._data[feature_name] + feature[center] = feature_value + + def get_feature_at_iteration(self, feature_name: str, + iteration: int) -> Any: + """Get feature at the given iteration. + + :param feature_name: The name of the feature. + :param iteration: The iteration to get the feature for, it should be + the iteration in the original scenario. + """ + if feature_name not in self._data: + raise MissingFeatureException( + f"Missing feature {feature_name} for " + f"{self._data['log_name']}:{self._data['token']}") + feature = self._data[feature_name] + f = feature.get(iteration, NONEXISTENT_FEATURE) + if f is NONEXISTENT_FEATURE: + raise MissingFeatureAtIterationException( + f"Missing feature {feature_name} at iteration {iteration} for " + f"{self._data['log_name']}:{self._data['token']}") + return f + + def feature_exists_at_iteration(self, feature_name: str, + iteration: int) -> bool: + """Whether there is feature at the given iteration. + + :param feature_name: The name of the feature. + :param iteration: The iteration to get the feature for, it should be + the iteration in the original scenario. + :return True if there is feature at the given iteration, False otherwise. + """ + if feature_name not in self._data: + return False + feature = self._data[feature_name] + return iteration in feature + + def add_feature_at_iteration(self, feature_name: str, feature_value, + iteration: int): + """Add feature at the given iteration. + + :param feature_name: The name of the feature. + :param feature_value: The value of the feature. + :param iteration: The iteration to get the feature for. + """ + if feature_name not in self._data: + self._data[feature_name] = {} + feature = self._data[feature_name] + else: + feature = self._data[feature_name] + feature[iteration] = feature_value + + @property + def log_name(self) -> str: + """The log name of the original scenario.""" + return self._data['log_name'] + + @property + def token(self) -> str: + """The token of the original scenario.""" + return self._data['token'] + + @property + def database_interval(self) -> float: + """The database interval of the original scenario.""" + return self._data['database_interval'] + + @property + def iterations(self) -> range: + """All the prepared iterations.""" + return range(self._iteration_start, self._iteration_end, + self._iteration_step) + + def get_mission_goal(self) -> StateSE2: + return self._data['mission_goal'] + + def _iter_to_index(self, iteration: int) -> int: + return (iteration - self._iteration_start) // self._iteration_step + + def get_ego_state_at_iteration(self, iteration: int) -> NpEgoState: + """Get the ego state at the given iteration. + + Note that the state is in coordinates of the prepared scenario (i.e., + the cooridinates of the original scenario minus the offset). + + :param iteration: The iteration to get the time point for, it should be + the iteration in the original scenario. + :return The ego state at the given iteration. + """ + return self.get_feature_at_iteration('ego_state', + iteration).view(NpEgoState) + + def get_number_of_iterations(self) -> int: + """The number of iterations in the original scenario.""" + return self._iteration_end + + def get_time_point(self, iteration: int) -> TimePoint: + """Get the time point of the given iteration. + + :param iteration: The iteration to get the time point for, it should be + the iteration in the original scenario. + """ + i = self._iter_to_index(iteration) + return TimePoint(time_us=int(self._data['timestamps'][i])) + + def backup_feature(self, feature_name: str): + """Backup the feature with the given name. + + Make a copy of the feature and store it in the backup. Note that later + backup will overwrite the previous backup. + + :param feature_name: The name of the feature. + """ + self._backup[feature_name] = copy.deepcopy(self._data[feature_name]) + + def get_backup_feature(self, feature_name: str): + """Get the backup feature with the given name. + + :param feature_name: The name of the feature. + """ + return self._backup[feature_name] + + def restore_feature(self, feature_name: str): + """Restore the feature with the given name. + + The feature with name `feature_name` will be restored from its backup from + the last call of `backup_feature`. + + :param feature_name: The name of the feature. + """ + self._data[feature_name] = copy.deepcopy(self._backup[feature_name]) + + +class ScenarioPreparer(ABC): + """Base class for scenario preparer. + + A scenario preparer is used to prepare PreparedScenario for future use. + """ + + @abstractmethod + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + """Prepare the scenario for the given iterations. + + :param scenario: The scenario to prepare. + :param prepared_scenario: The prepared scenario to store the prepared + features. + :param iterations: The iterations to prepare the scenario for. + """ + pass + + +class PreparedScenarioFeatureBuilder(ScenarioPreparer): + """Feature builder for horizon features.""" + + @abstractmethod + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + """Prepare the scenario for the given iterations. + + :param scenario: The scenario to prepare. + :param prepared_scenario: The prepared scenario to store the prepared + features. + :param iterations: The iterations to prepare the scenario for. + """ + pass + + @abstractmethod + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> AbstractModelFeature: + """Get features from the prepared scenario. + + :param scenario: The prepared scenario. + :param iteration: The iteration to get the features for. + :param ego_state: The ego state at the given iteration. + """ + pass diff --git a/projects/BWM/nuplan_extent/planning/training/__init__.py b/projects/BWM/nuplan_extent/planning/training/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/__init__.py b/projects/BWM/nuplan_extent/planning/training/modeling/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/__init__.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/__init__.py new file mode 100644 index 0000000..70825c7 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/__init__.py @@ -0,0 +1 @@ +# Models package initialization \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/models/diffusion.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/models/diffusion.py new file mode 100644 index 0000000..3bb807e --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/models/diffusion.py @@ -0,0 +1,476 @@ +import math +from abc import abstractmethod +from typing import Tuple +import os +import torch +from torch import Tensor, nn + +from nuplan_extent.planning.training.modeling.models.encoders.perciever_context_encoder import ( + CrossAttention, + FeedForward, + MultiHeadAttention, +) + + +def modulate(x, shift, scale): + return x * (1 + scale) + shift + + +def timestep_embedding(timesteps, dim, max_period=10000): + """ + Create sinusoidal timestep embeddings. + + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + if timesteps.dim() == 0: + timesteps = timesteps.unsqueeze(0) + + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) + * torch.arange(start=0, end=half, dtype=torch.float32) + / half + ).to(device=timesteps.device) + args = timesteps[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + +class AdaLNBlock(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 4, + drop: float = 0.0, + mlp_ratio: int = 4, + ): + super().__init__() + + self.norm1 = nn.LayerNorm(dim, eps=1e-6, elementwise_affine=False) + self.attn = MultiHeadAttention(kv_dim=dim, q_dim=dim, num_heads=num_heads) + self._num_heads = num_heads + + self.norm2 = nn.LayerNorm(dim, eps=1e-6, elementwise_affine=False) + self.mlp = FeedForward(dim, widening_factor=mlp_ratio, dropout=drop) + + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True) + ) + + @abstractmethod + def pre_attn( + self, scene_tensor: Tensor, context: Tensor, valid_mask: Tensor + ) -> Tuple[Tensor, Tensor, Tensor]: + raise NotImplementedError + + @abstractmethod + def post_attn(self, scene_tensor: Tensor, batch_size: int) -> Tensor: + raise NotImplementedError + + def forward(self, x: Tensor, c: Tensor, valid_mask: Tensor) -> Tensor: + B, NA, NT, ND = x.size() + + x, attn_mask, c = self.pre_attn(x, c, valid_mask) + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( + self.adaLN_modulation(c).chunk(6, dim=-1) + ) + queries = modulate(self.norm1(x), shift_msa, scale_msa) + x = x + gate_msa * self.attn( + queries, + queries, + attn_mask.unsqueeze(1).repeat(1, self._num_heads, 1, 1).bool(), + ) + x = x + gate_mlp * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) + x = self.post_attn(x, B) + return x + + +class TemporalBlock(AdaLNBlock): + def pre_attn( + self, scene_tensor: Tensor, context: Tensor, valid_mask: Tensor + ) -> Tuple[Tensor, Tensor, Tensor]: + """ + scene_tensor: tensor of shape (B, NA, NT, ND) + valid_mask: tensor of shape (B, NA, NT) + """ + B, NA, NT, ND = scene_tensor.size() + scene_tensor = scene_tensor.reshape(B * NA, NT, ND) + context = context.reshape(B * NA, NT, ND) + + # reshape the valid mask to be (B * NA, NT, 1) + valid_mask = valid_mask.unsqueeze(-1).reshape(B * NA, NT, 1) + # take the outer product of the valid mask with itself to get the attention mask + attn_mask = valid_mask @ valid_mask.transpose(1, 2) + + return scene_tensor, attn_mask, context + + def post_attn(self, scene_tensor: Tensor, batch_size: int) -> Tensor: + return scene_tensor.reshape( + batch_size, -1, scene_tensor.size(-2), scene_tensor.size(-1) + ) + + +class SpatialBlock(AdaLNBlock): + def pre_attn( + self, scene_tensor: Tensor, context: Tensor, valid_mask: Tensor + ) -> Tuple[Tensor, Tensor, Tensor]: + """ + scene_tensor: tensor of shape (B, NA, NT, ND) + valid_mask: tensor of shape (B, NA, NT) + """ + B, NA, NT, ND = scene_tensor.size() + scene_tensor = scene_tensor.permute(0, 2, 1, 3).reshape(B * NT, NA, ND) + context = context.permute(0, 2, 1, 3).reshape(B * NT, NA, ND) + + # reshape the valid mask to be (B * NT, NA, 1) + valid_mask = valid_mask.permute(0, 2, 1).unsqueeze(-1).reshape(B * NT, NA, 1) + # take the outer product of the valid mask with itself to get the attention mask + attn_mask = valid_mask @ valid_mask.transpose(1, 2) + + # attn_mask = torch.ones(B * NT, NA, NA, device=scene_tensor.device) + return scene_tensor, attn_mask, context + + def post_attn(self, scene_tensor: Tensor, batch_size: int) -> Tensor: + return scene_tensor.reshape( + batch_size, -1, scene_tensor.size(-2), scene_tensor.size(-1) + ).permute(0, 2, 1, 3) + + +class CombinedAttention(nn.Module): + def __init__( + self, + hidden_dim: int, + ): + super().__init__() + self.temporal_attention = TemporalBlock(hidden_dim) + self.spatial_attention = SpatialBlock(hidden_dim) + + def forward( + self, scene_tensor: Tensor, context: Tensor, valid_mask: Tensor + ) -> Tensor: + scene_tensor = self.temporal_attention(scene_tensor, context, valid_mask) + scene_tensor = self.spatial_attention(scene_tensor, context, valid_mask) + return scene_tensor + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + """ + + def __init__(self, hidden_size, frequency_embedding_size=256): + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + self.frequency_embedding_size = frequency_embedding_size + + def forward(self, t): + t_freq = timestep_embedding(t, self.frequency_embedding_size) + t_emb = self.mlp(t_freq) + return t_emb + + +class MLP(nn.Module): + """Transformer Feed-Forward network.""" + + def __init__(self, input_dim: int, output_dim: int, widening_factor: int = 1): + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(input_dim, output_dim * widening_factor), + nn.GELU(), + nn.Linear(output_dim * widening_factor, output_dim), + ) + + def forward(self, x: torch.Tensor): + return self.mlp(x) + + +class Nexus(nn.Module): + """Based on the Nexus paper. Perciever I/O structure""" + + def __init__( + self, + nblocks: int = 4, + hidden_dim: int = 256, + scene_tensor_dim: int = 8, + cross_attention_num_heads: int = 4, + ): + super().__init__() + self.hidden_dim = hidden_dim + self.scene_tensor_dim = scene_tensor_dim + self._num_heads = cross_attention_num_heads + self.cross_attention = CrossAttention( + kv_dim=hidden_dim, + q_dim=hidden_dim, + qk_out_dim=hidden_dim, + v_out_dim=hidden_dim, + num_heads=self._num_heads, + ) + self.input_proj = nn.Linear( + 3 * scene_tensor_dim, hidden_dim, bias=False + ) + # self.input_proj = nn.Linear( + # scene_tensor_dim, hidden_dim, bias=False + # ) + self.physical_timestep_embeddor = TimestepEmbedder(hidden_dim) + self.diffusion_timestep_embeddor = TimestepEmbedder(hidden_dim) + + self.backbone = nn.Sequential( + *[CombinedAttention(hidden_dim) for _ in range(nblocks)] + ) + + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(hidden_dim, 2 * hidden_dim, bias=True) + ) + self.norm_final = nn.LayerNorm(hidden_dim, elementwise_affine=False, eps=1e-6) + self.output_proj = nn.Linear(hidden_dim, scene_tensor_dim) + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + self.apply(_basic_init) + + # init first layer + w = self.input_proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.constant_(self.input_proj.bias, 0) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.physical_timestep_embeddor.mlp[0].weight, std=0.02) + nn.init.normal_(self.physical_timestep_embeddor.mlp[2].weight, std=0.02) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.diffusion_timestep_embeddor.mlp[0].weight, std=0.02) + nn.init.normal_(self.diffusion_timestep_embeddor.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in DiT blocks: + for block in self.backbone: + nn.init.constant_(block.temporal_attention.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.temporal_attention.adaLN_modulation[-1].bias, 0) + nn.init.constant_(block.spatial_attention.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.spatial_attention.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.output_proj.weight, 0) + nn.init.constant_(self.output_proj.bias, 0) + + def forward( + self, + local_context: torch.Tensor, + diffused_scene_tensor: torch.Tensor, + valid_mask: torch.Tensor, + diffusion_times: torch.Tensor, + global_context: torch.Tensor, + ): + """ + Args: + scene_tensor: tensor of shape (B, NA, NT, ND) + valid_mask: tensor of shape (B, NA, NT) + diffusion_times: tensor of shape (B, NA, NT) + valid_mask: tensor of shape (B, NA, NT) + + """ + # x is the queries, and global context is the keys and values + B, NA, NT, ND = local_context.size() + + queries = self.input_proj.forward( + torch.cat([local_context, diffused_scene_tensor], dim=-1) + ) + # try to remove local context + # queries = self.input_proj.forward(diffused_scene_tensor) + + # positional encode the scene tensor, both diffusion timestep and physical timestep + diffusion_time_embed = self.diffusion_timestep_embeddor( + diffusion_times.view(-1) + ).view(B, NA, NT, -1) + physical_time_embed = ( + self.physical_timestep_embeddor( + (torch.arange(NT, device=local_context.device) / NT).view(-1), + ) + .view(1, 1, NT, -1) + .expand(B, NA, NT, -1) + ) + + # queries += physical_time_embed + # add the positional embeddings to the queries + if os.environ.get("NO_PHYPE", False): + queries += diffusion_time_embed + else: + queries += (diffusion_time_embed + physical_time_embed) + # queries += (diffusion_time_embed + physical_time_embed) + # queries += physical_time_embed + 0.5 + # queries += diffusion_time_embed + # note that we dont have to use the valid mask here as + fused_context = self.cross_attention( + inputs_kv=global_context, + inputs_q=queries.view(B, NA * NT, self.hidden_dim), + ).view(queries.size()) * valid_mask.unsqueeze(-1) + + for i, block in enumerate(self.backbone): + queries = block( + queries, + fused_context, + valid_mask, + ) + + shift, scale = self.adaLN_modulation(fused_context).chunk(2, dim=-1) + queries = modulate(self.norm_final(queries), shift, scale) + denoised_scene_tensor = self.output_proj(queries) + + return denoised_scene_tensor + + +class NexusNoTaskMask(nn.Module): + """ + Based on the Nexus paper. Perciever I/O structure + This version is designed for cases where task_mask is not concatenated to local_context, + so the input dimension is 2 * scene_tensor_dim instead of 3 * scene_tensor_dim. + """ + + def __init__( + self, + nblocks: int = 4, + hidden_dim: int = 256, + scene_tensor_dim: int = 8, + cross_attention_num_heads: int = 4, + ): + super().__init__() + self.hidden_dim = hidden_dim + self.scene_tensor_dim = scene_tensor_dim + self._num_heads = cross_attention_num_heads + self.cross_attention = CrossAttention( + kv_dim=hidden_dim, + q_dim=hidden_dim, + qk_out_dim=hidden_dim, + v_out_dim=hidden_dim, + num_heads=self._num_heads, + ) + # Use 2 * scene_tensor_dim instead of 3 * scene_tensor_dim + self.input_proj = nn.Linear( + 2 * scene_tensor_dim, hidden_dim, bias=False + ) + self.physical_timestep_embeddor = TimestepEmbedder(hidden_dim) + self.diffusion_timestep_embeddor = TimestepEmbedder(hidden_dim) + + self.backbone = nn.Sequential( + *[CombinedAttention(hidden_dim) for _ in range(nblocks)] + ) + + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(hidden_dim, 2 * hidden_dim, bias=True) + ) + self.norm_final = nn.LayerNorm(hidden_dim, elementwise_affine=False, eps=1e-6) + self.output_proj = nn.Linear(hidden_dim, scene_tensor_dim) + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + self.apply(_basic_init) + + # init first layer + w = self.input_proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.constant_(self.input_proj.bias, 0) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.physical_timestep_embeddor.mlp[0].weight, std=0.02) + nn.init.normal_(self.physical_timestep_embeddor.mlp[2].weight, std=0.02) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.diffusion_timestep_embeddor.mlp[0].weight, std=0.02) + nn.init.normal_(self.diffusion_timestep_embeddor.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in DiT blocks: + for block in self.backbone: + nn.init.constant_(block.temporal_attention.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.temporal_attention.adaLN_modulation[-1].bias, 0) + nn.init.constant_(block.spatial_attention.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.spatial_attention.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.output_proj.weight, 0) + nn.init.constant_(self.output_proj.bias, 0) + + def forward( + self, + local_context: torch.Tensor, + diffused_scene_tensor: torch.Tensor, + valid_mask: torch.Tensor, + diffusion_times: torch.Tensor, + global_context: torch.Tensor, + ): + """ + Args: + local_context: tensor of shape (B, NA, NT, ND) - without task_mask concatenated + diffused_scene_tensor: tensor of shape (B, NA, NT, ND) + valid_mask: tensor of shape (B, NA, NT) + diffusion_times: tensor of shape (B, NA, NT) + global_context: tensor for cross attention + + """ + # x is the queries, and global context is the keys and values + B, NA, NT, ND = local_context.size() + + queries = self.input_proj.forward( + torch.cat([local_context, diffused_scene_tensor], dim=-1) + ) + + # positional encode the scene tensor, both diffusion timestep and physical timestep + diffusion_time_embed = self.diffusion_timestep_embeddor( + diffusion_times.view(-1) + ).view(B, NA, NT, -1) + physical_time_embed = ( + self.physical_timestep_embeddor( + (torch.arange(NT, device=local_context.device) / NT).view(-1), + ) + .view(1, 1, NT, -1) + .expand(B, NA, NT, -1) + ) + + # add the positional embeddings to the queries + if os.environ.get("NO_PHYPE", False): + queries += diffusion_time_embed + else: + queries += (diffusion_time_embed + physical_time_embed) + + # note that we dont have to use the valid mask here as + fused_context = self.cross_attention( + inputs_kv=global_context, + inputs_q=queries.view(B, NA * NT, self.hidden_dim), + ).view(queries.size()) * valid_mask.unsqueeze(-1) + + for i, block in enumerate(self.backbone): + queries = block( + queries, + fused_context, + valid_mask, + ) + + shift, scale = self.adaLN_modulation(fused_context).chunk(2, dim=-1) + queries = modulate(self.norm_final(queries), shift, scale) + denoised_scene_tensor = self.output_proj(queries) + + return denoised_scene_tensor \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/models/utils.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/models/utils.py new file mode 100644 index 0000000..76f80e0 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/models/utils.py @@ -0,0 +1,96 @@ +import math +import torch +from torch import nn +from einops import rearrange, parse_shape + + +def exists(val): + return val is not None + + +def default(val, d): + if exists(val): + return val + return d() if callable(d) else d + + +def extract(a, t, x_shape): + if len(t.shape) == 3: + f, b, s = t.shape + out = a[t] + return out.reshape(f, b, 1, s, *((1,) * (len(x_shape) - 4))) + else: + f, b = t.shape + out = a[t] + return out.reshape(f, b, *((1,) * (len(x_shape) - 2))) + +def default_extract(a, t, x_shape): + f, b = t.shape + out = a[t] + return out.reshape(f, b, *((1,) * (len(x_shape) - 2))) + + +def linear_beta_schedule(timesteps): + """ + linear schedule, proposed in original ddpm paper + """ + scale = 1000 / timesteps + beta_start = scale * 0.0001 + beta_end = scale * 0.02 + return torch.linspace(beta_start, beta_end, timesteps, dtype=torch.float64) + + +def cosine_beta_schedule(timesteps, s=0.008): + """ + cosine schedule + as proposed in https://openreview.net/forum?id=-NEXDKk8gZ + """ + steps = timesteps + 1 + t = torch.linspace(0, timesteps, steps, dtype=torch.float64) / timesteps + alphas_cumprod = torch.cos((t + s) / (1 + s) * math.pi * 0.5) ** 2 + alphas_cumprod = alphas_cumprod / alphas_cumprod[0] + betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) + return torch.clip(betas, 0, 0.999) + + +def sigmoid_beta_schedule(timesteps, start=-3, end=3, tau=1, clamp_min=1e-5): + """ + sigmoid schedule + proposed in https://arxiv.org/abs/2212.11972 - Figure 8 + better for images > 64x64, when used during training + """ + steps = timesteps + 1 + t = torch.linspace(0, timesteps, steps, dtype=torch.float64) / timesteps + v_start = torch.tensor(start / tau).sigmoid() + v_end = torch.tensor(end / tau).sigmoid() + alphas_cumprod = (-((t * (end - start) + start) / tau).sigmoid() + v_end) / (v_end - v_start) + alphas_cumprod = alphas_cumprod / alphas_cumprod[0] + betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) + return torch.clip(betas, 0, 0.999) + + +class EinopsWrapper(nn.Module): + def __init__(self, from_shape: str, to_shape: str, module: nn.Module): + super().__init__() + self.module = module + self.from_shape = from_shape + self.to_shape = to_shape + + def forward(self, x: torch.Tensor, *args, **kwargs): + axes_lengths = parse_shape(x, pattern=self.from_shape) + x = rearrange(x, f"{self.from_shape} -> {self.to_shape}") + x = self.module(x, *args, **kwargs) + x = rearrange(x, f"{self.to_shape} -> {self.from_shape}", **axes_lengths) + return x + + +def get_einops_wrapped_module(module, from_shape: str, to_shape: str): + class WrappedModule(nn.Module): + def __init__(self, *args, **kwargs): + super().__init__() + self.wrapper = EinopsWrapper(from_shape, to_shape, module(*args, **kwargs)) + + def forward(self, x: torch.Tensor, *args, **kwargs): + return self.wrapper(x, *args, **kwargs) + + return WrappedModule \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/scenediffusion_with_opt.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/scenediffusion_with_opt.py new file mode 100644 index 0000000..f537381 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/diffusion/scenediffusion_with_opt.py @@ -0,0 +1,1863 @@ +""" +This file contains an implementation of the pseudocode from the paper +"Simple Diffusion: End-to-End Diffusion for High Resolution Images" +by Emiel Hoogeboom, Tim Salimans, and Jonathan Ho. + +Reference: +Hoogeboom, E., Salimans, T., & Ho, J. (2023). +Simple Diffusion: End-to-End Diffusion for High Resolution Images. +Retrieved from https://arxiv.org/abs/2301.11093 +""" + +import math +from typing import Optional +import os +import torch +import torch.nn as nn +from torch.special import expm1 +import numpy as np +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import ( + FEATURE_STD, + FEATURE_MEANS, + decode_scene_tensor, + encode_scene_tensor, + unnormalize_roadgraph +) +from nuplan_extent.planning.training.modeling.models.tokenizers.base_tokenizer_utils import ( + check_collision, +) +from collections import namedtuple +from .models.utils import linear_beta_schedule, cosine_beta_schedule, sigmoid_beta_schedule, extract, EinopsWrapper +from torch.amp import autocast +from torch.nn import functional as F + +import casadi as ca +from typing import List + + +# helper +def log(t, eps=1e-20): + return torch.log(t.clamp(min=eps)) + +ModelPrediction = namedtuple("ModelPrediction", ["pred_noise", "pred_x_start", "model_out"]) + + +class TrajectoryOptimizationError(RuntimeError): + """A candidate must not be saved after its dynamics optimization fails.""" + + +def solve_trajectory(solver, stage, **kwargs): + """Expose solver failures to the generation loop instead of returning input.""" + try: + solution = solver(**kwargs) + stats = solver.stats() + if not stats.get("success", False): + raise TrajectoryOptimizationError( + f"{stage} optimization failed: {stats.get('return_status', 'unknown status')}" + ) + result = solution['x'].full().flatten() + if not np.isfinite(result).all(): + raise TrajectoryOptimizationError(f"{stage} optimization returned non-finite states") + return result + except TrajectoryOptimizationError: + raise + except RuntimeError as error: + raise TrajectoryOptimizationError(f"{stage} optimization raised: {error}") from error + + +def visualize_trajectories(trajectories, mask, map_tensor,num, save_path="trajectories.png"): + import numpy as np + import matplotlib.pyplot as plt + # import pdb;pdb.set_trace() + # visualize_trajectories(scene_tensor, mask, raw_map, num, save_path) + # scene_tensor: [b,na,nt,ndim], mask: [b,na,nt], raw_map: [b,nm,2], num: int, save_path: str + # scene_tensor and raw_map are both normalized while input + trajectories = trajectories[0, :num, :, :4].cpu().detach().numpy() # na,nt,ndim + mask = mask[0, :num, :].cpu().detach().numpy().astype(bool) # na,nt + map_tensor = map_tensor[0,:,:2].cpu().detach().numpy() # nm,nt,2 + + trajectories = decode_scene_tensor(trajectories) + map_mask = ~ (map_tensor == 50).all(axis=-1) # nm,nt + map_tensor = unnormalize_roadgraph(map_tensor) + plt.figure(figsize=(8, 6)) + plt.scatter(map_tensor[map_mask, 0], map_tensor[map_mask, 1], marker=".", alpha=0.3, color='lightgrey') + + for i in range(trajectories.shape[0]): # iterate over each trajectory + x = trajectories[i, mask[i], 0] # extract x + y = trajectories[i, mask[i], 1] # extract y + cos_h = trajectories[i, mask[i], 2] # extract cos(heading) + sin_h = trajectories[i, mask[i], 3] # extract sin(heading) + if mask[i].sum() == 0: + continue + plt.plot(x, y, marker="o", linestyle="-", label=f"Trajectory {i+1}", alpha=0.7) # plot trajectory + for j in range(0, x.shape[0], 5): # plot arrows every 5 points + plt.arrow(x[j], y[j], 0.3 * cos_h[j], 0.3 * sin_h[j], head_width=0.1, color="black") + + + plt.xlabel("X Coordinate") + plt.ylabel("Y Coordinate") + plt.title("Trajectory Visualization") + plt.legend(loc="best", fontsize=8, frameon=False) + plt.grid(True) + + plt.savefig(save_path, dpi=300) + plt.close() + +class simpleDiffusion(nn.Module): + def __init__( + self, + model, + # image_size, + noise_size=64, + pred_param="v", + schedule="shifted_cosine", + steps=512, + uncertainty_scale=1.0, + condition_time=5, + scheduling_matrix="full_sequence", + final_step=True, + fill_scene_tensor=True, + constrain_mode=['clip'], + constrain_gamma=1.0, + loss_factor=[1.0, 0.0, 0.0, 0.0], + distill=False, + ): + super().__init__() + self.distill = distill + self.constraint_gamma = constrain_gamma + self.loss_factor = loss_factor + self.constrain_mode=constrain_mode + # Training objective + assert pred_param in [ + "v", + "eps", + ], "Invalid prediction parameterization. Must be 'v' or 'eps'" + self.pred_param = pred_param + + # Sampling schedule + assert schedule in [ + "cosine", + "shifted_cosine", + ], "Invalid schedule. Must be 'cosine' or 'shifted_cosine'" + self.schedule = schedule + self.noise_d = noise_size + self.image_d = 128 + # self.image_d = image_size + + # Model + assert isinstance( + model, nn.Module + ), "Model must be an instance of torch.nn.Module." + self.model = model + + num_params = sum(p.numel() for p in self.model.parameters()) + print(f"Number of parameters: {num_params}") + + # Steps + self.steps = steps + self.uncertainty_scale = uncertainty_scale + self.condition_time = condition_time + self.scheduling_matrix = scheduling_matrix + self.final_step = final_step + self.fill_scene_tensor = fill_scene_tensor + + # optimization + self.routes_tensor = None + self.routes_mask = None + + def logsnr_schedule_cosine(self, t, logsnr_min=-15, logsnr_max=15): + """ + Function to compute the logSNR schedule at timepoint t with cosine: + + logSNR(t) = -2 * log (tan (pi * t / 2)) + + + logsnr_t = -2 * log(tan(t_min + t * (t_max - t_min))) + + Args: + t (int): The timepoint t. + logsnr_min (int): The minimum logSNR value. + logsnr_max (int): The maximum logSNR value. + + Returns: + logsnr_t (float): The logSNR value at timepoint t. + """ + logsnr_max = logsnr_max + math.log(self.noise_d / self.image_d) + logsnr_min = logsnr_min + math.log(self.noise_d / self.image_d) + t_min = math.atan(math.exp(-0.5 * logsnr_max)) + t_max = math.atan(math.exp(-0.5 * logsnr_min)) + + logsnr_t = -2 * log(torch.tan(torch.tensor(t_min + t * (t_max - t_min)))) + + return logsnr_t + + def logsnr_schedule_cosine_shifted(self, t): + """ + Function to compute the logSNR schedule at timepoint t with shifted cosine: + + logSNR_shifted(t) = logSNR(t) + 2 * log(noise_d / image_d) + + Args: + t (int): The timepoint t. + image_d (int): The image dimension. + noise_d (int): The noise dimension. + + Returns: + logsnr_t_shifted (float): The logSNR value at timepoint t. + """ + logsnr_t = self.logsnr_schedule_cosine(t) + logsnr_t_shifted = logsnr_t + 2 * math.log(self.noise_d / self.image_d) + + return logsnr_t_shifted + + def diffuse(self, x, alpha_t, sigma_t): + """ + Function to diffuse the input tensor x to a timepoint t with the given alpha_t and sigma_t. + + Args: + x (torch.Tensor): The input tensor to diffuse. + alpha_t (torch.Tensor): The alpha value at timepoint t. + sigma_t (torch.Tensor): The sigma value at timepoint t. + + Returns: + z_t (torch.Tensor): The diffused tensor at timepoint t. + eps_t (torch.Tensor): The noise tensor at timepoint t. + """ + eps_t = torch.randn_like(x) + + z_t = alpha_t * x + sigma_t * eps_t + + return z_t, eps_t + + def clip(self, x): + """ + Function to clip the input tensor x to the range [-1, 1]. + + Args: + x (torch.Tensor): The input tensor to clip. + + Returns: + x (torch.Tensor): The clipped tensor. + """ + return torch.clamp(x, -1, 1) + + def constrain(self, x, mode=['clip'], window=3, gamma=0.4, + raw_map=None, valid_mask=None, + threshold=2.7/(2*FEATURE_STD[0]), separation_distance=2.5, + keep_mask=None, scene_tensor=None): + + if type(mode) is list: + if type(gamma) is not list: + gamma = [gamma] * len(mode) + assert len(mode) == len(gamma), "mode and gamma must have the same length, but got {} and {}".format(len(mode), len(gamma)) + for m,g in zip(mode,gamma): + x=self.constrain(x,m,window,g,raw_map,valid_mask,threshold,separation_distance,keep_mask,scene_tensor) + return x + + B, NA, NT, D = x.shape + + if mode == 'keep': + x[keep_mask.bool()] = scene_tensor[keep_mask.bool()] + return x + + elif mode == 'clip': + x = self.clip(x) + return x + + elif mode == 'velocity': # Update positions using the predicted velocities. + x_pred = decode_scene_tensor(x) # [b, na, nt, dim] + + def compute_trajectory(velocity_matrix, start_point, t=0.5): + trajectory = torch.zeros(velocity_matrix.shape, device=velocity_matrix.device) + trajectory[..., 0, :] = start_point + for i in range(velocity_matrix.shape[2]-1): + trajectory[...,i + 1,:] = trajectory[...,i,:] + velocity_matrix[...,i,:]*t + return trajectory + + x_pred[...,4:,:2] = torch.where(valid_mask[...,4:5,None].repeat(1,1,17,2).bool(), + compute_trajectory(x_pred[...,4:,4:6], x_pred[...,4,:2]), + x_pred[...,4:,:2]) + x_pred = encode_scene_tensor(x_pred) + + elif mode == 'sma': # Smooth positions using a moving average. + if window is None or NTthreshold + x_pred[replace_mask] = anchor_pred[replace_mask] + x_pred = x_pred.reshape(B,NA,NT,2) + x_pred = torch.cat([x_pred,x[...,2:]],dim=-1) + else: + raise ValueError('Unsupported mode') + + # if velocity < 0.5, keep token consistent + consist_mask = torch.norm(decode_scene_tensor(x)[...,4:6],dim=-1) <= 0.7 + consist_mask = consist_mask.unsqueeze(-1).repeat(1,1,1,x_pred.shape[-1]).bool() + x_pred[consist_mask] = x[consist_mask] + + return x + gamma * (x_pred.to(dtype=x.dtype, device=x.device) - x) + + @torch.no_grad() + def ddpm_sampler_step(self, input_features, z_t, pred, valid_mask, keep_mask, logsnr_t, logsnr_s, grad_list=None, + constrain={'mode':['clip']}, optimization=True, forward_simulation=True): + """ + Compute the mean and variance for a denoising update that skips steps. + Function to perform a single step of the DDPM sampler. + + Args: + z_t (torch.Tensor): The diffused tensor at timepoint t. + pred (torch.Tensor): The predicted value from the model (v or eps). + logsnr_t (float): The logSNR value at timepoint t. + logsnr_s (float): The logSNR value at the sampling timepoint s. + + Returns: + z_s (torch.Tensor): The diffused tensor at sampling timepoint s. + """ + c = -expm1(logsnr_t - logsnr_s) + alpha_t = torch.sqrt(torch.sigmoid(logsnr_t)) + alpha_s = torch.sqrt(torch.sigmoid(logsnr_s)) + sigma_t = torch.sqrt(torch.sigmoid(-logsnr_t)) + sigma_s = torch.sqrt(torch.sigmoid(-logsnr_s)) + recip_alpha_t = torch.sqrt(1.0 / torch.sigmoid(logsnr_t)) + recipml_alpha_t = torch.sqrt(1.0 / torch.sigmoid(logsnr_t) - 1.0) + + if self.pred_param == "v": + x_pred = alpha_t * z_t - sigma_t * pred # pred_x_start + pred_noise = (recip_alpha_t * z_t - x_pred) / recipml_alpha_t # pred_noise + elif self.pred_param == "eps": + x_pred = (z_t - sigma_t * pred) / alpha_t + + constrain = {'mode': []} + x_pred = self.constrain(x_pred, **constrain) + + x_pred = self.optimization_constrain(input_features, x_pred, keep_mask, valid_mask, optimization, forward_simulation) + + if grad_list is not None: + [grad, x_t, target] = grad_list + mu = alpha_s * (z_t * (1 - c) / alpha_t + c * x_pred) - grad*300 # Apply optional guidance directly to the mean. + else: + mu = alpha_s * (z_t * (1 - c) / alpha_t + c * x_pred) + + variance = (sigma_s**2) * c # Variance formula from Simple Diffusion. + + return mu, variance, x_pred + + + def optimization_constrain(self, + input_features, + x_pred, + keep_mask, + valid_mask, + optimization, + forward_simulation): + if optimization: + x_pred[keep_mask.bool()] = input_features.tensor[keep_mask.bool()] + if self.routes_tensor is None: + self.compute_routes_tensor(input_features) + + has_initial = valid_mask[..., :6].any(dim=-1, keepdim=True) # shape (B, N, 1) + op_valid_mask =torch.logical_and(valid_mask.bool(), has_initial) + + + # raw optimization + x_pred = self.scene_nlp_optimization( + z_t=decode_scene_tensor(x_pred), + keep_mask=keep_mask, + valid_mask=op_valid_mask + ) + + # forward simulation + if forward_simulation: + x_pred = self.forward_simulation(x_pred, keep_mask, op_valid_mask) + + x_pred = encode_scene_tensor(x_pred) + + return x_pred + + def compute_routes_tensor( + self, + input_features, + max_hop: int = 8, + connect_thresh: float = 0.5, + n_route: int = 100, + n_point: int = 200 + ) -> torch.Tensor: + road_graph = unnormalize_roadgraph(input_features.road_graph.clone()) + road_graph_validity = input_features.road_graph_validity + + B, n_poly, n_pts, _ = road_graph.shape + device = road_graph.device + dtype = road_graph.dtype + + routes_tensor = torch.zeros(B, n_route, n_point, 3, device=device, dtype=dtype) + routes_mask = torch.zeros(B, n_route, device=device, dtype=torch.bool) + + def sample_and_heading(coords: torch.Tensor) -> torch.Tensor: + deltas = coords[1:] - coords[:-1] + seg_len = torch.norm(deltas, dim=1) + cum_len = torch.cat([torch.zeros(1, device=device), seg_len.cumsum(0)]) + total = cum_len[-1].item() + if total == 0: + pts = coords[0].unsqueeze(0).repeat(n_point, 1) + heads = torch.zeros(n_point, device=device) + return torch.cat([pts, heads.unsqueeze(1)], dim=1) + + target = torch.linspace(0, total, n_point, device=device) + idx = torch.searchsorted(cum_len, target) + idx0 = torch.clamp(idx - 1, 0, coords.size(0) - 2) + idx1 = torch.clamp(idx, 1, coords.size(0) - 1) + t = (target - cum_len[idx0]) / (cum_len[idx1] - cum_len[idx0]) + p0, p1 = coords[idx0], coords[idx1] + pts = p0 + (p1 - p0) * t.unsqueeze(1) + + diffs = pts[1:] - pts[:-1] + heads = torch.atan2(diffs[:, 1], diffs[:, 0]) + heads = torch.cat([heads, heads[-1:]], dim=0) + return torch.cat([pts, heads.unsqueeze(1)], dim=1) + + for b in range(B): + valid_idx_list, start_pts, end_pts = [], [], [] + for i in range(n_poly): + point_valid = road_graph_validity[b, i].any(dim=-1) # (n_pts,) + vi = torch.nonzero(point_valid, as_tuple=True)[0] + if vi.numel() == 0: + continue + start_i, end_i = vi[0].item(), vi[-1].item() + start_pts.append(road_graph[b, i, start_i, :2]) + end_pts.append(road_graph[b, i, end_i, :2]) + valid_idx_list.append(i) + + if not valid_idx_list: + continue + + start_pts = torch.stack(start_pts, dim=0) # (n_valid,2) + end_pts = torch.stack(end_pts, dim=0) # (n_valid,2) + n_valid = len(valid_idx_list) + + ei = end_pts[:, None, :] # (n_valid,1,2) + sj = start_pts[None, :, :] # (1,n_valid,2) + adj = torch.norm(ei - sj, dim=-1) < connect_thresh + + in_deg = adj.sum(dim=0) # (n_valid,) + + routes: List[List[int]] = [] + + def dfs(path: List[int]): + last = path[-1] + extended = False + for nxt in torch.nonzero(adj[last], as_tuple=True)[0].tolist(): + if nxt not in path and len(path) < max_hop: + dfs(path + [nxt]) + extended = True + if not extended: + routes.append([valid_idx_list[k] for k in path]) + + starts = torch.nonzero(in_deg == 0, as_tuple=True)[0].tolist() + for s in starts: + dfs([s]) + + for r, route in enumerate(routes[:n_route]): + coords_list = [] + for idx in route: + point_valid = road_graph_validity[b, idx].any(dim=-1) # (n_pts,) + # Then filter the coordinates using the mask. + pts = road_graph[b, idx, :, :2][point_valid] # (n_valid_pts,2) + if pts.numel() > 0: + coords_list.append(pts) + if not coords_list: + continue + coords_seq = torch.cat(coords_list, dim=0) + if coords_seq.shape[0] < 2: + continue + routes_tensor[b, r] = sample_and_heading(coords_seq) + routes_mask[b, r] = True + + self.routes_tensor = routes_tensor + self.routes_mask = routes_mask + + def assign_agent_routes( + self, + z_t: torch.Tensor, # (B, n_agents, T, 8) + valid_mask: torch.Tensor, # (B, n_agents, T) + angle_thresh: float = math.pi / 3, # 60° + disp_thresh: float = 20.0 # 20 m + ) -> torch.Tensor: + B, N, T, _ = z_t.shape + _, R, P, _ = self.routes_tensor.shape + + device = z_t.device + out = torch.full((B, N), -1, dtype=torch.long, device=device) + + for b in range(B): + valid_routes = torch.nonzero(self.routes_mask[b], as_tuple=True)[0] # (R_valid,) + if valid_routes.numel() == 0: + continue + + vm = valid_mask[b] # (N, T) + z = z_t[b, ..., :2] # (N, T, 2) + cos = z_t[b, ..., 2] # (N, T) + sin = z_t[b, ..., 3] # (N, T) + yaw = torch.atan2(sin, cos) # (N, T) + + for i in range(N): + t_valid = torch.nonzero(vm[i], as_tuple=True)[0] # (Tv,) + if t_valid.numel() == 0: + continue + + pos0 = z[i, t_valid[0]] # (2,) + yaw0 = yaw[i, t_valid[0]].item() + disp = torch.norm(z[i, t_valid[-1]] - pos0) + if disp < disp_thresh: + continue + + pts = self.routes_tensor[b, valid_routes, :, :2] # (Rv, P, 2) + heads = self.routes_tensor[b, valid_routes, :, 2] # (Rv, P) + + # (Rv, P) - (1,1,2) -> (Rv, P) + d0 = torch.norm(pts - pos0.view(1, 1, 2), dim=2) # (Rv, P) + idx0 = torch.argmin(d0, dim=1) # (Rv,) + + head0 = heads[torch.arange(idx0.size(0), device=device), idx0] # (Rv,) + ang_diff = ((yaw0 - head0 + math.pi) % (2 * math.pi)) - math.pi + mask_angle = ang_diff.abs() <= angle_thresh # (Rv,) + + if not mask_angle.any(): + continue + + sel_routes = valid_routes[mask_angle] # (K,) + K = sel_routes.size(0) + sel_pts = pts[mask_angle] # (K, P, 2) + + pos_valid = z[i, t_valid] # (Tv, 2) + pos_batch = pos_valid.unsqueeze(0).expand(K, -1, -1) # (K, Tv,2) + dists = torch.cdist(pos_batch, sel_pts) # (K, Tv, P) + min_d, _ = dists.min(dim=2) # (K, Tv) + scores = min_d.sum(dim=1) # (K,) + + best_idx = torch.argmin(scores).item() # 0..K-1 + out[b, i] = sel_routes[best_idx] + + return out + + def optimize_nlp_agent_forward( + self, + z_i_pred, # (T, 8) + z_i_ref, + z_others_pred, # (M, T, 8) + valid_others, # (M, T) + keep_i, # (T, 8) + valid_i, # (T,) + dt=0.5, + dt_opt=0.1, + a_min=-8.0, a_max=4.0, + delta_min=-0.6, delta_max=0.6, + safe_dist=1.0, + pos_weight=1.0, + lat_weight=1000.0, + heading_weight=10000.0, + vel_weight=0.0, + control_a_weight=1.0, + control_del_weight=10.0 * 2, + control_ddel_weight=50.0 * 2, + w_obs=10000.0, + v_static_thresh=1.0, + angle_thresh=np.deg2rad(60) + ): + if not np.any(np.asarray(valid_i, dtype=bool) & ~keep_i.any(axis=1)): + return z_i_pred.copy() + T = z_i_pred.shape[0] + ratio = int(dt / dt_opt) + T_opt = (T - 1) * ratio + 1 + + orig_valid = np.where(valid_i)[0] + if len(orig_valid) == 0: + return z_i_pred.copy() + + x_ref = z_i_pred[:, 0] + y_ref = z_i_pred[:, 1] + v_ref = np.hypot(z_i_pred[:, 4], z_i_pred[:, 5]) + phi = np.arctan2(z_i_pred[:, 3], z_i_pred[:, 2]) + phi = np.unwrap(phi) + f0 = orig_valid[0] + off = ((phi[f0] + np.pi) % (2 * np.pi) - np.pi) - phi[f0] + phi_ref = phi + off + + x_exp = z_i_ref[:, 0] + y_exp = z_i_ref[:, 1] + v_exp = np.hypot(z_i_ref[:, 4], z_i_ref[:, 5]) + phi = np.arctan2(z_i_ref[:, 3], z_i_ref[:, 2]) + phi = np.unwrap(phi) + f0 = orig_valid[0] + off = ((phi[f0] + np.pi) % (2 * np.pi) - np.pi) - phi[f0] + phi_exp = phi + off + + collision_map = {t: [] for t in orig_valid} + M = z_others_pred.shape[0] + for j in range(M): + for t in orig_valid: + if not valid_others[j, t] or v_ref[t] <= v_static_thresh: + continue + + vx_t = z_others_pred[j, t, 4] + vy_t = z_others_pred[j, t, 5] + speed_t = np.hypot(vx_t, vy_t) + dx_c = z_others_pred[j, t, 0] - x_ref[t] + dy_c = z_others_pred[j, t, 1] - y_ref[t] + fx, fy = np.cos(phi_ref[t]), np.sin(phi_ref[t]) + proj = fx * dx_c + fy * dy_c + dist_c = np.hypot(dx_c, dy_c) + ang = np.arccos(np.clip(proj / (dist_c), -1.0, 1.0)) + if not (speed_t <= v_static_thresh or ang < angle_thresh): + continue + + a_obs = z_others_pred[j, t, 6] / 2 + b_obs = z_others_pred[j, t, 7] / 2 + r_circle = z_i_pred[t, 7] / 2 + safe_dist + d_front = z_i_pred[t, 6] / 2 - z_i_pred[t, 7] / 2 + d_rear = -d_front + + A = a_obs + r_circle + B = b_obs + r_circle + sf = lf = 10 + + x_o, y_o = z_others_pred[j, t, 0], z_others_pred[j, t, 1] + c, s_ = np.cos(phi_ref[t]), np.sin(phi_ref[t]) + x_f = x_ref[t] + d_front * c + y_f = y_ref[t] + d_front * s_ + x_r = x_ref[t] + d_rear * c + y_r = y_ref[t] + d_rear * s_ + + for x_c, y_c in ((x_f, y_f), (x_r, y_r)): + dx = x_c - x_o + dy = y_c - y_o + u1 = c * dx + s_ * dy + u2 = -s_ * dx + c * dy + if (u1 / A) ** sf + (u2 / B) ** lf < 1.0: + collision_map[t].append((j, A, B, sf, lf, x_o, y_o, d_front, d_rear)) + break + + if all(len(collision_map[t]) == 0 for t in orig_valid): + return z_i_pred.copy() + + valid_opt = np.zeros(T_opt, bool) + runs = [] + s = prev = orig_valid[0] + for t in orig_valid[1:]: + if t == prev + 1: + prev = t + else: + runs.append((s, prev)) + s = t + prev = t + runs.append((s, prev)) + for a, b in runs: + for k in range(a*ratio, b*ratio + 1): + valid_opt[k] = True + + collision_map_opt = {} + for t in orig_valid: + k = t * ratio + if valid_opt[k] and collision_map[t]: + collision_map_opt[k] = collision_map[t].copy() + + var_idx = {} + cnt = 0 + for k in range(T_opt): + if valid_opt[k]: + var_idx[('x', k)] = slice(cnt, cnt+4) + cnt += 4 + for k in range(T_opt-1): + if valid_opt[k] and valid_opt[k+1]: + var_idx[('u', k, k+1)] = slice(cnt, cnt+2) + cnt += 2 + + coll_pairs = [ + (k, j, A, B, sf, lf, x_o, y_o, d_front, d_rear) + for k, lst in collision_map_opt.items() + for (j, A, B, sf, lf, x_o, y_o, d_front, d_rear) in lst + ] + n_slack = len(coll_pairs) * 2 + slack_slice = slice(cnt, cnt + n_slack) + cnt_new = cnt + n_slack + + w = ca.SX.sym('w', cnt_new) + g, lbg, ubg = [], [], [] + J = 0 + + for t in orig_valid: + k0 = t * ratio + sl = var_idx.get(('x', k0)) + if sl is None: + continue + xi = w[sl] + J += pos_weight * ((xi[0] - x_exp[t])**2 + (xi[1] - y_exp[t])**2) + J += vel_weight * (xi[3] - v_exp[t])**2 + + ang_diff =xi[2] - phi_exp[t] + g.append(ang_diff) + lbg.append(-np.pi / 3) + ubg.append(+np.pi / 3) + J += heading_weight * ang_diff ** 2 + + n_x = -ca.sin(phi_exp[t]) + n_y = ca.cos(phi_exp[t]) + e_lat = n_x * (xi[0] - x_exp[t]) + n_y * (xi[1] - y_exp[t]) + J += lat_weight * e_lat ** 2 + + for key, sl in var_idx.items(): + if key[0] == 'u': + ui = w[sl] + J += control_a_weight * ui[0]**2 \ + + control_del_weight* ui[1]**2 + _, k0, k1 = key + nxt = var_idx.get(('u', k1, k1+1)) + if nxt is not None: + J += control_ddel_weight * (ui[1] - w[nxt][1])**2 + + for key, sl in var_idx.items(): + if key[0] != 'u': + continue + _, k0, k1 = key + sl_x0 = var_idx[('x', k0)] + sl_x1 = var_idx[('x', k1)] + x0 = w[sl_x0] + x1 = w[sl_x1] + u = w[sl] + orig_t = k0 // ratio + Lk = z_i_pred[orig_t, 6] * 0.6 + 1e-6 + + f1 = x0[0] + x0[3]*ca.cos(x0[2])*dt_opt - x1[0] + f2 = x0[1] + x0[3]*ca.sin(x0[2])*dt_opt - x1[1] + f3 = x0[2] + (x0[3]/Lk)*ca.tan(u[1])*dt_opt - x1[2] + f4 = x0[3] + u[0]*dt_opt - x1[3] + g += [f1, f2, f3, f4] + lbg += [0, 0, 0, 0] + ubg += [0, 0, 0, 0] + + sl0 = var_idx.get(('x', 0)) + if sl0 is not None: + xi0 = w[sl0] + g += [xi0[0]-x_ref[0], + xi0[1]-y_ref[0], + xi0[2]-phi_ref[0], + xi0[3]-v_ref[0]] + lbg += [0, 0, 0, 0] + ubg += [0, 0, 0, 0] + + km = keep_i.any(axis=1) + orig_true = np.where(km)[0] + boundary_ts = [ + t for t in orig_true + if (t > 0 and not km[t-1]) or (t < T-1 and not km[t+1]) + ] + for t in boundary_ts: + k0 = t * ratio + sl = var_idx.get(('x', k0)) + if sl is None: + continue + xi = w[sl] + g += [xi[0]-x_ref[t], xi[1]-y_ref[t], + xi[2]-phi_ref[t], xi[3]-v_ref[t]] + lbg += [0, 0, 0, 0] + ubg += [0, 0, 0, 0] + + s_var = w[slack_slice] + for idx, (k, j, A, B, sf, lf, x_o, y_o, d_front, d_rear) in enumerate(coll_pairs): + slx = var_idx[('x', k)] + xi = w[slx] + x_s, y_s, phi_s = xi[0], xi[1], xi[2] + c, s_ = ca.cos(phi_s), ca.sin(phi_s) + x_f = x_s + d_front * c + y_f = y_s + d_front * s_ + x_r = x_s + d_rear * c + y_r = y_s + d_rear * s_ + for sub, (xc, yc) in enumerate(((x_f, y_f), (x_r, y_r))): + dx = xc - x_o + dy = yc - y_o + u1 = c * dx + s_ * dy + u2 = -s_ * dx + c * dy + expr = ca.power(u1 / A, sf) + ca.power(u2 / B, lf) + s_var[idx * 2 + sub] - 1 + g.append(expr) + lbg.append(0) + ubg.append(ca.inf) + J += w_obs * s_var[idx * 2 + sub] ** 2 + + lbx = [-ca.inf] * cnt_new + ubx = [ ca.inf] * cnt_new + for key, sl in var_idx.items(): + if key[0] == 'u': + lbx[sl.start] = a_min + ubx[sl.start] = a_max + lbx[sl.start+1] = delta_min + ubx[sl.start+1] = delta_max + for k in range(T_opt): + sl = var_idx.get(('x', k)) + if sl: + lbx[sl.start+3] = 0.0 + for idx in range(slack_slice.start, slack_slice.stop): + lbx[idx] = 0.0 + # ubx[idx] = 0.0 + + nlp = {'x': w, 'f': J, 'g': ca.vertcat(*g)} + solver = ca.nlpsol('solver', 'ipopt', nlp, { + 'ipopt.max_iter': 1000, + 'ipopt.print_level': 0, + 'print_time': False, + }) + + w0 = np.zeros(cnt_new) + for key, sl in var_idx.items(): + if key[0] == 'x': + k = key[1] + t_cont = k / ratio + i0 = int(np.floor(t_cont)) + i1 = min(i0 + 1, T - 1) + alpha = t_cont - i0 + z0, z1 = z_i_pred[i0], z_i_pred[i1] + x_i = (1-alpha)*z0[0:2] + alpha*z1[0:2] + phi_i = (1-alpha)*phi_ref[i0] + alpha*phi_ref[i1] + v_i = (1-alpha)*v_ref[i0] + alpha*v_ref[i1] + w0[sl] = [x_i[0], x_i[1], phi_i, v_i] + elif key[0] == 'u': + w0[sl] = [0.0, 0.0] + + w_opt = solve_trajectory( + solver, "collision", x0=w0, lbx=lbx, ubx=ubx, lbg=lbg, ubg=ubg, + ) + + z_opt = z_i_pred.copy() + for t in orig_valid: + if not valid_i[t] or keep_i[t,0]: + continue + k0 = t * ratio + sl = var_idx.get(('x', k0)) + xi = w_opt[sl] + phi_opt = xi[2]; v_opt = xi[3] + z_opt[t, 0] = xi[0] + z_opt[t, 1] = xi[1] + z_opt[t, 2] = np.cos(phi_opt) + z_opt[t, 3] = np.sin(phi_opt) + z_opt[t, 4] = v_opt * np.cos(phi_opt) + z_opt[t, 5] = v_opt * np.sin(phi_opt) + return z_opt + + def forward_simulation( + self, + x_pred: torch.Tensor, # (B, N, T, 8) + keep_mask: torch.Tensor, # (B, N, T, 8) + valid_mask: torch.Tensor, # (B, N, T) + dt: float = 0.5 + ) -> torch.Tensor: + B, N, T, _ = x_pred.shape + device = x_pred.device + + pred = x_pred.detach().cpu().numpy().copy() + x_pred_cy = x_pred.detach().cpu().numpy().copy() + vm_np = valid_mask.detach().cpu().numpy() # (B, N, T) + km_np = keep_mask.detach().cpu().numpy() # (B, N, T, 8) + out = np.zeros_like(pred) + + for b in range(B): + out[b, :, 0, :] = pred[b, :, 0, :] + for t in range(T-1): + fut = pred[b, :, t:, :] # (N, H+1,8) + x_ref = x_pred_cy[b, :, t:, :] # (N, H+1,8) + vm = vm_np[b, :, t:] # (N, H+1) + km = km_np[b, :, t:, :] # (N, H+1,8) + + for i in range(N): + if not (vm[i,0] and vm[i,1]) or km[i,0].any() or km[i,1].any(): + out[b, i, t+1, :] = pred[b, i, t+1, :] + continue + + traj = self.optimize_nlp_agent_forward( + z_i_pred = fut[i], + z_i_ref = x_ref[i], + z_others_pred = np.delete(fut, i, axis=0), + valid_others = np.delete(vm, i, axis=0), + keep_i = km[i], + valid_i = vm[i], + dt = dt + ) + + pred[b, i, t:, :] = traj + out[b, i, t+1, :] = traj[1] + + return torch.from_numpy(pred).to(device) + + def compute_start_from_v(self, z_t, pred, logsnr_t, logsnr_s): + c = -expm1(logsnr_t - logsnr_s) + alpha_t = torch.sqrt(torch.sigmoid(logsnr_t)) + alpha_s = torch.sqrt(torch.sigmoid(logsnr_s)) + sigma_t = torch.sqrt(torch.sigmoid(-logsnr_t)) + sigma_s = torch.sqrt(torch.sigmoid(-logsnr_s)) + recip_alpha_t = torch.sqrt(1.0 / torch.sigmoid(logsnr_t)) + recipml_alpha_t = torch.sqrt(1.0 / torch.sigmoid(logsnr_t) - 1.0) + + if self.pred_param == "v": + x_pred = alpha_t * z_t - sigma_t * pred # pred_x_start + return x_pred + + def _generate_scheduling_matrix(self, scene_tensor, zero_init=True): + ''' + Build a (steps, B, A, T) schedule of noise levels for each denoising step, agent, and timestep. + ''' + B, NA, NT = scene_tensor.shape[:3] + if self.scheduling_matrix == "pyramid": + return self._generate_pyramid_scheduling_matrix(zero_init, NT, self.uncertainty_scale)[:,np.newaxis,np.newaxis,:].repeat(B, 1).repeat(NA, 2) + elif self.scheduling_matrix == "full_sequence": # Share a linearly decreasing noise schedule across agents and timesteps; zero_init keeps the first five timesteps noise-free. + scheduling_matrix = np.linspace(1, 0, self.steps)[:,np.newaxis,np.newaxis,np.newaxis].repeat(B, 1).repeat(NA, 2).repeat(NT, 3) # (steps, B, A, T) + if zero_init: + scheduling_matrix[:,:,:,:5] = 0 # [m B NA NT] + return scheduling_matrix.astype(np.float32) + elif self.scheduling_matrix == "half_half_sequence": + matrix_1 = np.linspace(1, 0, self.steps)[:,np.newaxis,np.newaxis,np.newaxis].repeat(B, 1).repeat(NA, 2).repeat(NT//2, 3) + ones_matrix_1 = np.ones((self.steps, B, NA, NT-NT//2), dtype=np.float32) + scheduling_matrix_1 = np.concatenate([matrix_1, ones_matrix_1], axis=-1) + zeros_matrix_2 = np.zeros_like(matrix_1) + matrix_2 = np.linspace(1, 0, self.steps)[:,np.newaxis,np.newaxis,np.newaxis].repeat(B, 1).repeat(NA, 2).repeat(NT-NT//2, 3) + scheduling_matrix_2 = np.concatenate([zeros_matrix_2, matrix_2], axis=-1) + scheduling_matrix = np.concatenate([scheduling_matrix_1, scheduling_matrix_2], axis=0) + if zero_init: + scheduling_matrix[:,:,:,:5] = 0 #[m B NA NT] + return scheduling_matrix.astype(np.float32) + elif self.scheduling_matrix == "autoregressive": + return self._generate_pyramid_scheduling_matrix(zero_init, NT, self.steps)[:,np.newaxis,np.newaxis,:].repeat(B, 1).repeat(NA, 2) + elif self.scheduling_matrix == "trapezoid": + return self._generate_trapezoid_scheduling_matrix(zero_init, NT, self.uncertainty_scale)[:,np.newaxis,np.newaxis,:].repeat(B, 1).repeat(NA, 2) + + def _generate_pyramid_scheduling_matrix(self, zero_init: bool, horizon: int, uncertainty_scale: float): + if zero_init: + horizon = horizon - self.condition_time + height = self.steps + int((horizon - 1) * uncertainty_scale) + 1 + scheduling_matrix = np.zeros((height, horizon), dtype=np.int64) + for m in range(height): + for t in range(horizon): + scheduling_matrix[m, t] = self.steps + int(t * uncertainty_scale) - m + scheduling_matrix = np.concatenate([np.zeros((height, self.condition_time)), scheduling_matrix], axis=1) + scheduling_matrix = np.clip(scheduling_matrix, 0, self.steps)/self.steps + + return scheduling_matrix.astype(np.float32) + + def _generate_trapezoid_scheduling_matrix(self, zero_init: bool, horizon: int, uncertainty_scale: float): + if zero_init: + horizon = horizon - self.condition_time + extra_step = (horizon+1) % 2 + height = self.steps + int((horizon + 1) // 2 * uncertainty_scale) + extra_step + scheduling_matrix = np.zeros((height, horizon), dtype=np.int64) + for m in range(height): + for t in range((horizon + 1) // 2 + extra_step): + scheduling_matrix[m, t] = self.steps + int(t * uncertainty_scale) - m + scheduling_matrix[m, -t] = self.steps + int(t * uncertainty_scale) - m + + scheduling_matrix = np.concatenate([np.zeros((height, self.condition_time)), scheduling_matrix], axis=1) + scheduling_matrix = np.clip(scheduling_matrix, 0, self.steps)/self.steps + + return scheduling_matrix.astype(np.float32) + + def _filling_scene_tensor(self, scene_tensor, z_t, keep_mask, scaling_matrix): + ''' + Initialize noise (B, A, T, D) and noise levels (steps, B, A, T), preserving known timesteps with zero noise and using scaling_matrix elsewhere. + ''' + if not self.fill_scene_tensor: + return scaling_matrix, z_t + # keep_mask: [B NA NT D], scaling_matrix: [m B NA NT] + z_t = torch.where(keep_mask.bool(), scene_tensor, z_t) # Preserve known timesteps and use pure noise elsewhere. + keep_mask = keep_mask[:,:,:,0].bool().unsqueeze(0).repeat(scaling_matrix.shape[0], 1, 1, 1) # (steps, B, A, T) + scaling_matrix = np.where(~keep_mask.cpu().numpy(), scaling_matrix, np.full(scaling_matrix.shape, 0).astype(np.float32)) # Set known timesteps to zero noise and retain scaling_matrix elsewhere. + return scaling_matrix, z_t + + def guidance_fn(self, x_start, scene_tensor, keep_mask, valid_mask, target): + + # keep_mask[:,:,:5] = 0 # keep only the goals + mask = keep_mask.clone() + weight = torch.full_like(x_start, 4.0, device=x_start.device) + weight = torch.where(mask.bool(), weight, torch.full_like(weight, 1.0, device=x_start.device)) + loss = nn.functional.mse_loss(x_start, target.requires_grad_(), reduction="none") + loss = -(weight * valid_mask.unsqueeze(-1) * loss).mean() * 10000 + # import pdb; pdb.set_trace() + # print('target', target[0,0,:,0]) + # print('loss', (x_start-target)[0,0,:,0]) + + return loss, (x_start-target) + # return (x_start-target) + + def sampler_step(self, input_features, scene_tensor, x, keep_mask, u_t, u_s, local_context, global_context, + valid_mask, schedule_func, use_guidance_fn, compute_mu, target, constrain={'mode':['clip']}, + optimization=True, forward_simulation=True): + + # u_t = np.where( + # u_t <= 0, + # np.full_like(u_t, 0.017), + # u_t, + # ) + + orig_x = x.clone().detach() # (B, A, T, D) + logsnr_t = schedule_func(u_t) # (B, A, T) + logsnr_t = logsnr_t.clone().detach().to(scene_tensor.device) + alpha_t = ( + torch.sqrt(torch.sigmoid(logsnr_t)) + .view(scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + .to(scene_tensor.device) + ) # (B, A, T, 1) + sigma_t = ( + torch.sqrt(torch.sigmoid(-logsnr_t)) + .view(scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + .to(scene_tensor.device) + ) # (B, A, T, 1) + scaled_context, eps_t = self.diffuse(x, alpha_t, sigma_t) + z_t = torch.where(keep_mask.bool(), scaled_context, orig_x) + + logsnr_s = schedule_func(u_s) # (B, A, T) + logsnr_s = logsnr_s.to(scene_tensor.device) + + u_t = torch.tensor(u_t, device=x.device) + u_s = torch.tensor(u_s, device=x.device) + + grad_list = None + if use_guidance_fn: + with torch.enable_grad(): + x = z_t.detach().requires_grad_() + pred = self.model( + local_context=local_context, + diffused_scene_tensor=x, + valid_mask=valid_mask, + diffusion_times=u_t, + global_context=global_context, + ) + x_start = self.compute_start_from_v(z_t, pred, logsnr_t.unsqueeze(-1).repeat(1, 1, 1, scene_tensor.shape[3]), logsnr_s.unsqueeze(-1).repeat(1, 1, 1, scene_tensor.shape[3])) + guidance_loss, dist = self.guidance_fn(x_start, scene_tensor, keep_mask, valid_mask, target) + grad_compute = -torch.autograd.grad( + guidance_loss, + x_start, + )[0] + grad = dist/1000 + grad = grad_compute/10 + # print('grad', grad[0,0,:,0]) + # print('grad_compute', grad_compute[0,0,:,0]) + + grad_list = [grad, x, target] + mu, variance, x0_pred = self.ddpm_sampler_step( + input_features, + x, pred, valid_mask, keep_mask, + logsnr_t.unsqueeze(-1).repeat(1, 1, 1, scene_tensor.shape[3]), + logsnr_s.unsqueeze(-1).repeat(1, 1, 1, scene_tensor.shape[3]), + grad_list, constrain, + optimization=optimization, + forward_simulation=forward_simulation + ) + else: + pred = self.model( + local_context=local_context, + diffused_scene_tensor=z_t, + valid_mask=valid_mask, + diffusion_times=u_t, + global_context=global_context, + ) # (B, n_agents, n_timesteps, n_features) + mu, variance, x0_pred = self.ddpm_sampler_step( + input_features, z_t, pred, valid_mask, keep_mask, + logsnr_t.unsqueeze(-1).repeat(1, 1, 1, scene_tensor.shape[3]), + logsnr_s.unsqueeze(-1).repeat(1, 1, 1, scene_tensor.shape[3]), + grad_list, constrain, + optimization=optimization, + forward_simulation=forward_simulation + ) + + intermidiates = mu.clone().detach() + if not compute_mu: + return mu, intermidiates, x0_pred + + # apply keep_mask + mu[keep_mask.bool()] = scene_tensor[keep_mask.bool()] + z_t = mu + torch.randn_like(mu) * torch.sqrt(variance) + + return z_t, intermidiates, x0_pred + + def optimize_dense_single_agent_with_heading(self, + z_agent, # (T, 8) + keep_mask_agent, # (T, 8) bool + valid_mask_agent, # (T,) bool + dt_orig, # 0.5 + dt_opt, # 0.1 + a_min, a_max, + delta_min, delta_max, + pos_weight, vel_weight, + control_a_weight, control_del_weight, + control_ddel_weight, + route=None, + heading_weight=100.0, + ): + if not np.any(np.asarray(valid_mask_agent, dtype=bool) & ~keep_mask_agent.any(axis=1)): + return z_agent + + T = z_agent.shape[0] + ratio = int(dt_orig / dt_opt) + T_opt = (T - 1) * ratio + 1 + + orig_valid = np.where(valid_mask_agent)[0] + phi_seq = np.arctan2(z_agent[:, 3], z_agent[:, 2]) + phi_seq = np.unwrap(phi_seq) + first = orig_valid[0] + val = phi_seq[first] + val_wrapped = (val + np.pi) % (2 * np.pi) - np.pi + offset = val_wrapped - val + phi_seq = phi_seq + offset + + route_headings = None + if route is not None: + P = route.shape[0] + pos_valid = z_agent[orig_valid, :2] # (V,2) + # route_pts: (P,2) + route_pts = route[:, :2] # (P,2) + dmat = np.linalg.norm(pos_valid[:, None, :] - route_pts[None, :, :], axis=2) + nearest = dmat.argmin(axis=1) # (V,) + raw_h = route[nearest, 2] # (V,) + unwrapped = np.unwrap(raw_h) # (V,) + first = orig_valid[0] + phi0 = phi_seq[first] + h_ref = unwrapped[0] + diff = (h_ref - phi0 + np.pi) % (2 * np.pi) - np.pi + offset = (phi0 + diff) - h_ref + unwrapped = unwrapped + offset + route_headings = np.full(T, np.nan) + route_headings[orig_valid] = unwrapped + + valid_opt = np.zeros(T_opt, dtype=bool) + if len(orig_valid) > 0: + runs = [] + start = orig_valid[0] + prev = start + for t in orig_valid[1:]: + if t == prev + 1: + prev = t + else: + runs.append((start, prev)) + start = t + prev = t + runs.append((start, prev)) + for (s, e) in runs: + for topt in range(s * ratio, e * ratio + 1): + valid_opt[topt] = True + + var_idx = {} + cnt = 0 + for topt in range(T_opt): + if not valid_opt[topt]: + continue + var_idx[('x', topt)] = slice(cnt, cnt + 4) + cnt += 4 + for topt in range(T_opt - 1): + if valid_opt[topt] and valid_opt[topt + 1]: + var_idx[('u', topt, topt + 1)] = slice(cnt, cnt + 2) + cnt += 2 + + w = ca.SX.sym('w', cnt) + g, lbg, ubg = [], [], [] + J = 0 + + for torig in orig_valid: + topt = torig * ratio + idx_x = var_idx.get(('x', topt)) + if idx_x is None: + continue + x_i = w[idx_x] # [x, y, phi, v] + z_r = z_agent[torig] + v_ref = np.hypot(z_r[4], z_r[5]) + J += pos_weight * ((x_i[0] - z_r[0]) ** 2 + (x_i[1] - z_r[1]) ** 2) + J += vel_weight * ((x_i[3] - v_ref) ** 2) + + if route_headings is not None: + h_ref = route_headings[torig] + ang_diff = x_i[2] - h_ref + g.append(ang_diff) + lbg.append(-np.pi / 3) + ubg.append(+np.pi / 3) + J += heading_weight * ang_diff ** 2 + + for key, sl in var_idx.items(): + if key[0] == 'u': + u_i = w[sl] + J += control_a_weight * u_i[0] ** 2 \ + + control_del_weight * u_i[1] ** 2 + + t0, t1 = key[1], key[2] + next_key = ('u', t1, t1 + 1) + sl_next = var_idx.get(next_key) + if sl_next is None: + continue + delta_curr = w[sl][1] + delta_next = w[sl_next][1] + J += control_ddel_weight * (delta_next - delta_curr) ** 2 + + for key, sl in var_idx.items(): + if key[0] != 'u': + continue + t0, t1 = key[1], key[2] + idx_x0 = var_idx[('x', t0)] + idx_x1 = var_idx[('x', t1)] + x0, x1, u = w[idx_x0], w[idx_x1], w[sl] + orig_t0 = t0 // ratio + wheelbase = z_agent[orig_t0, 6] * 0.6 + 1e-6 + f1 = x0[0] + x0[3] * ca.cos(x0[2]) * dt_opt - x1[0] + f2 = x0[1] + x0[3] * ca.sin(x0[2]) * dt_opt - x1[1] + f3 = x0[2] + (x0[3] / wheelbase) * ca.tan(u[1]) * dt_opt - x1[2] + f4 = x0[3] + u[0] * dt_opt - x1[3] + g += [f1, f2, f3, f4] + lbg += [0] * 4 + ubg += [0] * 4 + + km = keep_mask_agent.any(axis=1) + orig_true = np.where(km)[0] + boundary_ts = [ + t for t in orig_true + if (t > 0 and not km[t - 1]) or (t < T - 1 and not km[t + 1]) + ] + for torig in boundary_ts: + topt = torig * ratio + sl = var_idx.get(('x', topt)) + if sl is None: + continue + z0 = z_agent[torig] + phi0 = phi_seq[torig] + v0 = np.hypot(z0[4], z0[5]) + g += [ + w[sl][0] - z0[0], + w[sl][1] - z0[1], + w[sl][2] - phi0, + w[sl][3] - v0 + ] + lbg += [0] * 4 + ubg += [0] * 4 + + lbx = [-ca.inf] * cnt + ubx = [ca.inf] * cnt + for key, sl in var_idx.items(): + if key[0] == 'u': + lbx[sl.start] = a_min + ubx[sl.start] = a_max + lbx[sl.start + 1] = delta_min + ubx[sl.start + 1] = delta_max + elif key[0] == 'x': + lbx[sl.start + 3] = 0.0 + + nlp = {'x': w, 'f': J, 'g': ca.vertcat(*g)} + solver = ca.nlpsol( + 'solver', 'ipopt', nlp, + { + 'ipopt.max_iter': 100, + 'ipopt.print_level': 0, + 'print_time': False, + 'ipopt.tol': 1e-8, + 'ipopt.constr_viol_tol': 1e-8, + 'ipopt.compl_inf_tol': 1e-8, + 'ipopt.acceptable_tol': 1e-8, + } + ) + + v_seq = np.hypot(z_agent[:, 4], z_agent[:, 5]) + w0 = np.zeros(cnt) + for key, sl in var_idx.items(): + if key[0] != 'x': + continue + topt = key[1] + t_cont = topt / ratio + i0 = int(np.floor(t_cont)) + i1 = min(i0 + 1, T - 1) + alpha = t_cont - i0 # 0..1 + z0, z1 = z_agent[i0], z_agent[i1] + x_interp = (1 - alpha) * z0[0:2] + alpha * z1[0:2] + v_interp = (1 - alpha) * v_seq[i0] + alpha * v_seq[i1] + phi_interp = (1 - alpha) * phi_seq[i0] + alpha * phi_seq[i1] + w0[sl] = [x_interp[0], x_interp[1], phi_interp, v_interp] + + w_opt = solve_trajectory( + solver, "dynamics", x0=w0, lbx=lbx, ubx=ubx, lbg=lbg, ubg=ubg, + ) + z_opt = z_agent.copy() + + for torig in range(T): + if not valid_mask_agent[torig]: + continue + if keep_mask_agent[torig, 0]: + continue + topt = torig * ratio + idx = var_idx.get(('x', topt)) + if idx is None: + continue + xi = w_opt[idx] + phi, v = xi[2], xi[3] + z_opt[torig, 0] = xi[0] + z_opt[torig, 1] = xi[1] + z_opt[torig, 2] = np.cos(phi) + z_opt[torig, 3] = np.sin(phi) + z_opt[torig, 4] = v * np.cos(phi) + z_opt[torig, 5] = v * np.sin(phi) + + return z_opt + + def scene_nlp_optimization(self, z_t, keep_mask, valid_mask, + dt=0.5, a_min=-8.0, a_max=4.0, + delta_min=-0.6, delta_max=0.6, + pos_weight=1.0, vel_weight=0.0, + control_a_weight=1.0, + control_del_weight=10.0, + control_ddel_weight=50.0 + ): + B, n_agents, T, _ = z_t.shape + opt_z = z_t.clone().cpu().numpy() + agent_route_idx = self.assign_agent_routes(z_t, valid_mask) + for b in range(B): + for i in range(n_agents): + z_ai = opt_z[b, i] # (T,8) + km_ai = keep_mask[b, i].cpu().numpy().astype(bool) + vm_ai = valid_mask[b, i].cpu().numpy().astype(bool) + + r_idx = int(agent_route_idx[b, i].item()) + route = self.routes_tensor[b, r_idx].cpu().numpy() if r_idx >= 0 else None# (P,3) + z_opt = self.optimize_dense_single_agent_with_heading( + z_ai, km_ai, vm_ai, + dt, 0.1, a_min, a_max, delta_min, delta_max, + pos_weight, vel_weight, + control_a_weight, control_del_weight, control_ddel_weight, + route=route + ) + + opt_z[b, i] = z_opt + return torch.from_numpy(opt_z).to(z_t.device) + + @torch.no_grad() + def compute_target(self, scene_tensor, keep_mask): + # keep_mask[:,:,:5] = 0 # keep only the goals + keep_flag_mask = keep_mask[:, :, :, 0] == 1 + indices = torch.nonzero(keep_flag_mask, as_tuple=False) + first_index = indices[0] if indices.numel() > 0 else torch.tensor([0]) + target = scene_tensor.clone() + + return target + + def extrapolate(self, scene_tensor, valid_mask, keep_mask): + batch_size, num_vehicles, num_times, num_params = scene_tensor.shape + extrapolated_scene_tensor = torch.zeros_like(scene_tensor, device=scene_tensor.device, dtype=scene_tensor.dtype) + + for b in range(batch_size): + for v in range(num_vehicles): + vehicle_mask = keep_mask[b, v, :, 0] # [NT] + vehicle_scene = scene_tensor[b, v] # [NT, D] + + keep_indices = torch.nonzero(vehicle_mask, as_tuple=False).squeeze(-1) #[num_keep_T] + if vehicle_mask.sum() == 0: + continue + else: + pre_idx, post_idx = keep_indices[-2], keep_indices[-1] + extrapolated_scene_tensor[b, v, :5] = vehicle_scene[:5] + extrapolated_scene_tensor[b, v, 5:] = vehicle_scene[4] + (vehicle_scene[post_idx] - vehicle_scene[pre_idx]) * (torch.arange(5, num_times, device=scene_tensor.device).float().unsqueeze(-1) - 4)/ (post_idx - pre_idx) + extrapolated_scene_tensor[b, v, 5:,-2:] = vehicle_scene[4,-2:].unsqueeze(0) + + return extrapolated_scene_tensor, [] + # @torch.no_grad() + def sample( + self, + input_features, + scene_tensor, # (B, n_agents, n_timesteps, n_features) + valid_mask, # (B, n_agents, n_timesteps) + keep_mask, # (B, n_agents, n_timesteps, n_features) + global_context, # map_encoding + z_t: Optional[torch.Tensor] = None, # noise (B, n_agents, n_timesteps, n_features) + return_intermidates: bool = False, # whether to return intermediate results + use_guidance_fn: bool = False, # whether to use guidance function + raw_map=None # (B, n_polylines, n_max_valid_points, n_features) + ): + """ + Standard DDPM sampling procedure. Begun by sampling z_T ~ N(0, 1) + and then repeatedly sampling z_s ~ p(z_s | z_t) + + Args: + x_shape (tuple): The shape of the input tensor. + global_context (torch.Tensor): The global context tensor. + + + Returns: + x_pred (torch.Tensor): The predicted tensor. + """ + # Routes belong to this input map and batch. Reuse them only within + # this sampling call, including its repeated optimization steps. + self.routes_tensor = None + self.routes_mask = None + + use_extrapolate = os.environ.get('EXTRAPOLATE', False) + if use_extrapolate: + print('extrapolate') + return self.extrapolate(scene_tensor, valid_mask, keep_mask) + + if z_t is None: + z_t = torch.randn(scene_tensor.shape).to(scene_tensor.device) + fuse_mask = False + if fuse_mask == True: + keep_mask = keep_mask * valid_mask.unsqueeze(-1) + local_context = scene_tensor * keep_mask + # add the valid mask as a channel + local_context = torch.cat([local_context, keep_mask], dim=-1) # (B, n_agents, n_timesteps, n_features*2) + + intermidiates = [] + schedule_func = ( + self.logsnr_schedule_cosine + if self.schedule == "cosine" + else self.logsnr_schedule_cosine_shifted + ) + + constrain={'mode':self.constrain_mode,'gamma':self.constraint_gamma,'raw_map':raw_map,'valid_mask':valid_mask,'keep_mask':keep_mask.bool(),'scene_tensor':scene_tensor} + scaling_matrix = self._generate_scheduling_matrix(scene_tensor) # (steps, B, A, T) + scaling_matrix, z_t = self._filling_scene_tensor(scene_tensor, z_t, keep_mask, scaling_matrix) # (steps, B, A, T) + # import pdb; pdb.set_trace() + gt_replace = os.environ.get('GT_REPLACE', False) # + if gt_replace: + res = torch.zeros_like(scene_tensor) + gt_replace_mask = np.logical_not(scaling_matrix[0].astype(bool)) + res[gt_replace_mask] = scene_tensor[gt_replace_mask] + if self.fill_scene_tensor: + res = torch.where(keep_mask.bool(), scene_tensor, res) + + # original_z_t = z_t.clone() + target = self.compute_target(scene_tensor, keep_mask) # + + # ******************* Sampling Loop ******************* + # Steps T -> 1 + for t in range(scaling_matrix.shape[0]-1): + u_t = scaling_matrix[t] + u_s = scaling_matrix[t+1] + z_t, mu, x0_pred = self.sampler_step( + input_features, scene_tensor, + z_t, keep_mask, u_t, u_s, + local_context, global_context, valid_mask, schedule_func, + use_guidance_fn, + True, target, + constrain, + optimization=(scaling_matrix.shape[0]-1 - t <= 5), # (scaling_matrix.shape[0]-1 - t <= 5) False True + forward_simulation=(scaling_matrix.shape[0]-1 - t <= 1), # (scaling_matrix.shape[0]-1 - t <= 1) False True + ) + # z_t = torch.where(keep_mask.bool(), original_z_t, z_t) + + if return_intermidates: + intermidiates.append(mu) + if gt_replace: + gt_replace_mask = np.logical_and(np.logical_not(u_s.astype(bool)), u_t.astype(bool)) + res[gt_replace_mask] = z_t[gt_replace_mask] + z_t[gt_replace_mask] = scene_tensor[gt_replace_mask] + # input() + if gt_replace: + z_t = res + + # Final step + if self.final_step: + u_t = np.full_like(u_t, 1 / self.steps) + u_s = np.full_like(u_s, 0) + + x_pred, _, x0_pred = self.sampler_step( + input_features, scene_tensor, + z_t, keep_mask, u_t, u_s, + local_context, global_context, valid_mask, schedule_func, + use_guidance_fn, + False, target, + constrain, + optimization=True, # False True + forward_simulation=True # False True + ) + + x_pred[keep_mask.bool()] = scene_tensor[keep_mask.bool()] + if return_intermidates: + intermidiates.append(x_pred) + return x_pred, intermidiates + + def compute_loss( + self, + scene_tensor, + valid_mask, + global_context, + diffusion_times, + task_mask, + control_mask, + raw_map = None + ): + """ + A function to compute the loss of the model. The loss is computed as the mean squared error + between the predicted noise tensor and the true noise tensor. Various prediction parameterizations + imply various weighting schemes as outlined in Kingma et al. (2023) + + Args: + scene_tensor (torch.Tensor): The scene tensor (B, NA, NT, ND). + valid_mask (torch.Tensor): The validity mask (B, NA, NT). + global_context (torch.Tensor): The global context tensor (B, S, NC). + diffusion_times (torch.Tensor): The diffusion times (B, NT). + task_mask (torch.Tensor): The inpainting mask (B, NA, NT, ND). + control_mask (torch.Tensor): The control mask (B, NA, NT, ND). + + Returns: + loss (torch.Tensor): The loss value. + """ + + if False and self.distill: + return self.compute_consist_loss( + scene_tensor, + valid_mask, + global_context, + diffusion_times, + task_mask, + control_mask, + raw_map + ) + + schedule_func = ( + self.logsnr_schedule_cosine + if self.schedule == "cosine" + else self.logsnr_schedule_cosine_shifted + ) + task_mask = torch.logical_or(task_mask, control_mask) + # if self.fill_scene_tensor: + # keep_mask = task_mask[:,:,:,0].bool() + # diffusion_times = torch.where(~keep_mask, diffusion_times, torch.full(diffusion_times.shape, 0.017, device=diffusion_times.device)) + logsnr_t = schedule_func(diffusion_times) + logsnr_t = logsnr_t.to(scene_tensor.device) + alpha_t = ( + torch.sqrt(torch.sigmoid(logsnr_t)) + .view(scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + .to(scene_tensor.device) + ) + sigma_t = ( + torch.sqrt(torch.sigmoid(-logsnr_t)) + .view(scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + .to(scene_tensor.device) + ) + z_t, eps_t = self.diffuse(scene_tensor, alpha_t, sigma_t) + # create the local context + local_context = scene_tensor * task_mask + # add the valid mask as a channel + local_context = torch.cat([local_context, task_mask], dim=-1) + + pred = self.model( + local_context=local_context, + diffused_scene_tensor=z_t, + valid_mask=valid_mask, + diffusion_times=diffusion_times, + global_context=global_context, + ) + + if self.pred_param == "v": + eps_pred = sigma_t * z_t + alpha_t * pred + else: + eps_pred = pred + + # Apply min-SNR weighting (https://arxiv.org/pdf/2303.09556) + snr = torch.exp(logsnr_t).clamp_(max=5) + if self.pred_param == "v": + weight = 1 / (1 + snr) + else: + weight = 1 / snr + + weight = weight.view(scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + + # add zero weights to invalid pixels + weight = weight * valid_mask.unsqueeze(-1) + # weight = weight * torch.logical_not(task_mask) + + loss = torch.sum(weight * (eps_pred - eps_t) ** 2) + # velo_loss = self.compute_traj_loss(pred, alpha_t, z_t, sigma_t, valid_mask, weight) + # map_loss = self.compute_map_loss(pred, alpha_t, z_t, sigma_t, valid_mask, weight, raw_map) + # coll_loss = self.compute_collision_loss(pred, alpha_t, z_t, sigma_t, valid_mask, weight) + + # loss = loss + velo_loss + map_loss + coll_loss + # loss = loss + map_loss + velo_loss + return ( + loss, + dict( + ), + ) + + def compute_collision_loss(self, pred, alpha_t, z_t, sigma_t, validity, weight, min_distance=2.15): + + x_pred = alpha_t * z_t - sigma_t * pred + x_pred = decode_scene_tensor(x_pred) + + trajectories = x_pred[...,:2] + + B, NA, NT, D = trajectories.shape + + # compute pairwise L2 distance + traj_exp1 = trajectories.unsqueeze(2) # (B, NA, 1, NT, D) + traj_exp2 = trajectories.unsqueeze(1) # (B, 1, NA, NT, D) + distances = torch.norm(traj_exp1 - traj_exp2, dim=-1) # (B, NA, NA, NT) + + # avoid computing self-distance(i == j) + mask_self = torch.eye(NA, device=trajectories.device).unsqueeze(0).unsqueeze(-1) # (1, NA, NA, 1) + distances = distances + mask_self * 1e6 + + # compute validity mask + validity_exp1 = validity.unsqueeze(2) # (B, NA, 1, NT) + validity_exp2 = validity.unsqueeze(1) # (B, 1, NA, NT) + valid_mask = (validity_exp1 * validity_exp2).bool() # (B, NA, NA, NT) + + # compute collision penalty(distances < min_distance) + collision_mask = (distances < min_distance) & valid_mask # only consider valid trajectory points + collision_penalty = (min_distance - distances).clamp(min=0) # only punish violations + weight = weight.unsqueeze(1)[...,0] + loss = torch.sum(collision_penalty * collision_mask * weight) + + return loss + + def compute_repulsion_loss(self, pred, alpha_t, z_t, sigma_t, validity, min_dist=2.15, sigma=0.5): + x_pred = alpha_t * z_t - sigma_t * pred + x_pred = decode_scene_tensor(x_pred) + + trajs = x_pred[...,:2] + + B, NA, NT, D = trajs.shape + + # Expand for pairwise distance computation + traj_i = trajs.unsqueeze(2) # [B, NA, 1, NT, D] + traj_j = trajs.unsqueeze(1) # [B, 1, NA, NT, D] + + # Compute pairwise Euclidean distance + dist = torch.norm(traj_i - traj_j, dim=-1) # [B, NA, NA, NT] + + # Compute Gaussian penalty: exp(- ((d - min_dist)² / (2σ²))) + penalty = torch.exp(-((dist - min_dist) ** 2) / (2 * sigma ** 2)) + + # Mask out self-interactions (i == j) + mask_self = torch.eye(NA, device=trajs.device).unsqueeze(0).unsqueeze(-1) # [1, NA, NA, 1] + penalty = penalty * (1 - mask_self) # [B, NA, NA, NT] + + # Apply validity mask: only consider valid agents at each timestep + valid_mask = (validity.unsqueeze(2) * validity.unsqueeze(1)).unsqueeze(0) # [B, NA, NA, NT] + penalty = penalty * valid_mask + + # Compute final loss, normalized by number of valid interactions + valid_pairs = valid_mask.sum() + # loss = penalty.sum() / (valid_pairs + 1e-6) # Avoid division by zero + loss = penalty.sum() + + return loss + + def compute_traj_loss(self, pred, alpha_t, z_t, sigma_t, valid_mask, weight): + x_pred = alpha_t * z_t - sigma_t * pred + B, NA, NT, D = x_pred.shape + x_pred = decode_scene_tensor(x_pred) + freq = 2 + + def expand_zeros(valid_mask): + kernel = torch.tensor([1, 1, 1], dtype=torch.float32).view(1, 1, 3).to(valid_mask.device) + pad_mask = torch.nn.functional.pad(valid_mask, (1, 1), mode='replicate') + expanded_mask = torch.nn.functional.conv1d(pad_mask.view(-1, 1, 23), kernel, padding=0, groups=1).view_as(valid_mask) + return (expanded_mask > 0).float() + + valid_mask = expand_zeros(valid_mask) + + compute_traj = x_pred[...,:2] + x_pred[...,4:6] / freq + compute_traj = torch.cat((x_pred[...,:1,:2], compute_traj[...,:-1,:]), -2) + + traj_loss = torch.sum(weight * valid_mask.unsqueeze(-1) * encode_scene_tensor(compute_traj-x_pred[...,:2])**2) + + return traj_loss + + def compute_map_loss(self, pred, alpha_t, z_t, sigma_t, valid_mask, weight, raw_map=None): + # map L2 loss mean + # compute the L2 distance between the predicted_x and closet map center line point + if raw_map is None or 0 in raw_map.shape: + return torch.tensor(0.0).to(pred.device) + x_pred = alpha_t * z_t - sigma_t * pred + B, NA, NT, D = x_pred.shape + # only constrain the x,y channel + x_pred = x_pred[...,:2].reshape(B,-1,2) + encoded_map = raw_map[...,:2] + # find the closet map anchor point for agent at any time + agent_num,map_num = x_pred.shape[1],encoded_map.shape[1] + anchor_pred = x_pred.unsqueeze(2).repeat(1,1,map_num,1) - encoded_map.unsqueeze(1).repeat(1,agent_num,1,1) + min_index = torch.argmin(torch.norm(anchor_pred, dim=-1), dim=-1) + # index out closet anchor map point + anchor_pred = encoded_map[torch.arange(min_index.shape[0]).unsqueeze(-1).expand_as(min_index),min_index] + # if distance > threshold, then compute the l2 loss + threshold = 3.75/(2*FEATURE_STD[0]) # 3.5m + distance = torch.norm((anchor_pred-x_pred),dim=-1).reshape(B*NA,NT) + in_threshold_mask = distance < threshold + first_true_indices = torch.argmax(valid_mask.reshape(B*NA,NT), dim=-1) + use_mask = in_threshold_mask[torch.arange(B*NA), first_true_indices] * torch.any(valid_mask.reshape(B*NA,NT), dim=-1) + loss_mask = use_mask.unsqueeze(-1) + map_loss = (distance * loss_mask * weight.reshape(B*NA,NT)).sum() + return map_loss + + def compute_consist_loss( + self, + scene_tensor, + valid_mask, + global_context, + diffusion_times, + task_mask, + control_mask, + raw_map=None + ): + """ + A function to compute the loss of the model. The loss is computed as the mean squared error + between the predicted noise tensor and the true noise tensor. Various prediction parameterizations + imply various weighting schemes as outlined in Kingma et al. (2023) + + Args: + scene_tensor (torch.Tensor): The scene tensor (B, NA, NT, ND). + valid_mask (torch.Tensor): The validity mask (B, NA, NT). + global_context (torch.Tensor): The global context tensor (B, S, NC). + diffusion_times (torch.Tensor): The diffusion times (B, NT). + task_mask (torch.Tensor): The inpainting mask (B, NA, NT, ND). + control_mask (torch.Tensor): The control mask (B, NA, NT, ND). + + Returns: + loss (torch.Tensor): The loss value. + """ + # common part: scene_tensor, task_mask, local_context + schedule_func = ( + self.logsnr_schedule_cosine + if self.schedule == "cosine" + else self.logsnr_schedule_cosine_shifted + ) + task_mask = torch.logical_or(task_mask, control_mask) + + # create the local context + local_context = scene_tensor * task_mask + # add the valid mask as a channel + local_context = torch.cat([local_context, task_mask], dim=-1) + + + # create diffusion from diffusion_times with less noise + diffusion_times_ln = torch.clamp(diffusion_times - 0.1, 0., 1.) + diffusion_times = torch.cat([diffusion_times, diffusion_times_ln], dim=0) # [2B, NA, NT, C] + + logsnr_t = schedule_func(diffusion_times) + logsnr_t = logsnr_t.to(scene_tensor.device) + + alpha_t = ( + torch.sqrt(torch.sigmoid(logsnr_t)) + .view(2*scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + .to(scene_tensor.device) + ) + sigma_t = ( + torch.sqrt(torch.sigmoid(-logsnr_t)) + .view(2*scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + .to(scene_tensor.device) + ) + z_t, eps_t = self.diffuse(scene_tensor.repeat(2,1,1,1), alpha_t, sigma_t) + + pred = self.model( + diffused_scene_tensor=z_t, + diffusion_times=diffusion_times, + local_context=local_context.repeat(2,1,1,1), + valid_mask=valid_mask.repeat(2,1,1), + global_context=global_context.repeat(2,1,1), + ) + + if self.pred_param == "v": + x_pred = alpha_t * z_t - sigma_t * pred + else: + x_pred = (z_t - sigma_t * pred) / alpha_t + + z_t_hn,z_t_ln = z_t.chunk(2, dim=0) + x_pred_hn,x_pred_ln = x_pred.chunk(2, dim=0) + logsnr_t_hn,logsnr_t_ln = logsnr_t.chunk(2, dim=0) + alpha_t_hn,alpha_t_ln = alpha_t.chunk(2, dim=0) + sigma_t_hn,sigma_t_ln = sigma_t.chunk(2, dim=0) + pred_hn,pred_ln = pred.chunk(2, dim=0) + + # Apply min-SNR weighting (https://arxiv.org/pdf/2303.09556) + snr = torch.exp(logsnr_t_hn).clamp_(max=5) + if self.pred_param == "v": + weight = 1 / (1 + snr) + else: + weight = 1 / snr + + weight = weight.view(scene_tensor.shape[0], scene_tensor.shape[1], scene_tensor.shape[2], 1) + + # add zero weights to invalid pixels + weight = weight * valid_mask.unsqueeze(-1) + # weight = weight * torch.logical_not(task_mask) + + loss = torch.sum(weight * (x_pred_hn - scene_tensor) ** 2) + consist_loss = torch.sum(weight * (x_pred_hn - x_pred_ln) ** 2) + velo_loss = self.compute_traj_loss(pred_hn, alpha_t_hn, z_t_hn, sigma_t_hn, valid_mask, weight) + map_loss = self.compute_map_loss(pred_hn, alpha_t_hn, z_t_hn, sigma_t_hn, valid_mask, weight, raw_map) + + loss = self.loss_factor[0] * loss + self.loss_factor[1] * velo_loss + self.loss_factor[2] * map_loss + self.loss_factor[3] * consist_loss + # loss = loss + map_loss + velo_loss + return ( + loss, + dict( + # diffused_scene_tensor=z_t, + # pred_scene_tensor=x_pred, + ), + ) diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/encoders/__init__.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/encoders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/encoders/perciever_context_encoder.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/encoders/perciever_context_encoder.py new file mode 100644 index 0000000..7924250 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/encoders/perciever_context_encoder.py @@ -0,0 +1,488 @@ +# code from https://github.com/esceptico/perceiver-io/ +from typing import Optional + +import torch +import torch.nn as nn +from nuplan.planning.training.modeling.types import TargetsType + +from nuplan_extent.planning.training.preprocessing.feature_builders.nexus_feature_builder import ( + SceneTensor, +) + +import os + +class LoRALayer(nn.Module): + def __init__(self, linear_layer, use_lora: bool = False, rank=8): + """ + Wraps a linear layer and adds LoRA (Low-Rank Adaptation). + + Args: + linear_layer (nn.Linear): The linear layer to be wrapped. + rank (int): Rank of the low-rank decomposition. Default is 8. + """ + super(LoRALayer, self).__init__() + + # self.use_lora = use_lora + # if os.environ.get('USE_LoRA', 'False').lower() == 'true': + # self.use_lora = True + + # Get the shape of the original weight matrix + self.in_features = linear_layer.in_features + self.out_features = linear_layer.out_features + # Initialize LoRA matrices A and B + self.lora_A = nn.Parameter(torch.zeros(self.in_features, rank)) # LoRA matrix A + self.lora_B = nn.Parameter(torch.zeros(rank, self.out_features)) # LoRA matrix B + + # Apply Kaiming initialization to LoRA matrix A + nn.init.kaiming_normal_(self.lora_A, mode='fan_in', nonlinearity='relu') + + def forward(self, x): + """ + Forward pass. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor. + """ + # if self.use_lora: + # # LoRA output: x @ A @ B + # lora_output = x @ self.lora_A @ self.lora_B + # else: + # lora_output = 0. + lora_output = x @ self.lora_A @ self.lora_B + return lora_output + + +class MultiHeadAttention(nn.Module): + """Multi-head attention""" + + def __init__( + self, + kv_dim: int, + q_dim: int, + *, + qk_out_dim: Optional[int] = None, + v_out_dim: Optional[int] = None, + output_dim: Optional[int] = None, + num_heads: int = 1, + dropout: float = 0.0, + ): + """Constructor. + + Args: + kv_dim: Size of input key and value vectors. + q_dim: Size of input query vector. + qk_out_dim: Size of Query and Key matrices last dimension. + If None, it will be equal to q_dim. Defaults to None. + v_out_dim: Size of Value matrix last dimension. + If None, it will be equal to qk_out_dim. Defaults to None. + output_dim: Size of output after the QKV attention. + If none, it will be equal to v_out_dim. Defaults to None. + num_heads: Number of heads. Defaults to 1. + dropout: Dropout probability. Defaults to 0.0. + """ + super().__init__() + + if qk_out_dim is None: + qk_out_dim = q_dim + if v_out_dim is None: + v_out_dim = qk_out_dim + if output_dim is None: + output_dim = v_out_dim + + self.num_heads = num_heads + self.qk_head_dim = qk_out_dim // num_heads + self.v_head_dim = v_out_dim // num_heads + + self.q = nn.Linear(q_dim, qk_out_dim) + self.v = nn.Linear(kv_dim, v_out_dim) + + self.use_lora = os.environ.get('USE_LoRA', 'False').lower() == 'true' + # lora layer + if self.use_lora: + self.q_lora = LoRALayer(self.q) + self.v_lora = LoRALayer(self.v) + + self.k = nn.Linear(kv_dim, qk_out_dim) + self.projection = nn.Linear(v_out_dim, output_dim) + self.dropout = nn.Dropout(dropout) + self.scale = self.qk_head_dim**-0.5 + + def transform_for_scores(self, x: torch.Tensor, head_dim: int): + # (..., seq_len, dim) -> (..., n_heads, seq_len, head_dim) + *dims, seq, hid = x.size() + x = x.view(*dims, seq, self.num_heads, head_dim) + return x.transpose(-3, -2) + + def forward( + self, + inputs_kv: torch.Tensor, + inputs_q: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + ): + """ + Args: + inputs_kv: Key/Value embeddings of shape (B, ..., M, C). + inputs_q: Query embeddings of shape (B, ..., N, D) + attention_mask: Tensor of shape (B, ..., N, M). + + Returns: + Tensor of shape (B, ..., N, D) + """ + keys, queries, values = self.k(inputs_kv), self.q(inputs_q), self.v(inputs_kv) + # lora layer + if self.use_lora: + queries += self.q_lora(inputs_q) + values += self.v_lora(inputs_kv) + + keys = self.transform_for_scores(keys, self.qk_head_dim) + queries = self.transform_for_scores(queries, self.qk_head_dim) + values = self.transform_for_scores(values, self.v_head_dim) + attention = queries @ keys.transpose(-2, -1) * self.scale + if attention_mask is not None: + min_value = torch.finfo(attention.dtype).min + extended_mask = ~attention_mask * min_value + attention = attention + extended_mask + attention = attention.softmax(dim=-1) + attention = self.dropout(attention) + if attention_mask is not None: + attention = attention.masked_fill(~attention_mask, value=0) + weighted = attention @ values + # (..., n_heads, seq_len, head_dim) -> (..., seq_len, hid) + *dims, n_heads, seq, hid = weighted.size() + weighted = weighted.transpose(-3, -2) + weighted = weighted.reshape(*dims, seq, n_heads * hid) + return self.projection(weighted) + + +class FeedForward(nn.Module): + """Transformer Feed-Forward network.""" + + def __init__(self, dim: int, widening_factor: int = 4, dropout: float = 0.0): + """Constructor. + + Args: + dim: Dimension of input tensor. + widening_factor: Widening factor. Defaults to 4. + dropout: Dropout probability. Defaults to 0. + """ + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(dim, dim * widening_factor), + nn.GELU(), + nn.Linear(dim * widening_factor, dim), + nn.Dropout(dropout), + ) + + def forward(self, x: torch.Tensor): + return self.mlp(x) + + +class SelfAttention(nn.Module): + """Self-attention module.""" + + def __init__( + self, + *, + hidden_dim: int, + qk_out_dim: Optional[int] = None, + v_out_dim: Optional[int] = None, + widening_factor: int = 4, + num_heads: int = 1, + dropout: float = 0.0, + attention_dropout: float = 0.0, + ): + """Constructor. + + Args: + hidden_dim: Dimension of input tensor. + qk_out_dim: Size of Query and Key matrices last dimension. + Defaults to None. + v_out_dim: Size of Value matrix last dimension. + Defaults to None. + widening_factor: Feed-forward network widening factor. + Defaults to 4. + num_heads: Number of attention heads. Defaults to 1. + dropout: Dropout probability. Defaults to 0. + attention_dropout: Attention scores probability. Defaults to 0. + """ + super().__init__() + self.layer_norm = nn.LayerNorm(hidden_dim) + self.qkv_layer_norm = nn.LayerNorm(hidden_dim) + self.attention = MultiHeadAttention( + kv_dim=hidden_dim, + q_dim=hidden_dim, + qk_out_dim=qk_out_dim, + v_out_dim=v_out_dim, + output_dim=hidden_dim, + num_heads=num_heads, + dropout=attention_dropout, + ) + self.dropout = nn.Dropout(dropout) + self.mlp = FeedForward(hidden_dim, widening_factor, dropout) + + def forward(self, x: torch.Tensor, attention_mask: Optional[torch.Tensor] = None): + """ + Args: + x: Input tensor of shape (B, ..., M, C). + attention_mask: Input mask tensor of shape (B, ..., M, M). + Mask values selected in [0, 1]. Defaults to None. + """ + x_norm = self.layer_norm(x) + attention = self.attention( + inputs_kv=x_norm, inputs_q=x_norm, attention_mask=attention_mask + ) + attention = self.dropout(attention) + x = x + attention + x = x + self.mlp(self.qkv_layer_norm(x)) + return x + + +class CrossAttention(nn.Module): + """Cross-attention module.""" + + def __init__( + self, + *, + kv_dim: int, + q_dim: int, + qk_out_dim: Optional[int] = None, + v_out_dim: Optional[int] = None, + widening_factor: int = 1, + num_heads: int = 1, + use_query_residual: bool = True, + dropout: float = 0.0, + attention_dropout: float = 0.0, + ): + """Constructor. + + Args: + kv_dim: Dimension of key/value input tensor. + q_dim: Dimension of query input tensor. + qk_out_dim: Size of Query and Key matrices last dimension. + Defaults to None. + v_out_dim: Size of Value matrix last dimension. + Defaults to None. + widening_factor: Feed-forward network widening factor. + Defaults to 4. + num_heads: Number of attention heads. Defaults to 1. + use_query_residual: Indicates whether to use query residual in + cross-attention. Defaults to True. + dropout: Dropout probability. Defaults to 0. + attention_dropout: Attention scores probability. Defaults to 0. + """ + super().__init__() + self.use_query_residual = use_query_residual + self.kv_layer_norm = nn.LayerNorm(kv_dim) + self.q_layer_norm = nn.LayerNorm(q_dim) + self.qkv_layer_norm = nn.LayerNorm(q_dim) + self.attention = MultiHeadAttention( + kv_dim=kv_dim, + q_dim=q_dim, + qk_out_dim=qk_out_dim, + v_out_dim=v_out_dim, + output_dim=q_dim, + num_heads=num_heads, + dropout=attention_dropout, + ) + self.dropout = nn.Dropout(dropout) + self.mlp = FeedForward(q_dim, widening_factor, dropout) + + def forward( + self, + inputs_kv: torch.Tensor, + inputs_q: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + ): + """ + Args: + inputs_kv: Key/Value embeddings of shape (B, ..., M, C). + inputs_q: Query embeddings of shape (B, ..., N, D) + attention_mask: Tensor of shape (B, ..., N, M). Mask values selected + in [0, 1]. Defaults to None. + """ + attention = self.attention( + inputs_kv=self.kv_layer_norm(inputs_kv), + inputs_q=self.q_layer_norm(inputs_q), + attention_mask=attention_mask, + ) + attention = self.dropout(attention) + if self.use_query_residual: + x = inputs_q + attention + else: + x = attention + x = x + self.mlp(self.qkv_layer_norm(x)) + return x + + +class Encoder(nn.Module): + """Perceiver encoder module. Consists of two components: cross-attention + module that maps an input tensor and a trainable latent tensor to a latent + tensor and a stacked Transformer blocks with shared weights. + """ + + def __init__( + self, + num_latents: int, + latent_dim: int, + input_dim: int, + num_self_attn_per_block: int = 2, + num_blocks: int = 4, + qk_out_dim: Optional[int] = None, + v_out_dim: Optional[int] = None, + num_cross_attn_heads: int = 1, + num_self_attn_heads: int = 8, + cross_attn_widening_factor: int = 1, + self_attn_widening_factor: int = 1, + use_query_residual: bool = True, + dropout: float = 0.0, + cross_attention_dropout: float = 0.0, + self_attention_dropout: float = 0.0, + ): + """Constructor. + + Args: + num_latents: Number of latent vectors. + latent_dim: Dimension of latent vector. + input_dim: Dimension of input tensor. + num_self_attn_per_block: Number of self-attention modules per + transformer block. Defaults to 2. + num_blocks: Number of transformer blocks. Defaults to 4. + qk_out_dim: Size of Query and Key matrices last dimension. + Defaults to None. + v_out_dim: Size of Value matrix last dimension. + Defaults to None. + num_cross_attn_heads: Number of cross-attention heads. + Defaults to 1. + num_self_attn_heads: Number of self-attention heads. + Defaults to 8. + cross_attn_widening_factor: Widening factor in cross-attention + feed-forward layer. Defaults to 1. + self_attn_widening_factor: Widening factor in self-attention + feed-forward layer. Defaults to 1. + use_query_residual: Indicates whether to use query residual in + cross-attention. Defaults to True. + dropout: Feed-forward dropout probability. Defaults to 0. + cross_attention_dropout: Cross-attention scores dropout probability. + Defaults to 0. + self_attention_dropout: Self-attention scores dropout probability. + Defaults to 0. + """ + super().__init__() + self.num_blocks = num_blocks + + self.latents = nn.Parameter(torch.randn(num_latents, latent_dim)) + self.cross_attn = CrossAttention( + kv_dim=input_dim, + q_dim=latent_dim, + widening_factor=cross_attn_widening_factor, + num_heads=num_cross_attn_heads, + qk_out_dim=qk_out_dim, + v_out_dim=v_out_dim, + use_query_residual=use_query_residual, + dropout=dropout, + attention_dropout=cross_attention_dropout, + ) + self.self_attention_block = nn.ModuleList( + [ + SelfAttention( + hidden_dim=latent_dim, + widening_factor=self_attn_widening_factor, + num_heads=num_self_attn_heads, + qk_out_dim=qk_out_dim, + v_out_dim=v_out_dim, + dropout=dropout, + attention_dropout=self_attention_dropout, + ) + for _ in range(num_self_attn_per_block) + ] + ) + + def forward(self, x: torch.Tensor, kv_mask: Optional[torch.Tensor] = None): + """ + Args: + x: Input tensor of shape (B, M, C). + kv_mask: Input mask tensor of shape (B, M). Mask values selected + in [0, 1]. Defaults to None. + + Returns: + Latent tensor. + """ + batch_size = x.size(0) + if kv_mask is not None: + kv_mask = kv_mask[:, None, None, :] + + latents = self.cross_attn( + inputs_kv=x, + inputs_q=self.latents.repeat(batch_size, 1, 1), + attention_mask=kv_mask, + ) + for _ in range(self.num_blocks): + for self_attn_layer in self.self_attention_block: + latents = self_attn_layer(latents) + return latents + + +class PercieverEncoder(nn.Module): + """Wrapper around the perciever io encoder""" + + def __init__( + self, + num_latents: int, + latent_dim: int, + input_dim: int, + num_self_attn_per_block: int = 2, + num_blocks: int = 4, + qk_out_dim: Optional[int] = None, + v_out_dim: Optional[int] = None, + num_cross_attn_heads: int = 1, + num_self_attn_heads: int = 8, + cross_attn_widening_factor: int = 1, + self_attn_widening_factor: int = 1, + use_query_residual: bool = True, + dropout: float = 0.0, + cross_attention_dropout: float = 0.0, + self_attention_dropout: float = 0.0, + ): + super().__init__() + self._encoder = Encoder( + num_latents, + latent_dim, + input_dim, + num_self_attn_per_block, + num_blocks, + qk_out_dim, + v_out_dim, + num_cross_attn_heads, + num_self_attn_heads, + cross_attn_widening_factor, + self_attn_widening_factor, + use_query_residual, + dropout, + cross_attention_dropout, + self_attention_dropout, + ) + + def forward(self, scene_tensor: SceneTensor) -> TargetsType: + """ + Predict + :param features: input features containing rasterized data. + features['raster'] is a HorizonRasterV2 object or a dictionary of + raster layer tensors. + :return: encoder_features: dict of predictions from network + """ + rg: torch.Tensor = scene_tensor.road_graph # B x n_lines x n_points x n_dim + rgv: torch.Tensor = scene_tensor.road_graph_validity + rg_invalid = (rgv == 0.0).all(dim=-1) # B x n_lines x n_points + B, NL, NP, ND = rg.shape + + rg = rg.view(B, NL * NP, ND) + rg_invalid = rg_invalid.view(B, NL * NP) + + latents = self._encoder.forward( + x=rg, kv_mask=rg_invalid + ) # B x n_latents x latent dim + + return latents diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/nexus_with_opt.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/nexus_with_opt.py new file mode 100644 index 0000000..17513bb --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/nexus_with_opt.py @@ -0,0 +1,614 @@ +import logging +import torch +import numpy as np + +from torch import nn +from typing import List, Dict + +from nuplan.planning.simulation.trajectory.trajectory_sampling import TrajectorySampling +from nuplan.planning.training.modeling.torch_module_wrapper import TorchModuleWrapper +from nuplan.planning.training.modeling.types import FeaturesType, TargetsType +from nuplan.planning.training.preprocessing.feature_builders.abstract_feature_builder import ( + AbstractFeatureBuilder, +) +from nuplan.planning.training.preprocessing.target_builders.abstract_target_builder import ( + AbstractTargetBuilder, +) + +from nuplan_extent.planning.training.preprocessing.feature_builders.nexus_feature_builder import ( + SceneTensor, + N_SCENE_TENSOR_FEATURES, +) +import torch.distributions as tdist +import random +import time +from ...preprocessing.features.scene_tensor import decode_scene_tensor + +np.set_printoptions(precision=2, suppress=True) + +logger = logging.getLogger(__name__) + + + +class Nexus(TorchModuleWrapper): + def __init__( + self, + diffuser: nn.Module, + global_encoder: nn.Module, + render: nn.Module, + feature_builders: List[AbstractFeatureBuilder], + target_builders: List[AbstractTargetBuilder], + future_trajectory_sampling: TrajectorySampling, + postprocessor: nn.Module = None, + pretraining_path: str = None, + num_paralell_scenario: int = 1, + num_conditioned_frames: int = 4, + downstream_task: str = "scenario_extrapolation", + temporal_schedule_prob: float = 0.5, + behavior_pred_task_prob: float = 0.5, + control_agent_prob: float = 0.9, + control_time_prob: float = 0.9, + control_feature_prob: List[float] = [0.9] * N_SCENE_TENSOR_FEATURES, + forcing: bool = True, + ): + super().__init__( + feature_builders=feature_builders, + target_builders=target_builders, + future_trajectory_sampling=future_trajectory_sampling, + ) + self.diffuser = diffuser + self.global_encoder = global_encoder + self.render = render + self.postprocessor = postprocessor + self._num_paralell_scenario = num_paralell_scenario + self._num_conditioned_frames = num_conditioned_frames + self._downstream_task = downstream_task + self._temporal_schedule_prob = temporal_schedule_prob + self._behavior_pred_task_prob = behavior_pred_task_prob + self._control_agent_prob = control_agent_prob + self._control_time_prob = control_time_prob + self._control_feature_prob = torch.tensor(control_feature_prob) + + self.pretraining_path = pretraining_path + self.load_pretrained_weights() + self.forcing = True + # self.schedule_prob = [0.2, 0.4, 0.6, 0.8] + # self.schedule_prob = [0.5, 1.0, 1.0, 1.0] + self.schedule_prob = [0., 0., 0., 1.0] + + def _build_model(self): + pass + + def set_vis_features(self, is_vis_features: bool, vis_features_path: str): + """ + Set params for saving features, for visualization, only when simulation feature video callback is on. + :param is_vis_features: whether to save features + :param vis_features_path: path to save features + """ + self._is_vis_features = is_vis_features + self._vis_features_path = vis_features_path + + def load_pretrained_weights(self): + logger.info(f"loading pretrained weights: {self.pretraining_path}") + + def match_incompatible_keys(checkpoint_state_dict, src, dst): + filtered_state_dict = {} + for name, param in checkpoint_state_dict.items(): + if name.startswith(src): + name = name[len(src) :] + filtered_state_dict[name] = param + return filtered_state_dict + + def filter_incompatible_keys( + model_state_dict, checkpoint_state_dict, name_prefix="" + ): + filtered_state_dict = {} + for name, param in checkpoint_state_dict.items(): + name = name_prefix + name + if ( + name in model_state_dict + and param.shape == model_state_dict[name].shape + ): + filtered_state_dict[name] = param + else: + logger.info(f"Skipping incompatible key: {name}") + return filtered_state_dict + + if self.pretraining_path is not None: + checkpoint = torch.load(self.pretraining_path, map_location="cpu")[ + "state_dict" + ] + checkpoint = match_incompatible_keys(checkpoint, src="model.", dst="") + + checkpoint_not_found_num = 0 + model_not_found_num = 0 + for k, v in checkpoint.items(): + if k not in self.state_dict() or self.state_dict()[k].shape != v.shape: + logger.info(f"{k} not in model") + print(f"{k} not in model") + checkpoint_not_found_num += 1 + for k, v in self.state_dict().items(): + if k not in checkpoint or checkpoint[k].shape != v.shape: + logger.info(f"{k} not in checkpoint") + model_not_found_num += 1 + self.load_state_dict( + filter_incompatible_keys(self.state_dict(), checkpoint), strict=False + ) + logger.info( + f"checkpoint not found num: {checkpoint_not_found_num}/{len(checkpoint)}, model not found num: {model_not_found_num}/{len(self.state_dict())}" + ) + # lora.mark_only_lora_as_trainable(self, bias='lora_only') + + def forward(self, input_features: FeaturesType, scenario=None) -> TargetsType: + """ + Predict + :param input_features: input features containing + :return: targets: predictions from network + """ + if self.training: + return self.forward_train(input_features) + else: + with torch.no_grad(): + # import pdb; pdb.set_trace() + if self._downstream_task is not None and 'sim_agents' in self._downstream_task : + # Waymo Sim Agents rollout -> 32 parallel worlds, 8s into future + return self.sim_agents_batched_rollout(input_features) + if "task_mask" in input_features: + return self.forward_inference(input_features) + else: + return self.forward_validation(input_features) + + def sim_agents_batched_rollout(self, input_features): + # import pdb; pdb.set_trace() + n_rollouts = 32 + # Extract the last dimension to agents_id + agents_id = input_features['scene_tensor'].tensor[:,:,0, -1] + # Remove the last dimension from input_features['scene_tensor'].tensor + input_features['scene_tensor'].tensor = input_features['scene_tensor'].tensor[..., :-1] + # repeat and batch essential features: [B, ...] => [32*B, ...] + tmp_feature_dict = input_features.copy() + original_bs = tmp_feature_dict["scene_tensor"].tensor.shape[0] + # repeat the scene_tensor: [0-31: batch 1], [32-63: batch 2].... + for key, value in vars(tmp_feature_dict['scene_tensor']).items(): + if isinstance(value, torch.Tensor): + tmp_feature_dict['scene_tensor'].__setattr__(key, value.repeat_interleave(n_rollouts, dim=0)) + + # inpainting here + scene_tensor_features: SceneTensor = tmp_feature_dict["scene_tensor"] + global_context = self.global_encoder(scene_tensor_features) + + if 'test' in self._downstream_task: + # all valid tokens in scene_tensor should be kept in test time + # keep_mask = scene_tensor_features.validity.unsqueeze(-1).expand(-1, -1, -1, scene_tensor_features.tensor.shape[-1]) + valid_mask = scene_tensor_features.validity + valid_mask,keep_mask = valid_mask.chunk(2,dim=-1) + keep_mask = keep_mask.unsqueeze(-1).repeat(1,1,1,scene_tensor_features.tensor.shape[-1]) + # diffusion model only generates tokens where valid_mask is 1, + # in waymo, agents present at current timestep(5th) should be predicted in future timesteps(8s@2Hz) + # valid_mask = scene_tensor_features.validity.clone() + valid_mask[:, :, 5:] = (scene_tensor_features.validity[:, :, 4:5] == 1).expand(-1, -1, 16) + + elif 'val' in self._downstream_task: + n_past_timesteps = 5 + if True: + # behavior prediction task + keep_mask = torch.zeros_like(scene_tensor_features.tensor) + keep_mask[:, :, :n_past_timesteps] = 1 + valid_mask = scene_tensor_features.validity.clone() + else: + # intent prediction task + valid_mask = scene_tensor_features.validity + valid_mask,keep_mask = valid_mask.chunk(2,dim=-1) + # keep_mask[...,-1] = 0 + keep_mask = keep_mask.unsqueeze(-1).repeat(1,1,1,scene_tensor_features.tensor.shape[-1]) + else: + raise NotImplementedError(f'Unknown downstream task: {self._downstream_task}') + + self.diffuser.model.eval() + sampled_tensor, _ = self.diffuser.sample( + scene_tensor=scene_tensor_features.tensor, + valid_mask=valid_mask, + keep_mask=keep_mask, + global_context=global_context, + raw_map=self.extract_raw_map(scene_tensor_features) + ) # batch, n_agents, n_timesteps, n_features + # n_features (x, y, cos(yaw), sin(yaw), l, w) + self.diffuser.model.train() + sampled_tensor = decode_scene_tensor(sampled_tensor) + # reshape into [[32 rollout for b1], [32 rollout for b2], ...] format. + sim_agent_rollouts = [[] for _ in range(original_bs)] + for batch_index, tok_seq in enumerate(sampled_tensor): + batch_number = batch_index // n_rollouts + sim_agent_rollouts[batch_number].append(tok_seq) + out = {"scene_tensor": input_features['scene_tensor'], + "sim_agents_rollouts": sim_agent_rollouts, + "agents_map": agents_id} + return out + + def generate_task_mask( + self, scene_tensor_features: SceneTensor, n_past_timesteps: int + ) -> torch.Tensor: + n_valid_agents_per_sample = scene_tensor_features.validity.any(dim=-1).sum( + dim=-1 + ) + # sample a random number of agents to condition on, one for each sample + task_mask_sg = torch.zeros_like(scene_tensor_features.tensor) + for batch_idx in range(scene_tensor_features.tensor.shape[0]): + n = n_valid_agents_per_sample[batch_idx] + n_chosen = torch.randint(0, n, (1,), device=n.device) + mask = torch.rand(n, device=n.device) < n_chosen / n # NA + + task_mask_sg[batch_idx, :n] = mask.unsqueeze(-1).unsqueeze(-1) + # always condition on ego + task_mask_sg[:, 0] = 1.0 + + task_mask_bp = torch.zeros_like(scene_tensor_features.tensor) + task_mask_bp[:, :, :n_past_timesteps] = 1 + + task_type = torch.rand(scene_tensor_features.tensor.shape[0]) # B + task_mask = torch.zeros_like(scene_tensor_features.tensor) + behavior_task_idx = task_type < self._behavior_pred_task_prob + task_mask[behavior_task_idx] = task_mask_bp[behavior_task_idx] + task_mask[~behavior_task_idx] = task_mask_sg[~behavior_task_idx] + + return task_mask + + def _generate_gaussian_diffusion_times(self, scene_tensor_features: SceneTensor): + + B, NA, NT = scene_tensor_features.tensor.shape[:3] + device = scene_tensor_features.tensor.device + valid_mask = scene_tensor_features.validity.bool() + diffusion_times_gaussian = torch.rand(B, 1, 1, device=device,).repeat(1, NA, NT) # this each batch sample get a random diffusion time + + def generate_gaussian(N_min=2, N_max=3, mu_min=0, mu_max=21, std_min=0.1, std_max=2.0, strength=0.2, mesh=None, device=device): + N = np.random.choice(np.arange(N_min, N_max+1)) + mus_x = torch.rand(N, device=device) * (mu_max - mu_min) + mu_min + stds_x = torch.rand(N, device=device) * (std_max - std_min) + std_min + random_values = torch.randint(0, 2, (N,), device=device) * 2 - 1 + mus_x = mus_x.view(N, 1, 1) + stds_x = stds_x.view(N, 1, 1) + random_values = random_values.view(N, 1, 1) + dist_x = tdist.Normal(mus_x, stds_x) + probs_x = strength * torch.exp(dist_x.log_prob(mesh.unsqueeze(0).repeat(N, 1, 1))) * random_values + return probs_x + + x_values = torch.arange(0, NA, device=device) + y_values = torch.arange(0, NT, device=device) + x_mesh, y_mesh = torch.meshgrid(x_values, y_values) + + probs_list = [] + for _ in range(B): + probs_x = generate_gaussian(N_min=5, N_max=10, mesh=x_mesh, device=device) + probs_y = generate_gaussian(mesh=y_mesh, device=device) + probs_sum = torch.sum(probs_x, dim=0) + torch.sum(probs_y, dim=0) + probs_list.append(probs_sum) + + probs_tensor = torch.stack(probs_list, dim=0) + diffusion_times_gaussian = torch.clamp((diffusion_times_gaussian + probs_tensor), min=0, max=1) + + return diffusion_times_gaussian + + def _generate_diffusion_forcing_times(self, scene_tensor_features: SceneTensor): + B, NA, NT = scene_tensor_features.tensor.shape[:3] + device = scene_tensor_features.tensor.device + valid_mask = scene_tensor_features.validity.bool() + + diffusion_times_uniform = torch.rand(B, 1, 1, device=device,).repeat(1, NA, NT) # this each batch sample get a random diffusion time + diffusion_times_temporal = torch.arange(1, NT+1, step=1, device=device,).unsqueeze(0).unsqueeze(0).repeat(B, NA, 1) + # take max + n_history_steps = 5 + n_future_steps = 16 + diffusion_times_temporal = torch.max( + torch.tensor(0), + (diffusion_times_temporal - n_history_steps) / n_future_steps, + ) + diffusion_times_agent = torch.rand(B, NA, 1, device=device,).repeat(1, 1, NT) # each agent get a random diffusion time + diffusion_times_random = torch.rand(B, NA, NT, device=device,) # each token get a random diffusion time + diffusion_times_gaussian = self._generate_gaussian_diffusion_times(scene_tensor_features) + + diffusion_times = torch.zeros(B, NA, NT, device=device,) + + rand_index = torch.rand(B) + time_idx = (rand_index < self.schedule_prob[0]) + diffusion_times[time_idx] = diffusion_times_uniform[time_idx] + + time_idx = (rand_index >= self.schedule_prob[0]) & (rand_index < self.schedule_prob[1]) + diffusion_times[time_idx] = diffusion_times_temporal[time_idx] + + time_idx = (rand_index >= self.schedule_prob[1]) & (rand_index < self.schedule_prob[2]) + diffusion_times[time_idx] = diffusion_times_agent[time_idx] + + time_idx = (rand_index >= self.schedule_prob[2]) & (rand_index < self.schedule_prob[3]) + diffusion_times[time_idx] = diffusion_times_random[time_idx] + + time_idx = (rand_index >= self.schedule_prob[3]) + diffusion_times[time_idx] = diffusion_times_gaussian[time_idx] + + diffusion_times = torch.where(~valid_mask, torch.full_like(diffusion_times, 1), diffusion_times) + + return diffusion_times + + def _generate_diffusion_times( + self, scene_tensor_features: SceneTensor + ) -> torch.Tensor: + diffusion_times_uniform = torch.rand( + scene_tensor_features.tensor.shape[0], + 1, + device=scene_tensor_features.tensor.device, + ).repeat( + 1, scene_tensor_features.tensor.shape[2] + ) # this each sample get a random diffusion time B x A x T + + diffusion_times_temporal = ( + torch.arange( + 0, + scene_tensor_features.tensor.shape[2], + step=1, + device=scene_tensor_features.tensor.device, + ) + .unsqueeze(0) + .repeat(scene_tensor_features.tensor.shape[0], 1) + ) # B, T t = 0 ... 1 with the dimension + # take max of + n_history_steps = 5 + n_future_steps = 16 + diffusion_times_temporal = torch.max( + torch.tensor(0), + (diffusion_times_temporal - n_history_steps) / n_future_steps, + ) + + diffusion_times = torch.zeros( + scene_tensor_features.tensor.shape[0], + scene_tensor_features.tensor.shape[2], + device=scene_tensor_features.tensor.device, + ) + + temporal_time_idx = ( + torch.rand(scene_tensor_features.tensor.shape[0]) + < self._temporal_schedule_prob + ) + diffusion_times[temporal_time_idx] = diffusion_times_temporal[temporal_time_idx] + diffusion_times[~temporal_time_idx] = diffusion_times_uniform[ + ~temporal_time_idx + ] + + return diffusion_times + + def generate_diffusion_times(self, scene_tensor_features: SceneTensor): + if self.forcing: + return self._generate_diffusion_forcing_times(scene_tensor_features) + else: + return self._generate_diffusion_times(scene_tensor_features) + + def generate_control_mask(self, scene_tensor_features: SceneTensor) -> torch.Tensor: + # TODO implement control mask + # 1 is valid + control_agent = ( + torch.rand( + scene_tensor_features.tensor.shape[0], + scene_tensor_features.tensor.shape[1], + device=scene_tensor_features.tensor.device, + ) + < self._control_agent_prob + ) + control_time = ( + torch.rand( + scene_tensor_features.tensor.shape[0], + scene_tensor_features.tensor.shape[1], + scene_tensor_features.tensor.shape[2], + device=scene_tensor_features.tensor.device, + ) + < self._control_time_prob + ) + control_feature = ( + torch.rand( + scene_tensor_features.tensor.shape[0], + scene_tensor_features.tensor.shape[1], + scene_tensor_features.tensor.shape[2], + scene_tensor_features.tensor.shape[3], + device=scene_tensor_features.tensor.device, + ) + < self._control_feature_prob + ) + + control_mask = torch.ones_like(scene_tensor_features.tensor) + # control_mask[control_agent] = 1 + control_mask[control_time] = 0 + # control_mask[control_feature] = 1 + return control_mask + + def generate_goal_mask(self, scene_tensor_features: SceneTensor, diffusion_times: torch.Tensor) -> torch.Tensor: + self.goal_threshold = 0.15 + self.zero_prob = 0.5 + goal_mask = diffusion_times < self.goal_threshold + zero_mask = torch.rand(diffusion_times.shape, device=diffusion_times.device) < self.zero_prob + + diffusion_times = torch.where(torch.logical_and(goal_mask, zero_mask), torch.zeros_like(diffusion_times, device=diffusion_times.device), diffusion_times) + + control_mask = torch.zeros_like(scene_tensor_features.tensor) + control_mask[diffusion_times==0] = 1 + + return control_mask, diffusion_times + + def forward_train(self, input_features: FeaturesType) -> Dict: + """ + Forward pass for training + :param input_features: input features + :param targets: targets + """ + # import pdb; pdb.set_trace() + # Encode image + input_features['scene_tensor'].tensor = input_features['scene_tensor'].tensor[...,:8] # to exclude agents id from scene_tensor + scene_tensor_features: SceneTensor = input_features["scene_tensor"] # [B A T C] + global_context = self.global_encoder(scene_tensor_features) # [B L C] + + n_past_timesteps = 4 + 1 # 1 current timestep + 4 past timesteps + present_mask = scene_tensor_features.validity[:, :, :n_past_timesteps].any( + dim=-1 + ) + for batch_idx in range(scene_tensor_features.tensor.shape[0]): + scene_tensor_features.validity[batch_idx, ~present_mask[batch_idx], :] = 0 + + # decice on the schedule + diffusion_times = self.generate_diffusion_times(scene_tensor_features) # [B T] + + # decide on task, here is conditioned scene generation + task_mask = self.generate_task_mask(scene_tensor_features, n_past_timesteps) + + # control_mask = self.generate_control_mask(scene_tensor_features) + control_mask, diffusion_times = self.generate_goal_mask(scene_tensor_features, diffusion_times) + + loss, outs = self.diffuser.compute_loss( # type: ignore + scene_tensor=scene_tensor_features.tensor, + valid_mask=scene_tensor_features.validity, + global_context=global_context, + diffusion_times=diffusion_times, + task_mask=task_mask, + control_mask=control_mask, + raw_map=self.extract_raw_map(scene_tensor_features) + ) + + return dict( + diffusion_out={ + "loss": loss, + "scene_tensor": scene_tensor_features.tensor, + "valid_mask": scene_tensor_features.validity, + "task_mask": task_mask, + **{k: v.detach() for k, v in outs.items()}, + } + ) + + def forward_validation(self, input_features: FeaturesType) -> Dict: + # Encode image + # global_context = self.image_encoder(input_features) # B, L, C + input_features['scene_tensor'].tensor = input_features['scene_tensor'].tensor[...,:8] # to exclude agents id from scene_tensor + scene_tensor_features: SceneTensor = input_features["scene_tensor"] + global_context = self.global_encoder(scene_tensor_features) + + n_past_timesteps = 4 + 1 # 1 current timestep + 4 past timesteps + present_mask = scene_tensor_features.validity[:, :, :n_past_timesteps].any( + dim=-1 + ) + + for batch_idx in range(scene_tensor_features.tensor.shape[0]): + scene_tensor_features.validity[batch_idx, ~present_mask[batch_idx], :] = 0 + + task_mask_bp = torch.zeros_like(scene_tensor_features.tensor) + task_mask_bp[:, :, :n_past_timesteps] = 1 + + time_consume = 0 + time_start = time.time() + xpred, _ = self.diffuser.sample( + scene_tensor=scene_tensor_features.tensor, + valid_mask=scene_tensor_features.validity, + global_context=global_context, + z_t=None, + keep_mask=task_mask_bp, + raw_map=self.extract_raw_map(scene_tensor_features) + # use_guidance_fn=True, + ) + time_end = time.time() + time_consume += time_end - time_start + # ensure that the last valid timestep is also conditioned on + valid_mask = scene_tensor_features.validity + intent_conditioned_task_mask_bp = torch.zeros_like(scene_tensor_features.tensor) + intent_conditioned_task_mask_bp[:, :, :n_past_timesteps] = 1 + last_valid_indices = torch.max( + (valid_mask == 1).float() + * torch.arange(valid_mask.shape[-1], device=valid_mask.device).float(), + dim=-1, + )[1] + batch_indices = torch.arange(valid_mask.shape[0], device=valid_mask.device)[ + :, None + ].expand(-1, valid_mask.shape[1]) + agent_indices = torch.arange(valid_mask.shape[1], device=valid_mask.device)[ + None, : + ].expand(valid_mask.shape[0], -1) + intent_conditioned_task_mask_bp[ + batch_indices, agent_indices, last_valid_indices + ] = 1.0 + time_start = time.time() + intent_conditioned_xpred, _ = self.diffuser.sample( + scene_tensor=scene_tensor_features.tensor, + valid_mask=scene_tensor_features.validity, + global_context=global_context, + z_t=None, + keep_mask=intent_conditioned_task_mask_bp, + raw_map=self.extract_raw_map(scene_tensor_features) + # use_guidance_fn=True, + ) + time_end = time.time() + time_consume += time_end - time_start + time_consume /= 2 + # print(f"Time consume: {time_consume}") + return dict( + behavior_prediction_out={ + "behavior_pred": xpred, + "intent_conditioned_behavior_pred": intent_conditioned_xpred, + "scene_tensor_gt": scene_tensor_features.tensor, + "valid_mask": scene_tensor_features.validity, + "task_mask": task_mask_bp, + "time_consume": time_consume, + "road_graph": scene_tensor_features.road_graph, + "road_graph_validity": scene_tensor_features.road_graph_validity, + } + ) + + def extract_raw_map(self, scene_tensor_features: SceneTensor) -> torch.Tensor: + # extract and pad map info + road_graph,road_graph_validity=scene_tensor_features.road_graph,scene_tensor_features.road_graph_validity + road_graph_validity=road_graph_validity.any(dim=-1) + B,N,P=road_graph_validity.shape + max_point_num=road_graph_validity.sum(-1).sum(-1).max() + padding=torch.ones((1,road_graph.shape[-1]),device=road_graph.device)*50 + raw_map=[] + for i in range(road_graph.shape[0]): + graph,valid=road_graph[i],road_graph_validity[i] + temp=graph[valid] + temp=torch.cat([temp,padding.expand(max_point_num-temp.shape[0],-1)],dim=0) + raw_map.append(temp) + raw_map=torch.stack(raw_map) + return raw_map + + def forward_inference( + self, + input_features: FeaturesType, + noise: torch.Tensor = None, + return_intermidates: bool = True, + ) -> Dict: + """ + Forward pass for inference + :param input_features: input features, including scene_tensor:SceneTensor and task_mask:(n_agents, n_timesteps, n_features) + :param noise: (n_agents, n_timesteps, n_features) + :return: predictions from network + """ + # Encode image + # global_context = self.image_encoder(input_features) + input_features['scene_tensor'].tensor = input_features['scene_tensor'].tensor[...,:8] # to exclude agents id from scene_tensor + scene_tensor_features: SceneTensor = input_features["scene_tensor"] + global_context = self.global_encoder(scene_tensor_features) + + if "task_mask" in input_features: + task_mask = input_features["task_mask"] + else: + return {} + + self.diffuser.model.eval() + sampled_tensor, intermidates = self.diffuser.sample( + input_features=input_features["scene_tensor"], + scene_tensor=scene_tensor_features.tensor, + valid_mask=scene_tensor_features.validity, + keep_mask=task_mask, + global_context=global_context, + z_t=noise, + return_intermidates=return_intermidates, + raw_map=self.extract_raw_map(scene_tensor_features) + ) # batch, n_agents, n_timesteps, n_features + # n_features (x, y, cos(yaw), sin(yaw), l, w) + self.diffuser.model.train() + + out = {"sampled_tensor": sampled_tensor, "task_mask": task_mask} + if return_intermidates: + out["intermidates_sampled_tensors"] = intermidates + + return out \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/post_processors/gump_naive_planner.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/post_processors/gump_naive_planner.py new file mode 100644 index 0000000..cf845f6 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/post_processors/gump_naive_planner.py @@ -0,0 +1,25 @@ +from typing import Dict, List + +import torch +import torch.nn as nn + + +class GUMPNaivePlanner(nn.Module): + """ + Naive planner that takes the predicted control logits and selects the control action with the highest probability. + """ + + def __init__(self): + super().__init__() + + def forward(self, predictions: Dict) -> Dict: + """ + Forward function of GUMPNaivePlanner. + + Args: + predictions (Dict): A dictionary of the encoder output. Must contain the 'pred_control_logits' tensor of shape (B, 3). + + Returns: + Dict: A dictionary of the post-processor output. + """ + import pdb; pdb.set_trace() \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/renders/gump_render.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/renders/gump_render.py new file mode 100644 index 0000000..8388fe5 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/renders/gump_render.py @@ -0,0 +1,28 @@ +from typing import Any, Dict, List, Tuple, Callable, Union +import torch +import torch.nn as nn +import numpy as np +import nuplan_extent.planning.training.modeling.models.tokenizers.gump_tokenizer_utils as gutils + +class GUMPRender(nn.Module): + """ + DummyPostProcessor + """ + + def __init__(self, + **kwargs): + super().__init__() + + def forward(self, tokenized_arrays: Dict, hist_tokenized_arrays = None) -> Dict: + """ + Dummy forward + """ + detokenized_arrays = gutils.detokenize_data(tokenized_arrays) + detokenized_arrays = gutils.filter_data(detokenized_arrays, eps=2.0) + return detokenized_arrays + + def update_last_frame_data(self, last_tokenized_arrays, pred_agent_tokens, return_list=None) -> Dict: + """ + Dummy forward + """ + return gutils.update_last_frame_data(last_tokenized_arrays, pred_agent_tokens, return_list) diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/tokenizers/base_tokenizer_utils.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/tokenizers/base_tokenizer_utils.py new file mode 100644 index 0000000..c4c8094 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/tokenizers/base_tokenizer_utils.py @@ -0,0 +1,417 @@ +import numpy as np +from enum import Enum +from numba.typed import Dict, List +from numba.core import types +from numba import jit + + +from enum import Enum +from numba.typed import Dict +from numba.core import types +from nuplan_extent.planning.training.preprocessing.features.tokenized_objects.state_type_v1_1 import VocabularyStateType, PositionalStateType + +class TokenType(Enum): + """ + Enum representing different types of tokens used in sequence modeling + of vehicle and pedestrian tracking data. + + Attributes: + DUMMY_TOKEN: Placeholder token for initialization or error handling. + BOS_TOKEN: Beginning of sequence token. + EGO_TOKEN: Represents the ego vehicle in the sequence. + AGENT_TOKEN: Represents other agents (vehicles, pedestrians) in the sequence. + NEWBORN_BOS_TOKEN: Special token for the beginning of a sequence for newborn agents. + NEWBORN_AGENT_TOKEN: Represents newly detected agents in the sequence. + PAD_TOKEN: Padding token used to fill sequence length. + """ + DUMMY_TOKEN = -1 + BOS_TOKEN = 0 + EGO_TOKEN = 1 + AGENT_TOKEN = 2 + NEWBORN_BOS_TOKEN = 3 + NEWBORN_AGENT_TOKEN = 4 + PAD_TOKEN = 5 + +class StatusType(Enum): + """ + Enum representing different status types of agents in traffic scenes. + + Attributes: + CONDITION: Represents conditioned agents in the scene, served as inputs. + GENERATED: Represents agents generated by the model. + """ + CONDITION = 0 + GENERATED = 1 + +class ClassType(Enum): + """ + Enum representing different class types of agents in traffic scenes. + + Attributes: + VEHICLE: Represents a vehicle. + PEDESTRIAN: Represents a pedestrian. + CYCLIST: Represents a cyclist. + """ + VEHICLE = 0 + PEDESTRIAN = 1 + CYCLIST = 2 + STATIC = 3 + + +class NpSequenceArray(np.ndarray): + """ + A numpy array subclass for handling sequences of tracking data efficiently. + + The array is structured with specific dimensions representing different data fields. + + Attributes: + dim (int): Number of dimensions in the array. + token_type (int): Index for token type in the sequence. + frame_index (int): Index for the frame identifier. + x_dim (int): Index for the X coordinate. + y_dim (int): Index for the Y coordinate. + heading_dim (int): Index for the heading. + vx_dim (int): Index for the velocity in X. + vy_dim (int): Index for the velocity in Y. + track_id_dim (int): Index for the track identifier, unique for objects. + track_token_dim (int): Index for the track token, unique for each class. + class_type_dim (int): Index for the class type of the agent. + status_dim (int): Index for the status of the agent (e.g., condition, generated). + """ + dim = 13 + token_type_dim = 0 + frame_index_dim = 1 + x_dim = 2 + y_dim = 3 + heading_dim = 4 + vx_dim = 5 + vy_dim = 6 + width_dim = 7 + length_dim = 8 + track_id_dim = 9 + track_token_dim = 10 + class_type_dim = 11 + status_dim = 12 + + def __new__(cls, input_array): + """Create a new instance of the array.""" + obj = np.asarray(input_array).view(cls) + return obj + + @property + def token_type(self): + """Array slice of token types.""" + return self[..., self.token_type_dim] + + @property + def frame_index(self): + """Array slice of frame indices.""" + return self[..., self.frame_index_dim] + + @property + def x(self): + """Array slice of X coordinates.""" + return self[..., self.x_dim] + + @property + def y(self): + """Array slice of Y coordinates.""" + return self[..., self.y_dim] + + @property + def heading(self): + """Array slice of headings.""" + return self[..., self.heading_dim] + + @property + def vx(self): + """Array slice of velocities in X.""" + return self[..., self.vx_dim] + + @property + def vy(self): + """Array slice of velocities in Y.""" + return self[..., self.vy_dim] + + @property + def width(self): + """Array slice of headings.""" + return self[..., self.width_dim] + + @property + def length(self): + """Array slice of headings.""" + return self[..., self.length_dim] + + @property + def track_id(self): + """Array slice of track IDs.""" + return self[..., self.track_id_dim] + + @property + def track_token(self): + """Array slice of track tokens.""" + return self[..., self.track_token_dim] + + @property + def class_type(self): + """Array slice of class types.""" + return self[..., self.class_type_dim] + + @property + def is_ego(self): + """Boolean array slice for ego vehicles.""" + return self[..., self.token_type_dim] == TokenType.EGO_TOKEN.value + +class NpTokenizedSequenceArray(NpSequenceArray): + dim = 19 + tokenized_x_dim = 13 + tokenized_y_dim = 14 + tokenized_heading_dim = 15 + next_tokenized_x_dim = 16 + next_tokenized_y_dim = 17 + next_tokenized_heading_dim = 18 + +# Constants for NpSequenceArray +TOKEN_TYPE_IDX = NpSequenceArray.token_type_dim +FRAME_INDEX_IDX = NpSequenceArray.frame_index_dim +X_DIM = NpSequenceArray.x_dim +Y_DIM = NpSequenceArray.y_dim +HEADING_DIM = NpSequenceArray.heading_dim +VX_DIM = NpSequenceArray.vx_dim +VY_DIM = NpSequenceArray.vy_dim +WIDTH_DIM = NpSequenceArray.width_dim +LENGTH_DIM = NpSequenceArray.length_dim +TRACK_ID_DIM = NpSequenceArray.track_id_dim +TRACK_TOKEN_DIM = NpSequenceArray.track_token_dim +CLASS_TYPE_DIM = NpSequenceArray.class_type_dim +NpSequence_DIM = NpSequenceArray.dim +STATUS_DIM = NpSequenceArray.status_dim + +BOS_TOKEN = VocabularyStateType.BOS_TOKEN.start +NEWBORN_BOS_TOKEN = VocabularyStateType.NEWBORN_BEGIN_TOKEN.start +PAD_TOKEN = VocabularyStateType.PAD_TOKEN.start + +MAX_TRACK_ID = VocabularyStateType.AGENTS.end + +@jit(nopython=True) +def normalize_angle(heading): + """ + Normalize the angle to be within the range [-pi, pi] using the arctan2 function. + + Args: + heading (float or np.ndarray): The heading angle in radians. + + Returns: + float or np.ndarray: Normalized angle between [-pi, pi]. + """ + return np.arctan2(np.sin(heading), np.cos(heading)) + +@jit(nopython=True) +def safe_add_one(index, max_index): + """ + Safely increments the index by one if it does not exceed the maximum allowed index. + + Args: + index (int): The current index to be incremented. + max_index (int): The maximum allowable index. + + Returns: + int: The incremented index if within bounds, otherwise returns the original index. + """ + if index < max_index: + return index + 1 + else: + print(f"Error: Index {index} exceeds the maximum allowable limit {max_index}.") + raise ValueError("Index exceeds the maximum allowable limit.") + return index + +@jit(nopython=True) +def convert_to_local(cur_state, next_state): + """ + Convert next_state to the coordinate system where cur_state is the origin and aligned with cur_state's orientation. + + Parameters: + cur_state (np.array): The current state coordinates and orientation (x, y, theta, w, l). + next_state (np.array): The next state coordinates and orientation (x, y, theta, w, l). + + Returns: + np.array: Transformed next_state relative to cur_state. + """ + x_c, y_c, theta_c, _, _ = cur_state + x_n, y_n, theta_n, w, l = next_state + + # Calculate relative position + dx = x_n - x_c + dy = y_n - y_c + + # Apply rotation matrix to align with cur_state's orientation + cos_theta = np.cos(-theta_c) + sin_theta = np.sin(-theta_c) + + local_x = dx * cos_theta - dy * sin_theta + local_y = dx * sin_theta + dy * cos_theta + + # Compute local orientation + local_orientation = theta_n - theta_c + + # Construct the local state + return np.array([local_x, local_y, local_orientation, w, l]) + +@jit(nopython=True) +def convert_to_global(cur_state, local_next_state): + """ + Convert local_next_state from the coordinate system where cur_state is the origin and aligned with cur_state's orientation + back to the global coordinate system. + + Parameters: + cur_state (np.array): The current state coordinates and orientation (x, y, theta, w, l). + local_next_state (np.array): The local next state coordinates and orientation relative to cur_state (x, y, theta, w, l). + + Returns: + np.array: Transformed next_state in global coordinates. + """ + # Extract position and orientation from cur_state + x_c, y_c, theta_c, w, l = cur_state + + # Extract local position and orientation + x_l, y_l, theta_l, w_l, l_l = local_next_state + + # Apply rotation matrix to convert local coordinates to global coordinates + rotation_matrix = np.array([[np.cos(theta_c), -np.sin(theta_c)], + [np.sin(theta_c), np.cos(theta_c)]]) + global_coordinates = rotation_matrix @ np.array([x_l, y_l]) + + # Calculate global position by adding translated coordinates to current position + global_x = x_c + global_coordinates[0] + global_y = y_c + global_coordinates[1] + + # Compute global orientation + global_orientation = theta_c + theta_l + + # Return new global state + return np.array([global_x, global_y, global_orientation, w_l, l_l]) + +@jit(nopython=True, fastmath=True) +def rotate_point(x, y, rad): + """Rotate a point around the origin by an angle.""" + cos_rad = np.cos(rad) + sin_rad = np.sin(rad) + return x * cos_rad - y * sin_rad, x * sin_rad + y * cos_rad + +@jit(nopython=True, fastmath=True) +def get_corners(x, y, heading, w, l): + """Compute the corners of the rectangle based on its state vector.""" + cos_h = np.cos(heading) + sin_h = np.sin(heading) + half_l = l / 2 + half_w = w / 2 + corners = np.array([ + [half_l * cos_h - half_w * sin_h, half_l * sin_h + half_w * cos_h], + [-half_l * cos_h - half_w * sin_h, -half_l * sin_h + half_w * cos_h], + [-half_l * cos_h + half_w * sin_h, -half_l * sin_h - half_w * cos_h], + [half_l * cos_h + half_w * sin_h, half_l * sin_h - half_w * cos_h] + ]) + corners += np.array([x, y]) + return corners + +@jit(nopython=True, fastmath=True) +def average_corner_distance(sa, sb): + """Calculate the average distance between corners of two rectangles.""" + corners_a = get_corners(sa[0], sa[1], sa[2], sa[3], sa[4]) + corners_b = get_corners(sb[0], sb[1], sb[2], sb[3], sb[4]) + distances = np.sqrt((corners_a[:, 0] - corners_b[:, 0])**2 + (corners_a[:, 1] - corners_b[:, 1])**2) + return distances.mean() + +@jit(nopython=True) +def project_polygon(axis, corners): + # Project all corners onto the axis and return the min and max projections + projections = np.dot(corners, axis) + return np.min(projections), np.max(projections) + +@jit(nopython=True) +def overlap(proj1, proj2): + # Check if projections on a single axis overlap + min1, max1 = proj1 + min2, max2 = proj2 + return max1 >= min2 and max2 >= min1 + +@jit(nopython=True, fastmath=True) +def check_collision(sa, sb): + """ + Check if two rectangles overlap using the Separating Axis Theorem. + + Args: + sa (np.array): The state vector of the first rectangle [x, y, heading, width, length]. + sb (np.array): The state vector of the second rectangle [x, y, heading, width, length]. + + Returns: + bool: True if there is an overlap (collision), False otherwise. + """ + x_a, y_a, heading_a, w_a, l_a = sa + x_b, y_b, heading_b, w_b, l_b = sb + + corners_a_loop = np.zeros((5, 2)) + corners_b_loop = np.zeros((5, 2)) + corners_a = get_corners(x_a, y_a, heading_a, w_a, l_a) + corners_b = get_corners(x_b, y_b, heading_b, w_b, l_b) + + # Complete the loop for corners + corners_a_loop[:4] = corners_a + corners_b_loop[:4] = corners_b + corners_a_loop[4] = corners_a[0] + corners_b_loop[4] = corners_b[0] + + # Calculate edges + edges_a = corners_a_loop[1:] - corners_a_loop[:-1] + edges_b = corners_b_loop[1:] - corners_b_loop[:-1] + + # Preallocate memory for axes + num_axes = 4 # As each rectangle has 4 sides and thus 4 potential separating axes + axes = np.zeros((num_axes * 2, 2)) # There will be 8 axes in total + + # Calculate axes + for i in range(num_axes): + axes[i, 0] = -edges_a[i, 1] + axes[i, 1] = edges_a[i, 0] + axes[num_axes + i, 0] = -edges_b[i, 1] + axes[num_axes + i, 1] = edges_b[i, 0] + + # Check for overlap on all axes + for i in range(num_axes * 2): + norm_axis = axes[i] / np.linalg.norm(axes[i]) + proj_a = project_polygon(norm_axis, corners_a) + proj_b = project_polygon(norm_axis, corners_b) + if not overlap(proj_a, proj_b): + return False # Found a separating axis + return True # No separating axis found, rectangles must overlap + +@jit(nopython=True) +def find_last_frame_index(tokenized_array): + frame_index = 0 + for i in range(tokenized_array.shape[0]): + if np.isnan(tokenized_array[i]).any(): + break + frame_index = tokenized_array[i, FRAME_INDEX_IDX] + return frame_index + +@jit(nopython=True) +def clamp(value, min_value, max_value): + """ + Manually clamp a value between min_value and max_value. + + Args: + value (float): The value to be clamped. + min_value (float): The minimum allowable value. + max_value (float): The maximum allowable value. + + Returns: + float: The clamped value. + """ + if value < min_value: + return min_value + elif value > max_value: + return max_value + else: + return value + \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/modeling/models/tokenizers/gump_tokenizer_utils.py b/projects/BWM/nuplan_extent/planning/training/modeling/models/tokenizers/gump_tokenizer_utils.py new file mode 100644 index 0000000..ad41a84 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/modeling/models/tokenizers/gump_tokenizer_utils.py @@ -0,0 +1,1301 @@ +import numpy as np +from enum import Enum +from numba.typed import Dict, List +from numba.core import types +from numba import jit, prange +import random + +from enum import Enum +from numba.typed import Dict +from numba.core import types +from nuplan_extent.planning.training.preprocessing.features.tokenized_objects.state_type_v1_1 import VocabularyStateType, PositionalStateType +from nuplan_extent.planning.training.modeling.models.tokenizers.base_tokenizer_utils import ( + safe_add_one, + normalize_angle, + average_corner_distance, + check_collision, + find_last_frame_index, + NpSequenceArray, + NpTokenizedSequenceArray, + TokenType, + ClassType, + StatusType +) +import torch +from einops import rearrange + + +X_START, X_END, X_RANGE, X_STEP = VocabularyStateType.X.start, VocabularyStateType.X.end, VocabularyStateType.X.x_range, VocabularyStateType.X.x_step +Y_START, Y_END, Y_RANGE, Y_STEP = VocabularyStateType.Y.start, VocabularyStateType.Y.end, VocabularyStateType.Y.y_range, VocabularyStateType.Y.y_step +HEADING_START, HEADING_END, HEADING_RANGE, HEADING_STEP = VocabularyStateType.HEADING.start, VocabularyStateType.HEADING.end, VocabularyStateType.HEADING.heading_range, VocabularyStateType.HEADING.heading_step +WIDTH_START, WIDTH_END, WIDTH_RANGE, WIDTH_STEP = VocabularyStateType.WIDTH.start, VocabularyStateType.WIDTH.end, VocabularyStateType.WIDTH.width_range, VocabularyStateType.WIDTH.width_step +LENGTH_START, LENGTH_END, LENGTH_RANGE, LENGTH_STEP = VocabularyStateType.LENGTH.start, VocabularyStateType.LENGTH.end, VocabularyStateType.LENGTH.length_range, VocabularyStateType.LENGTH.length_step +CLASS_TYPE_START, CLASS_TYPE_END = VocabularyStateType.CLASS_TYPE.start, VocabularyStateType.CLASS_TYPE.end +BOS_TOKEN_VALUE, NEWBORN_BOS_TOKEN_VALUE, PAD_TOKEN_VALUE = VocabularyStateType.BOS_TOKEN.start, VocabularyStateType.NEWBORN_BEGIN_TOKEN.start, VocabularyStateType.PAD_TOKEN.start + +# Constants for NpSequenceArray +TOKEN_TYPE_IDX = NpSequenceArray.token_type_dim +FRAME_INDEX_IDX = NpSequenceArray.frame_index_dim +X_DIM = NpSequenceArray.x_dim +Y_DIM = NpSequenceArray.y_dim +HEADING_DIM = NpSequenceArray.heading_dim +VX_DIM = NpSequenceArray.vx_dim +VY_DIM = NpSequenceArray.vy_dim +WIDTH_DIM = NpSequenceArray.width_dim +LENGTH_DIM = NpSequenceArray.length_dim +TRACK_ID_DIM = NpSequenceArray.track_id_dim +TRACK_TOKEN_DIM = NpSequenceArray.track_token_dim +CLASS_TYPE_DIM = NpSequenceArray.class_type_dim +NpSequence_DIM = NpSequenceArray.dim +STATUS_DIM = NpSequenceArray.status_dim + +# Constants for NpTokenizedSequenceArray +NpTokenizedSequence_DIM = NpTokenizedSequenceArray.dim +TOKENIZED_X_DIM = NpTokenizedSequenceArray.tokenized_x_dim +TOKENIZED_Y_DIM = NpTokenizedSequenceArray.tokenized_y_dim +TOKENIZED_HEADING_DIM = NpTokenizedSequenceArray.tokenized_heading_dim +NEXT_TOKENIZED_X_DIM = NpTokenizedSequenceArray.next_tokenized_x_dim +NEXT_TOKENIZED_Y_DIM = NpTokenizedSequenceArray.next_tokenized_y_dim +NEXT_TOKENIZED_HEADING_DIM = NpTokenizedSequenceArray.next_tokenized_heading_dim + +BOS_TOKEN = VocabularyStateType.BOS_TOKEN.start +NEWBORN_BOS_TOKEN = VocabularyStateType.NEWBORN_BEGIN_TOKEN.start +PAD_TOKEN = VocabularyStateType.PAD_TOKEN.start + +MAX_TRACK_ID = VocabularyStateType.AGENTS.end + +# constant for ego width and length +ego_width, ego_length = 2.297, 5.176 # hard code for nuplan + + +@jit(nopython=True) +def get_bos_array(frame_index): + """ + Create a beginning of sequence (BOS) array with specified frame index. + + Args: + frame_index (int): The index of the frame for which to create the BOS token. + + Returns: + np.ndarray: A numpy array representing the BOS token with the frame index. + """ + bos_array = np.zeros((NpSequence_DIM,)) + bos_array[TOKEN_TYPE_IDX] = TokenType.BOS_TOKEN.value + bos_array[FRAME_INDEX_IDX] = frame_index + return bos_array + +@jit(nopython=True) +def get_newborn_bos_array(frame_index): + """ + Create a beginning of sequence array for newborn agents with a specified frame index. + + Args: + frame_index (int): The index of the frame for which to create the newborn BOS token. + + Returns: + np.ndarray: A numpy array representing the newborn BOS token with the frame index. + """ + newborn_bos_array = np.zeros((NpSequence_DIM,)) + newborn_bos_array[TOKEN_TYPE_IDX] = TokenType.NEWBORN_BOS_TOKEN.value + newborn_bos_array[FRAME_INDEX_IDX] = frame_index + return newborn_bos_array + +@jit(nopython=True) +def pad_array(arr): + """ + Create a beginning of sequence (BOS) array with specified frame index. + + Args: + frame_index (int): The index of the frame for which to create the BOS token. + + Returns: + np.ndarray: A numpy array representing the BOS token with the frame index. + """ + bos_array = np.zeros((19,)) - 1 + bos_array[:arr.shape[0]] = arr + return bos_array + + +@jit(nopython=True) +def get_ego_array(frame_index, current_ego_array, track_id): + """ + Generate an array representing the ego vehicle's state at a specific frame. + + Args: + frame_index (int): The index of the current frame. + current_ego_array (np.ndarray): Array containing the ego's state data. + track_id (int): The track identifier for the ego vehicle. + + Returns: + np.ndarray: A numpy array representing the ego's state in the sequence. + """ + x, y, heading, vx, vy, ax, ay = current_ego_array + ego_array = np.zeros((NpSequence_DIM, )) + ego_array[TOKEN_TYPE_IDX] = TokenType.EGO_TOKEN.value + ego_array[FRAME_INDEX_IDX] = frame_index + ego_array[X_DIM] = x + ego_array[Y_DIM] = y + ego_array[HEADING_DIM] = normalize_angle(heading) + ego_array[VX_DIM] = vx + ego_array[VY_DIM] = vy + ego_array[WIDTH_DIM] = ego_width + ego_array[LENGTH_DIM] = ego_length + ego_array[CLASS_TYPE_DIM] = ClassType.VEHICLE.value + ego_array[TRACK_TOKEN_DIM] = -1 + ego_array[TRACK_ID_DIM] = track_id + return ego_array + + +@jit(nopython=True) +def get_agent_array(frame_index, current_agent_array, track_id, is_newborn, class_index): + """ + Generate an array representing an agent's state in a specific frame. + + Args: + frame_index (int): The index of the current frame. + current_agent_array (np.ndarray): Array containing the agent's state data. + track_id (int): The track identifier for the agent. + is_newborn (bool): Indicator if the agent is newly detected in this frame. + class_index (int): Class type index of the agent (e.g., vehicle, pedestrian). + + Returns: + np.ndarray: A numpy array representing the agent's state in the sequence. + """ + track_token, vx, vy, heading, width, length, x, y = current_agent_array + agent_array = np.zeros((NpSequence_DIM, )) + agent_array[TOKEN_TYPE_IDX] = TokenType.NEWBORN_AGENT_TOKEN.value if is_newborn else TokenType.AGENT_TOKEN.value + agent_array[FRAME_INDEX_IDX] = frame_index + agent_array[X_DIM] = x + agent_array[Y_DIM] = y + agent_array[HEADING_DIM] = normalize_angle(heading) + agent_array[VX_DIM] = vx + agent_array[VY_DIM] = vy + agent_array[WIDTH_DIM] = width + agent_array[LENGTH_DIM] = length + agent_array[CLASS_TYPE_DIM] = class_index + agent_array[TRACK_ID_DIM] = track_id + agent_array[TRACK_TOKEN_DIM] = track_token + return agent_array + + +@jit(nopython=True) +def get_hash(class_index, track_token): + """ + Generates a hash value based on class index and track token for unique identification. + + Args: + class_index (int): Class type index (e.g., vehicle, pedestrian). + track_token (int): Unique track token assigned to an agent. + + Returns: + int: A 64-bit integer hash value combining class index and track token. + """ + # Combining the class index and track token to generate a unique hash. + hash_value = int(class_index) << 32 | int(track_token) + return hash_value + + +@jit(nopython=True) +def get_track_id(class_index, current_agent_array, track_id_mapping): + """ + Determine the track ID for an agent, assigning a new ID if the agent is newly detected. + + Args: + class_index (int): The class index of the agent. + current_agent_array (np.ndarray): Current state array of the agent. + track_id_mapping (Dict): Mapping from hashed values to track IDs. + + Returns: + tuple: A tuple containing the track ID, newborn status, and updated track ID mapping. + """ + track_token, vx, vy, heading, width, length, x, y = current_agent_array + key = get_hash(class_index, track_token) + track_ids = track_id_mapping.values() + if key in track_id_mapping: + is_newborn = False + track_id = track_id_mapping[key] + else: + is_newborn = True + if len(track_ids) == 0: + track_id = 1 + else: + track_id = max(track_ids) + 1 + track_id_mapping[key] = track_id + return track_id, is_newborn, track_id_mapping + + +@jit(nopython=True) +def reorgnize_array(tokenized_arrays, T=21, block_size=1024): + B, max_len, dim = tokenized_arrays.shape + + orgnized_arrays = np.full((B, T, block_size, dim), np.nan) + mask = np.zeros((B, T, block_size)) + max_index = 0 + + embed_seq_index = 0 + for i in range(B): + max_token = 0 + for j in range(max_len): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value, TokenType.AGENT_TOKEN.value]: + time = int(current_token[FRAME_INDEX_IDX]) + index = int(current_token[TRACK_ID_DIM]) + max_index = max(index, max_index) + if index < block_size: + orgnized_arrays[i,time,index,:] = current_token + mask[i,time,index] = 1 + return orgnized_arrays, mask + +@jit(nopython=True) +def reformat_array(last_tokenized_arrays, tokenized_arrays,T=21): + new_pad_tokenized_arrays = np.full(tokenized_arrays.shape, np.nan) + + for i in range(last_tokenized_arrays.shape[0]): + index = 0 + for j in range(last_tokenized_arrays.shape[1]): + current_token = last_tokenized_arrays[i,j] + if np.isnan(current_token).any(): + continue + + frame_id = current_token[FRAME_INDEX_IDX] + track_id = current_token[TRACK_ID_DIM] + + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value]: + new_pad_tokenized_arrays[i,index] = pad_array(get_bos_array(frame_id)) + index = safe_add_one(index, tokenized_arrays.shape[1]) + new_pad_tokenized_arrays[i,index] = current_token + index = safe_add_one(index, tokenized_arrays.shape[1]) + if current_token[TOKEN_TYPE_IDX] in [TokenType.NEWBORN_AGENT_TOKEN.value, TokenType.AGENT_TOKEN.value]: + new_pad_tokenized_arrays[i,index] = current_token + index = safe_add_one(index, tokenized_arrays.shape[1]) + + return new_pad_tokenized_arrays + +@jit(nopython=True) +def get_feature_data(tokenized_arrays): + + state_index = [int(X_DIM), int(Y_DIM), int(HEADING_DIM), int(WIDTH_DIM), int(LENGTH_DIM), int(VX_DIM), int(VY_DIM)] + tokenized_index = [int(TOKENIZED_X_DIM), int(TOKENIZED_Y_DIM), int(TOKENIZED_HEADING_DIM)] + + state_embedding_features = np.zeros((tokenized_arrays.shape[0], tokenized_arrays.shape[1], tokenized_arrays.shape[2], 7), dtype=np.float64) + tokenized_embedding_features = np.zeros((tokenized_arrays.shape[0], tokenized_arrays.shape[1], tokenized_arrays.shape[2], 3), dtype=np.int64) + + for i in range(tokenized_arrays.shape[0]): + for j in range(tokenized_arrays.shape[1]): + for k in range(tokenized_arrays.shape[2]): + current_token = tokenized_arrays[i,j,k] + if np.isnan(current_token).any(): + continue + + track_id = current_token[TRACK_ID_DIM] + class_index = current_token[CLASS_TYPE_DIM] + vx, vy = current_token[VX_DIM], current_token[VY_DIM] + x, y, heading = current_token[X_DIM], current_token[Y_DIM], current_token[HEADING_DIM] + w, l = current_token[WIDTH_DIM], current_token[LENGTH_DIM] + tx, ty, tz = int(current_token[TOKENIZED_X_DIM]), int(current_token[TOKENIZED_Y_DIM]), int(current_token[TOKENIZED_HEADING_DIM]) + + state_embedding_features[i,j,k] = np.array([x, y, heading, w, l, vx, vy]) + tokenized_embedding_features[i,j,k] = np.array([tx, ty, tz]) + + return state_embedding_features, tokenized_embedding_features + +@jit(nopython=True) +def process_single_batch(agents_array, ego_array, max_seq_len=10240): + """ + Process a single batch of agent and ego arrays to create a tokenized sequence. + + Args: + agents_array (List[np.ndarray]): List of agent arrays for each class type and frame. + ego_array (np.ndarray): Array containing ego vehicle data across frames. + max_seq_len (int): Maximum length of the sequence to be processed. + + Returns: + np.ndarray: Tokenized information array for the batch. + """ + tokenized_info_array = np.nan * np.ones((max_seq_len, NpSequence_DIM)) + total_num_frames = ego_array.shape[0] + seq_index = 0 + track_id_mapping = Dict.empty( + key_type=types.int64, + value_type=types.int64 + ) + for frame_index in range(total_num_frames): + # Handling beginning of sequence + tokenized_info_array[seq_index] = get_bos_array(frame_index) + seq_index = safe_add_one(seq_index, max_seq_len) + + # Processing the ego vehicle + current_ego_array = ego_array[frame_index] + tokenized_info_array[seq_index] = get_ego_array(frame_index, current_ego_array, track_id=0) + seq_index = safe_add_one(seq_index, max_seq_len) + + # Cache for newborn agents to be processed at end of frame + stashed_newborn_agents_array = [] + + # Process each agent for the current frame + for class_index, agents in enumerate(agents_array): + current_agents_array = agents[frame_index] + for current_agent_array in current_agents_array: + if np.isnan(current_agent_array).any(): + continue + track_id, is_newborn, track_id_mapping = get_track_id(class_index, current_agent_array, track_id_mapping) + if track_id > MAX_TRACK_ID: + print("Error: Track ID exceeds the maximum allowable limit.") + continue + # Newborn agents are processed after all existing agents + if frame_index > 0 and is_newborn: + stashed_newborn_agents_array.append(get_agent_array(frame_index, current_agent_array, track_id=track_id, is_newborn=is_newborn, class_index=class_index)) + else: + tokenized_info_array[seq_index] = get_agent_array(frame_index, current_agent_array, track_id=track_id, is_newborn=False, class_index=class_index) + seq_index = safe_add_one(seq_index, max_seq_len) + # Handle the beginning of sequence for newborn agents + tokenized_info_array[seq_index] = get_newborn_bos_array(frame_index) + seq_index = safe_add_one(seq_index, max_seq_len) + + + # Append newborn agents to the sequence + for stashed_newborn_agent_array in stashed_newborn_agents_array: + tokenized_info_array[seq_index] = stashed_newborn_agent_array + seq_index = safe_add_one(seq_index, max_seq_len) + return tokenized_info_array + + +@jit(nopython=True) +def within_valid_range(data, valid_range): + """ + Check if the given data points (x, y) are within the specified valid range. + + Args: + data (np.ndarray): The data array containing x and y coordinates. + valid_range (np.ndarray): An array specifying the valid [xmin, xmax, ymin, ymax] range. + + Returns: + bool: True if the data is within the valid range, False otherwise. + """ + # Checking if the data's coordinates are within the provided range + if data[X_DIM] > valid_range[0] and data[X_DIM] < valid_range[1] and \ + data[Y_DIM] > valid_range[2] and data[Y_DIM] < valid_range[3]: + return True + return False + +@jit(nopython=True) +def tokenize_data(data): + """ + Convert data points into tokens based on specified ranges and steps. + + Args: + data (np.ndarray): The data array to be tokenized. + + Returns: + np.ndarray: The data array with tokenized values. + """ + def calculate_token(value, value_range, start, step): + # Clamping the value within the range and calculating the token + value = np.maximum(value_range[0], np.minimum(value_range[1], value)) + return start + int(round((value - value_range[0]) / step)) + + # Tokenizing data only for specific token types + if int(data[TOKEN_TYPE_IDX]) in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + x, y, heading = data[X_DIM], data[Y_DIM], data[HEADING_DIM] + x_token = calculate_token(x, X_RANGE, X_START, X_STEP) + y_token = calculate_token(y, Y_RANGE, Y_START, Y_STEP) + heading_token = calculate_token(heading, HEADING_RANGE, HEADING_START, HEADING_STEP) + data[TOKENIZED_X_DIM] = x_token + data[TOKENIZED_Y_DIM] = y_token + data[TOKENIZED_HEADING_DIM] = heading_token + else: + # Setting tokens to -1 if data type does not match + data[TOKENIZED_X_DIM] = -1 + data[TOKENIZED_Y_DIM] = -1 + data[TOKENIZED_HEADING_DIM] = -1 + return data + +@jit(nopython=True) +def tokenize_single_batch(processed_single_batch, max_seq_len=4096, valid_range=np.array([-100, 100, -100, 100])): + """ + Tokenize a batch of data by filtering out entries outside of a valid range and tokenizing the valid entries. + + Args: + processed_single_batch (np.ndarray): Processed batch data to be tokenized. + max_seq_len (int): Maximum sequence length for the output tokenized data. + valid_range (np.ndarray): Array specifying the valid [xmin, xmax, ymin, ymax] range. + + Returns: + np.ndarray: The tokenized data array. + """ + tokenized_data = np.nan * np.ones((max_seq_len, NpTokenizedSequence_DIM)) + seq_idx = 0 + for i in range(len(processed_single_batch)): + data = processed_single_batch[i] + if np.isnan(data).any() or not within_valid_range(data, valid_range): + continue + tokenized_data[seq_idx, :data.shape[0]] = data + tokenized_data[seq_idx] = tokenize_data(tokenized_data[seq_idx]) + seq_idx = safe_add_one(seq_idx, max_seq_len) + + # Setting next tokenized values for sequences + for i in range(len(processed_single_batch)): + data = tokenized_data[i] + if np.isnan(data).all(): + continue + for j in range(i+1, len(processed_single_batch)): + next_data = tokenized_data[j] + if next_data[TRACK_ID_DIM] == data[TRACK_ID_DIM] and next_data[FRAME_INDEX_IDX] == data[FRAME_INDEX_IDX] + 1: + data[NEXT_TOKENIZED_X_DIM] = next_data[TOKENIZED_X_DIM] + data[NEXT_TOKENIZED_Y_DIM] = next_data[TOKENIZED_Y_DIM] + data[NEXT_TOKENIZED_HEADING_DIM] = next_data[TOKENIZED_HEADING_DIM] + break + tokenized_data[i] = np.nan_to_num(data, -1) + return tokenized_data + +def run_function_multiple_times(num_runs, agents_array, ego_array): + for _ in range(1): + process_single_batch(agents_array, ego_array) + start_time = time.time() + for _ in range(num_runs): + tokenized_info_array = process_single_batch(agents_array, ego_array) + end_time = time.time() + print("Total time for {} runs: {:.2f} seconds".format(num_runs, end_time - start_time)) + return tokenized_info_array + + +@jit(nopython=True) +def get_frame_index(tokenized_arrays, block_size=1024, max_frames=1000): + """ + Get the frame index for the tokenized arrays. + + Args: + tokenized_arrays (numpy.ndarray): The tokenized arrays. + block_size (int, optional): The maximum block size. Defaults to 1024. + + Returns: + list: A list of frame indices. + """ + batch_size, seq_len, _ = tokenized_arrays.shape + frame_indices = (max_frames-1) * np.ones((batch_size, block_size,), dtype=np.int64) + for i in range(tokenized_arrays.shape[0]): + embed_seq_index = 0 + for j in range(tokenized_arrays.shape[1]): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + continue + if embed_seq_index >= block_size: + break + token_type = current_token[TOKEN_TYPE_IDX] + frame_index = current_token[FRAME_INDEX_IDX] + if token_type in [TokenType.BOS_TOKEN.value, TokenType.NEWBORN_BOS_TOKEN.value, TokenType.PAD_TOKEN.value]: + frame_indices[i, embed_seq_index] = frame_index + embed_seq_index = safe_add_one(embed_seq_index, frame_indices.shape[1]) + elif token_type in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + frame_indices[i, embed_seq_index] = frame_index + embed_seq_index = safe_add_one(embed_seq_index, frame_indices.shape[1]) + if embed_seq_index >= block_size: + break + frame_indices[i, embed_seq_index] = frame_index + embed_seq_index = safe_add_one(embed_seq_index, frame_indices.shape[1]) + else: + print('invalid type:', token_type) + return frame_indices + +@jit(nopython=True) +def get_frame_tuple(tokenized_arrays, block_size=1024, max_frames=1000): + + batch_size, T, seq_len, _ = tokenized_arrays.shape + frame_indices = (max_frames-1) * np.ones((batch_size, T, block_size,), dtype=np.int64) + for i in range(tokenized_arrays.shape[0]): + for j in range(tokenized_arrays.shape[1]): + for m in range(tokenized_arrays.shape[2]): + current_token = tokenized_arrays[i, j, m] + if np.isnan(current_token).any(): + continue + frame_index = current_token[FRAME_INDEX_IDX] + frame_indices[i, j, m] = frame_index + + return frame_indices + + +@jit(nopython=True) +def crop_array_by_mask(pred_agent_logits, pred_agent_tokens, target_tokenized_state, mask): + pred_agent_logits = rearrange(pred_agent_logits, "B T seq dim log -> (B T seq) dim log") + pred_agent_tokens = rearrange(pred_agent_tokens, "B T seq dim -> (B T seq) dim") + target_tokenized_state = rearrange(target_tokenized_state, "B T seq dim -> (B T seq) dim") + mask = rearrange(mask, "B T seq -> (B T seq)") + index = mask==1 + return pred_agent_logits[index], pred_agent_tokens[index], target_tokenized_state[index] + + +@jit(nopython=True) +def get_tokenized_inds(tokenized_arrays, block_size=1024): + """ + Get the tokenized indices and features for control, query, and state embeddings. + + Args: + tokenized_arrays (numpy.ndarray): The tokenized arrays. + block_size (int, optional): The maximum block size. Defaults to 1024. + + Returns: + tuple: A tuple containing the following numpy arrays: + - ctrl_embedding_inds: The indices for control embeddings. + - ctrl_embedding_features: The features for control embeddings. + - query_embedding_inds: The indices for query embeddings. + - query_embedding_features: The features for query embeddings. + - state_embedding_inds: The indices for state embeddings. + - state_embedding_features: The features for state embeddings. + """ + max_inds = tokenized_arrays.shape[0] * block_size + ctrl_embedding_inds = np.full((max_inds, 2), -1, dtype=np.int64) + ctrl_embedding_features = np.full(max_inds, -1, dtype=np.int64) + query_embedding_inds = np.full((max_inds, 2), -1, dtype=np.int64) + query_embedding_features = np.full((max_inds, 2), -1, dtype=np.int64) # Assuming two features (class_index, track_id) + state_embedding_inds = np.full((max_inds, 2), -1, dtype=np.int64) + state_embedding_features = np.full((max_inds, 7), -1, dtype=np.float64) # Assuming 7 features (x, y, heading, w, l, vx, vy) + tokenized_embedding_features = np.full((max_inds, 3), -1, dtype=np.int64) + + ctrl_index = 0 + query_index = 0 + state_index = 0 + + for i in range(tokenized_arrays.shape[0]): + embed_seq_index = 0 + for j in range(tokenized_arrays.shape[1]): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + continue + if embed_seq_index >= block_size: + break + token_type = current_token[TOKEN_TYPE_IDX] + + if token_type == TokenType.BOS_TOKEN.value: + ctrl_embedding_inds[ctrl_index] = (i, embed_seq_index) + ctrl_embedding_features[ctrl_index] = BOS_TOKEN + ctrl_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + elif token_type == TokenType.NEWBORN_BOS_TOKEN.value: + ctrl_embedding_inds[ctrl_index] = (i, embed_seq_index) + ctrl_embedding_features[ctrl_index] = NEWBORN_BOS_TOKEN + ctrl_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + elif token_type == TokenType.PAD_TOKEN.value: + ctrl_embedding_inds[ctrl_index] = (i, embed_seq_index) + ctrl_embedding_features[ctrl_index] = PAD_TOKEN + ctrl_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + elif token_type in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + track_id = current_token[TRACK_ID_DIM] + class_index = current_token[CLASS_TYPE_DIM] + vx, vy = current_token[VX_DIM], current_token[VY_DIM] + x, y, heading = current_token[X_DIM], current_token[Y_DIM], current_token[HEADING_DIM] + w, l = current_token[WIDTH_DIM], current_token[LENGTH_DIM] + tx, ty, tz = current_token[TOKENIZED_X_DIM], current_token[TOKENIZED_Y_DIM], current_token[TOKENIZED_HEADING_DIM] + + query_embedding_inds[query_index] = (i, embed_seq_index) + query_embedding_features[query_index] = (class_index + CLASS_TYPE_START, track_id) + query_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + + if embed_seq_index >= block_size: + break + + state_embedding_inds[state_index] = (i, embed_seq_index) + state_embedding_features[state_index] = (x, y, heading, w, l, vx, vy) + tokenized_embedding_features[state_index] = (tx, ty, tz) + state_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + + # Trim arrays to the size actually used + ctrl_embedding_inds = ctrl_embedding_inds[:ctrl_index] + ctrl_embedding_features = ctrl_embedding_features[:ctrl_index] + query_embedding_inds = query_embedding_inds[:query_index] + query_embedding_features = query_embedding_features[:query_index] + state_embedding_inds = state_embedding_inds[:state_index] + state_embedding_features = state_embedding_features[:state_index] + tokenized_embedding_features = tokenized_embedding_features[:state_index] + + return ctrl_embedding_inds, ctrl_embedding_features, query_embedding_inds, query_embedding_features, state_embedding_inds, state_embedding_features, tokenized_embedding_features + +# @jit(nopython=True) +def get_agent_target_inds(tokenized_arrays, block_size=1024, last_frame_only=False, return_list=False): + """ + Retrieves the indices of agent target embeddings and state embedding features from tokenized arrays. + + Args: + tokenized_arrays (numpy.ndarray): The tokenized arrays containing the tokens. + block_size (int, optional): The maximum number of tokens to consider. Defaults to 1024. + + Returns: + tuple: A tuple containing two numpy arrays: + - query_embedding_inds (numpy.ndarray): The indices of agent target embeddings. + - state_embedding_features (numpy.ndarray): The state embedding features. + + """ + max_inds = tokenized_arrays.shape[0] * block_size + query_embedding_inds = np.full((max_inds, 2), -1, dtype=np.int64) + state_embedding_features = np.full((max_inds, 3), -1, dtype=np.float64) # Assuming features for x, y, and heading + + query_index = 0 + state_index = 0 + index_list = [] + + for i in range(tokenized_arrays.shape[0]): + inbatch_list = [] + embed_seq_index = 0 + if last_frame_only: + last_frame_index = find_last_frame_index(tokenized_arrays[i]) + for j in range(tokenized_arrays.shape[1]): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + continue + if embed_seq_index >= block_size: + break + token_type = current_token[TOKEN_TYPE_IDX] + if token_type in [TokenType.BOS_TOKEN.value, TokenType.NEWBORN_BOS_TOKEN.value, TokenType.PAD_TOKEN.value]: + embed_seq_index = safe_add_one(embed_seq_index, block_size) # Advance the sequence index for control tokens + inbatch_list.append(embed_seq_index) + elif token_type in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + track_id = current_token[TRACK_ID_DIM] + class_index = current_token[CLASS_TYPE_DIM] + token_x, token_y, token_heading = current_token[TOKENIZED_X_DIM], current_token[TOKENIZED_Y_DIM], current_token[TOKENIZED_HEADING_DIM] + + if last_frame_only and current_token[FRAME_INDEX_IDX] != last_frame_index: + pass + else: + query_embedding_inds[query_index] = (i, embed_seq_index) + query_index += 1 + + state_embedding_features[state_index] = (token_x, token_y, token_heading) + state_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + inbatch_list.append(embed_seq_index) + if embed_seq_index >= block_size: + break + embed_seq_index = safe_add_one(embed_seq_index, block_size) + inbatch_list.append(embed_seq_index) + else: + print('invalid type:', token_type) + index_list.append(inbatch_list) + query_embedding_inds = query_embedding_inds[:query_index] + state_embedding_features = state_embedding_features[:state_index] + if return_list: + return query_embedding_inds, state_embedding_features, index_list + return query_embedding_inds, state_embedding_features + +@jit(nopython=True) +def get_ctrl_target_inds(tokenized_arrays, block_size=1024): + + token_type_to_tokenized = { + 0: BOS_TOKEN_VALUE, + 3: NEWBORN_BOS_TOKEN_VALUE, + 5: PAD_TOKEN_VALUE, + } + + max_inds = tokenized_arrays.shape[0] * block_size + ctrl_inds = np.full((max_inds, 2), -1, dtype=np.int64) + target_ctrl_states = np.full(max_inds, -1, dtype=np.int64) + ctrl_index = 0 + target_ctrl_index = 0 + + for i in range(tokenized_arrays.shape[0]): + embed_seq_index = 0 + for j in range(tokenized_arrays.shape[1]): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + continue + if embed_seq_index >= block_size: + break + token_type = current_token[TOKEN_TYPE_IDX] + if token_type in [TokenType.BOS_TOKEN.value, TokenType.NEWBORN_BOS_TOKEN.value, TokenType.PAD_TOKEN.value]: + if embed_seq_index > 0: + ctrl_inds[ctrl_index] = (i, embed_seq_index - 1) + target_ctrl_states[target_ctrl_index] = token_type_to_tokenized[int(token_type)] + ctrl_index += 1 + target_ctrl_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) # Advance the sequence index for control tokens + elif token_type in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + if embed_seq_index > 0: + ctrl_inds[ctrl_index] = (i, embed_seq_index - 1) + target_ctrl_states[target_ctrl_index] = int(current_token[TRACK_ID_DIM]) + ctrl_index += 1 + target_ctrl_index += 1 + embed_seq_index = safe_add_one(embed_seq_index, block_size) + if embed_seq_index >= block_size: + break + embed_seq_index = safe_add_one(embed_seq_index, block_size) + else: + print('invalid type:', token_type) + return ctrl_inds[:ctrl_index], target_ctrl_states[:target_ctrl_index] + +@jit(nopython=True) +def extract_history_data(hist_tokenized_arrays, num_conditioned_frames): + """ + Delete future data from the given hist_tokenized_arrays. + + Args: + hist_tokenized_arrays (numpy.ndarray): The input array containing tokenized historical data. + num_conditioned_frames (int): The number of frames to condition on. + + Returns: + numpy.ndarray: The modified hist_tokenized_arrays with future data deleted. + """ + for i in range(hist_tokenized_arrays.shape[0]): + start_frame_index = hist_tokenized_arrays[i, 0, FRAME_INDEX_IDX] + for j in range(hist_tokenized_arrays.shape[1]): + current_token = hist_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + continue + frame_index = current_token[FRAME_INDEX_IDX] + if (frame_index - start_frame_index) >= num_conditioned_frames: + hist_tokenized_arrays[i, j, :] = np.nan + return hist_tokenized_arrays + +@jit(nopython=True) +def extract_last_frame_data(hist_tokenized_arrays, last_num_frame=1, skip_nb_bos=True): + """ + Extracts the last frame data from the given tokenized arrays. + + Args: + hist_tokenized_arrays (ndarray): The input tokenized arrays. + + Returns: + ndarray: The last frame arrays with the same shape as the input arrays. + + Notes: + - Only the data from the last frame is kept. + - The last frame index is incremented by 1 for each token in the last frame. + """ + last_frame_arrays = np.nan * np.ones_like(hist_tokenized_arrays) + for i in range(hist_tokenized_arrays.shape[0]): + last_frame_index = 0 + for j in range(hist_tokenized_arrays.shape[1]): + current_token = hist_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + last_frame_index = current_token[FRAME_INDEX_IDX] + last_frame_index = last_frame_index - last_num_frame + 1 + last_frame_seq_index = 0 + for j in range(hist_tokenized_arrays.shape[1]): + current_token = hist_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + if current_token[FRAME_INDEX_IDX] >= last_frame_index: + + # skip the newborn bos token, since we do not predict new born agents here + if skip_nb_bos and current_token[TOKEN_TYPE_IDX] in [TokenType.NEWBORN_BOS_TOKEN.value]: + continue + # update the token type to agent token, since we do not predict new born agents here + if skip_nb_bos and current_token[TOKEN_TYPE_IDX] in [TokenType.NEWBORN_AGENT_TOKEN.value]: + current_token[TOKEN_TYPE_IDX] = TokenType.AGENT_TOKEN.value + last_frame_arrays[i, last_frame_seq_index] = current_token + last_frame_seq_index = safe_add_one(last_frame_seq_index, last_frame_arrays.shape[1]) + return last_frame_arrays + + +@jit(nopython=True) +def extract_sceanrio_data(tokenized_arrays, skip_nb_bos=True, mask_future=True): + """ + Extracts the last frame data from the given tokenized arrays. + + Args: + hist_tokenized_arrays (ndarray): The input tokenized arrays. + + Returns: + ndarray: The last frame arrays with the same shape as the input arrays. + + Notes: + - Only the data from the last frame is kept. + - The last frame index is incremented by 1 for each token in the last frame. + """ + hist_tokenized_arrays = tokenized_arrays + last_frame_arrays = np.nan * np.ones_like(hist_tokenized_arrays) + for i in range(hist_tokenized_arrays.shape[0]): + last_frame_seq_index = 0 + for j in range(hist_tokenized_arrays.shape[1]): + current_token = hist_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + # skip the newborn bos token, since we do not predict new born agents here + if skip_nb_bos and current_token[TOKEN_TYPE_IDX] in [TokenType.NEWBORN_BOS_TOKEN.value]: + continue + # update the token type to agent token, since we do not predict new born agents here + if skip_nb_bos and current_token[TOKEN_TYPE_IDX] in [TokenType.NEWBORN_AGENT_TOKEN.value]: + current_token[TOKEN_TYPE_IDX] = TokenType.AGENT_TOKEN.value + if current_token[FRAME_INDEX_IDX] >= 4 and mask_future: + current_token[TOKENIZED_X_DIM] = 1000 + current_token[TOKENIZED_Y_DIM] = 2000 + current_token[TOKENIZED_HEADING_DIM] = 2500 + last_frame_arrays[i, last_frame_seq_index] = current_token + last_frame_seq_index = safe_add_one(last_frame_seq_index, last_frame_arrays.shape[1]) + return last_frame_arrays + +@jit(nopython=True) +def extract_first_frame_data(hist_tokenized_arrays, first_num_frame=1): + """ + Extracts the first num frame data from the given tokenized arrays. + + Args: + hist_tokenized_arrays (ndarray): The input tokenized arrays. + + Returns: + ndarray: The first frame arrays with the same shape as the input arrays. + + Notes: + - Only the data from the last frame is kept. + - The last frame index is incremented by 1 for each token in the last frame. + """ + first_frame_arrays = np.nan * np.ones_like(hist_tokenized_arrays) + for i in range(hist_tokenized_arrays.shape[0]): + first_frame_seq_index = 0 + first_frame_index = hist_tokenized_arrays[i, 0, FRAME_INDEX_IDX] + for j in range(hist_tokenized_arrays.shape[1]): + current_token = hist_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + if current_token[FRAME_INDEX_IDX] < first_frame_index + first_num_frame: + first_frame_arrays[i, first_frame_seq_index] = current_token + first_frame_seq_index = safe_add_one(first_frame_seq_index, first_frame_arrays.shape[1]) + return first_frame_arrays + + +# @jit(nopython=True) +def update_last_frame_data(last_tokenized_arrays, pred_agent_tokens, return_list=None, block_size=2048): + """ + update last frame data with predicted agent tokens + :param last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :param pred_agent_tokens: np.ndarray, shape (num_agents, [x, y, heading] tokens) + :return updated_last_frame_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + embed_seq_index = 0 + for i in range(len(last_tokenized_arrays)): + max_token = 0 + for j in range(len(last_tokenized_arrays[i])): + current_token = last_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] in [TokenType.BOS_TOKEN.value]: + max_token += 1 + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value, TokenType.AGENT_TOKEN.value]: + last_tokenized_arrays[i, j, TOKENIZED_X_DIM] = pred_agent_tokens[embed_seq_index, 0] + last_tokenized_arrays[i, j, TOKENIZED_Y_DIM] = pred_agent_tokens[embed_seq_index, 1] + last_tokenized_arrays[i, j, TOKENIZED_HEADING_DIM] = pred_agent_tokens[embed_seq_index, 2] + max_token += 2 + embed_seq_index = safe_add_one(embed_seq_index, pred_agent_tokens.shape[0]) + if return_list is not None: + if max_token >= len(return_list[i]): + break + assert embed_seq_index == len(pred_agent_tokens), f"Number of predicted agent tokens {embed_seq_index} does not match the number of agent tokens {pred_agent_tokens.shape} in the last frame" + return last_tokenized_arrays + + +# @jit(nopython=True) +def update_frame_data(last_tokenized_arrays, pred_agent_tokens, return_list=None, block_size=2048): + """ + update last frame data with predicted agent tokens + :param last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :param pred_agent_tokens: np.ndarray, shape (num_agents, [x, y, heading] tokens) + :return updated_last_frame_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + embed_seq_index = 0 + for i in range(len(last_tokenized_arrays)): + for j in range(len(last_tokenized_arrays[i])): + current_token = last_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + continue + last_tokenized_arrays[i, j, TOKENIZED_X_DIM] = pred_agent_tokens[i, j, 0] + last_tokenized_arrays[i, j, TOKENIZED_Y_DIM] = pred_agent_tokens[i, j, 1] + last_tokenized_arrays[i, j, TOKENIZED_HEADING_DIM] = pred_agent_tokens[i, j, 2] + + return last_tokenized_arrays + +@jit(nopython=True) +def analysis(last_tokenized_arrays): + stat_dict = [] + num_dict = [] + for i in range(len(last_tokenized_arrays)): + num = 0 + for j in range(len(last_tokenized_arrays[i])): + current_token = last_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + ele_type = current_token[TOKEN_TYPE_IDX] + if num >= 2048: + break + if ele_type in [TokenType.EGO_TOKEN.value]: + stat_dict.append('EGO_TOKEN') + num += 2 + elif ele_type in [TokenType.NEWBORN_AGENT_TOKEN.value]: + stat_dict.append('NEWBORN_AGENT_TOKEN') + num += 2 + elif ele_type in [TokenType.AGENT_TOKEN.value]: + stat_dict.append('AGENT_TOKEN') + num += 2 + elif ele_type in [TokenType.BOS_TOKEN.value]: + stat_dict.append('BOS_TOKEN') + num += 1 + else: + stat_dict.append('other') + num += 1 + num_dict.append(num) + print(num_dict) + element_count = {x: stat_dict.count(x) for x in stat_dict} + print(len(stat_dict), element_count) + +@jit(nopython=True) +def get_frame_data(output_features, frame_index, frame_id=0): + assert output_features.shape[1] == frame_index.shape[1] + output = [] + for i in range(output_features.shape[0]): + current_feature = output_features[i] + out_feature = torch.zeros(current_feature.shape) + + first_pos = torch.where(frame_index[i] == frame_id)[0][0].item() + last_pos = torch.where(frame_index[i] == frame_id)[0][-1].item() + + out_feature[:(last_pos-first_pos)] = current_feature[first_pos:last_pos] + output.append(torch.unsqueeze(out_feature, dim=0)) + + output = torch.vstack(output) + return output + + +@jit(nopython=True) +def detokenize_data(tokenized_arrays): + """ + Detokenize the tokenized arrays to get the original data. + :param tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :return detokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + for i in range(len(tokenized_arrays)): + for j in range(len(tokenized_arrays[i])): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + x = X_RANGE[0] + (current_token[TOKENIZED_X_DIM] - X_START) * X_STEP + y = Y_RANGE[0] + (current_token[TOKENIZED_Y_DIM] - Y_START) * Y_STEP + heading = HEADING_RANGE[0] + (current_token[TOKENIZED_HEADING_DIM] - HEADING_START) * HEADING_STEP + tokenized_arrays[i, j, X_DIM] = x + tokenized_arrays[i, j, Y_DIM] = y + tokenized_arrays[i, j, HEADING_DIM] = heading + return tokenized_arrays + +@jit(nopython=True) +def filter_data(tokenized_arrays, eps=2.0): + """ + loop over tokenized arrays, remove agents that are out of X_RANGE and Y_RANGE + """ + filtered_data = np.ones_like(tokenized_arrays) * np.nan + for i in range(len(tokenized_arrays)): + filtered_index = 0 + for j in range(len(tokenized_arrays[i])): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + x = current_token[X_DIM] + y = current_token[Y_DIM] + if x >= X_RANGE[0] + eps and x <= X_RANGE[1] - eps and y >= Y_RANGE[0] + eps and y <= Y_RANGE[1] - eps: + filtered_data[i, filtered_index] = current_token + filtered_index += 1 + else: + filtered_data[i, filtered_index] = current_token + filtered_index += 1 + return filtered_data + + +@jit(nopython=True) +def update_history_data(hist_tokenized_arrays, last_tokenized_arrays): + """ + append last frame data to history data + :param hist_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :param last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :return updated_hist_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :return updated_last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + for i in range(len(hist_tokenized_arrays)): + for j in range(len(hist_tokenized_arrays[i])): + current_token = hist_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + for k in range(len(last_tokenized_arrays[i])): + last_token = last_tokenized_arrays[i, k] + if np.isnan(last_token).any(): + break + hist_tokenized_arrays[i, j] = last_token + j += 1 + return hist_tokenized_arrays + +@jit(nopython=True) +def add_one_to_frame_index(last_tokenized_arrays): + """ + add one to frame index in last frame data + :param last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :return updated_last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + for i in range(len(last_tokenized_arrays)): + for j in range(len(last_tokenized_arrays[i])): + current_token = last_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + current_token[FRAME_INDEX_IDX] += 1 + return last_tokenized_arrays + +@jit(nopython=True) +def count_num_frame(tokenized_arrays): + """ + Count the number of frames in the tokenized arrays. + """ + max_frames = - np.inf + for i in range(tokenized_arrays.shape[0]): + for j in range(len(tokenized_arrays[i])): + current_token = tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + num_frame = tokenized_arrays[i, j-1, FRAME_INDEX_IDX] - tokenized_arrays[i, 0, FRAME_INDEX_IDX] + 1 + max_frames = max(max_frames, num_frame) + return int(max_frames) + +@jit(nopython=True) +def add_one_to_frame_index(last_tokenized_arrays): + """ + add one to frame index in last frame data + :param last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :return updated_last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + for i in range(len(last_tokenized_arrays)): + for j in range(len(last_tokenized_arrays[i])): + current_token = last_tokenized_arrays[i, j] + if np.isnan(current_token).any(): + break + current_token[FRAME_INDEX_IDX] += 1 + return last_tokenized_arrays + +@jit(nopython=True) +def mark_as_generated(last_tokenized_arrays): + """ + mark the last frame data as generated + :param last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + :return updated_last_tokenized_arrays: np.ndarray, shape (batch_size, max_seq_len, NpTokenizedSequence_DIM) + """ + for i in range(len(last_tokenized_arrays)): + for j in range(len(last_tokenized_arrays[i])): + if np.isnan(last_tokenized_arrays[i, j]).any(): + break + last_tokenized_arrays[i, j, STATUS_DIM] = StatusType.GENERATED.value + return last_tokenized_arrays + +@jit(nopython=True) +def find_agent_index_in_ground_truth_array(tokenized_array, current_token): + # Localize access to current_token attributes + current_frame_index = current_token[FRAME_INDEX_IDX] + current_track_id = current_token[TRACK_ID_DIM] + + # Convert list to set for faster membership checking + valid_token_types = {TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value} + + for i in range(len(tokenized_array)): + # Early exit if NaN is found in the row + if np.isnan(tokenized_array[i]).any(): + break + # Check if the current row matches the criteria + if tokenized_array[i, FRAME_INDEX_IDX] == current_frame_index and tokenized_array[i, TRACK_ID_DIM] == current_track_id and tokenized_array[i, TOKEN_TYPE_IDX] in valid_token_types: + return i + + return -1 + +@jit(nopython=True) +def find_surrounding_agents_in_ground_truth_array(predicted_tokenized_array, current_token): + surrounding_agents_array = List() + for token_index in range(len(predicted_tokenized_array)): + other_token = predicted_tokenized_array[token_index] + if np.isnan(other_token).any(): + break + if other_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + if other_token[FRAME_INDEX_IDX] == current_token[FRAME_INDEX_IDX] and other_token[TRACK_ID_DIM] != current_token[TRACK_ID_DIM]: + surrounding_agents_array.append(other_token) + return surrounding_agents_array + +@jit(nopython=True) +def extract_ego_trajectory(tokenized_array): + ego_trajectory = List() + for i in range(len(tokenized_array)): + current_token = tokenized_array[i] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] == TokenType.EGO_TOKEN.value: + ego_trajectory.append([current_token[X_DIM], current_token[Y_DIM], current_token[HEADING_DIM], current_token[FRAME_INDEX_IDX]]) + return ego_trajectory + +@jit(nopython=True) +def extract_agents_trajectory(tokenized_array, max_frames=50): + agents_info_dict = Dict.empty(key_type=types.int64, value_type=types.float64[:,:]) + + frame_index = tokenized_array[0, FRAME_INDEX_IDX] + frame_index_inlist = 0 + for i in range(len(tokenized_array)): + current_token = tokenized_array[i] + cur_frame_index = current_token[FRAME_INDEX_IDX] + if cur_frame_index > frame_index: + frame_index = cur_frame_index + frame_index_inlist += 1 + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] == TokenType.NEWBORN_AGENT_TOKEN.value or current_token[TOKEN_TYPE_IDX] == TokenType.AGENT_TOKEN.value: + track_id, cls_type, frame_idx = int(current_token[TRACK_ID_DIM]), int(current_token[CLASS_TYPE_DIM]), int(current_token[FRAME_INDEX_IDX]) + if not hash_idx(track_id, cls_type) in agents_info_dict: + agents_info_dict[hash_idx(track_id, cls_type)] = np.ones((max_frames, 6)) * np.nan + agents_info_dict[hash_idx(track_id, cls_type)][frame_index_inlist] = np.array([current_token[X_DIM], current_token[Y_DIM], current_token[HEADING_DIM], current_token[WIDTH_DIM], current_token[LENGTH_DIM], current_token[FRAME_INDEX_IDX]]) + return agents_info_dict + +@jit(nopython=True) +def hash_idx(track_id, cls_type): + return track_id*20 + cls_type + +@jit(nopython=True) +def dehash_idx(h): + return h//20, h%20 + +@jit(nopython=True, parallel=True) +def calculate_smin_ade_batch(predicted_tokenized_array, tokenized_array, is_avg_corner_dist=False, ego_only=False): + smin_ade = 0 + for i in prange(len(predicted_tokenized_array)): + smin_ade += calculate_smin_ade(predicted_tokenized_array[i], tokenized_array[i], is_avg_corner_dist, ego_only) + return smin_ade + +@jit(nopython=True, parallel=True) +def calculate_collision_rate_batch(predicted_tokenized_array, ego_only=False): + collision_rate = 0 + for i in prange(len(predicted_tokenized_array)): + collision_rate += calculate_collision_rate(predicted_tokenized_array[i], ego_only) + return collision_rate / len(predicted_tokenized_array) + +@jit(nopython=True) +def calculate_smin_ade(predicted_tokenized_array, tokenized_array, is_avg_corner_dist=False, ego_only=False): + smin_ade = np.inf + ade_np = np.zeros(len(predicted_tokenized_array)) + for scene_index in range(len(predicted_tokenized_array)): + scene_ade = 0 + num_agents = 0 + for token_index in range(len(predicted_tokenized_array[scene_index])): + current_token = predicted_tokenized_array[scene_index, token_index] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + + if ego_only and current_token[TOKEN_TYPE_IDX] != TokenType.EGO_TOKEN.value: + continue + # skip the conditined tokens + if current_token[STATUS_DIM] == StatusType.CONDITION.value: + continue + gt_index = find_agent_index_in_ground_truth_array(tokenized_array, current_token) + if gt_index == -1: + continue + groud_truth_token = tokenized_array[gt_index] + if is_avg_corner_dist: + xa, ya, ha, wa, la = current_token[X_DIM], current_token[Y_DIM], current_token[HEADING_DIM], current_token[WIDTH_DIM], current_token[LENGTH_DIM] + xb, yb, hb, wb, lb = groud_truth_token[X_DIM], groud_truth_token[Y_DIM], groud_truth_token[HEADING_DIM], groud_truth_token[WIDTH_DIM], groud_truth_token[LENGTH_DIM] + dist = average_corner_distance( + np.array([xa, ya, ha, wa, la]), + np.array([xb, yb, hb, wb, lb]) + ) + else: + x_diff = current_token[X_DIM] - groud_truth_token[X_DIM] + y_diff = current_token[Y_DIM] - groud_truth_token[Y_DIM] + dist = np.sqrt(x_diff**2 + y_diff**2) + scene_ade += dist + num_agents += 1 + ade = scene_ade / (num_agents + 1e-5) + ade_np[scene_index] = ade + smin_ade = np.min(ade_np) + return smin_ade + +@jit(nopython=True) +def calculate_collision_rate(predicted_tokenized_array, ego_only=False, filter_dist=10): + num_agents = 0 + collied_agents = 0 + for token_index in range(len(predicted_tokenized_array)): + current_token = predicted_tokenized_array[token_index] + if np.isnan(current_token).any(): + break + if current_token[TOKEN_TYPE_IDX] in [TokenType.EGO_TOKEN.value, TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + if ego_only and current_token[TOKEN_TYPE_IDX] != TokenType.EGO_TOKEN.value: + continue + # skip the conditined tokens + if current_token[STATUS_DIM] == StatusType.CONDITION.value: + continue + surrounding_agents_array = find_surrounding_agents_in_ground_truth_array(predicted_tokenized_array, current_token) + num_agents += 1 + for other_token in surrounding_agents_array: + if np.isnan(other_token).any(): + break + xa, ya, ha, wa, la = current_token[X_DIM], current_token[Y_DIM], current_token[HEADING_DIM], current_token[WIDTH_DIM], current_token[LENGTH_DIM] + xb, yb, hb, wb, lb = other_token[X_DIM], other_token[Y_DIM], other_token[HEADING_DIM], other_token[WIDTH_DIM], other_token[LENGTH_DIM] + # prefailter + if (xa - xb) ** 2 + (ya - yb) ** 2 > filter_dist ** 2: + continue + is_collided = check_collision( + np.array([xa, ya, ha, wa, la]), + np.array([xb, yb, hb, wb, lb])) + if is_collided: + collied_agents += 1 + collision_rate = collied_agents / (num_agents + 1e-5) + if not ego_only: + # the collision is counted twice for each pair of agents + collision_rate /= 2 + return collision_rate + +@jit(nopython=True) +def random_start_sampling(tokenized_data, randidx_min=0, randidx_max=8): + """ + Randomly sample a starting frame index for each scene in the tokenized data. + + Args: + tokenized_data (np.ndarray): The tokenized data array. + + Returns: + np.ndarray: The array containing the starting frame index for each scene. + """ + sampled_tokenized_data = np.ones_like(tokenized_data) * np.nan + for i in range(len(tokenized_data)): + seq_index = 0 + start_frame_index = np.random.randint(randidx_min, randidx_max) + for j in range(len(tokenized_data[i])): + if tokenized_data[i, j, FRAME_INDEX_IDX] >= start_frame_index: + sampled_tokenized_data[i, seq_index] = tokenized_data[i, j] + seq_index += 1 + return sampled_tokenized_data + +@jit(nopython=True) +def shuffle_agents(tokenized_data): + shuffled_tokenized_data = np.ones_like(tokenized_data) * np.nan + # Specify the type of the list elements, assuming current_token is 1D float64 array + shuffle_buffer = List.empty_list(np.float64[:]) + + for i in range(len(tokenized_data)): + seq_index = 0 + for j in range(len(tokenized_data[i])): + current_token = tokenized_data[i, j] + if np.isnan(current_token).any() and len(shuffle_buffer) == 0: + break + if current_token[TOKEN_TYPE_IDX] == TokenType.EGO_TOKEN.value: + shuffled_tokenized_data[i, seq_index] = current_token + seq_index += 1 + elif current_token[TOKEN_TYPE_IDX] in [TokenType.AGENT_TOKEN.value, TokenType.NEWBORN_AGENT_TOKEN.value]: + shuffle_buffer.append(current_token) + elif current_token[TOKEN_TYPE_IDX] in [TokenType.BOS_TOKEN.value, TokenType.NEWBORN_BOS_TOKEN.value, TokenType.PAD_TOKEN.value] or np.isnan(current_token).any(): + indices = np.arange(len(shuffle_buffer)) + np.random.shuffle(indices) + for k in indices: + shuffled_tokenized_data[i, seq_index] = shuffle_buffer[k] + seq_index += 1 + shuffle_buffer = List.empty_list(np.float64[:]) + shuffled_tokenized_data[i, seq_index] = current_token + seq_index += 1 + if np.isnan(current_token).any(): + break + else: + print('invalid type:', current_token[TOKEN_TYPE_IDX]) + return shuffled_tokenized_data + + + \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/__init__.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/__init__.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/ego_trajectory_with_past_target_builder.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/ego_trajectory_with_past_target_builder.py new file mode 100644 index 0000000..0c8e592 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/ego_trajectory_with_past_target_builder.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import Type + +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.planning.simulation.trajectory.trajectory_sampling import TrajectorySampling +from nuplan.planning.training.preprocessing.feature_builders.abstract_feature_builder import AbstractModelFeature +from nuplan.planning.training.preprocessing.features.trajectory import Trajectory +from nuplan.planning.training.preprocessing.features.trajectory_utils import convert_absolute_to_relative_poses +from nuplan.planning.training.preprocessing.target_builders.abstract_target_builder import AbstractTargetBuilder + + +class EgoTrajectoryWithPastTargetBuilder(AbstractTargetBuilder): + """Trajectory builders constructed the desired ego's trajectory from a scenario.""" + + def __init__(self, future_trajectory_sampling: TrajectorySampling, current_step: int = 8) -> None: + """ + Initializes the class. + :param future_trajectory_sampling: parameters for sampled future trajectory + """ + self._num_future_poses = future_trajectory_sampling.num_poses + self._time_horizon = future_trajectory_sampling.time_horizon + self._current_step = current_step + + @classmethod + def get_feature_unique_name(cls) -> str: + """Inherited, see superclass.""" + return "trajectory" + + @classmethod + def get_feature_type(cls) -> Type[AbstractModelFeature]: + """Inherited, see superclass.""" + return Trajectory # type: ignore + + def get_targets(self, scenario: AbstractScenario) -> Trajectory: + """Inherited, see superclass.""" + current_absolute_state = scenario.initial_ego_state + trajectory_absolute_states = scenario.get_ego_future_trajectory( + iteration=0, num_samples=self._num_future_poses, time_horizon=self._time_horizon + ) + trajectory_absolute_states = [current_absolute_state] + [state for state in trajectory_absolute_states] + current_absolute_state = trajectory_absolute_states[self._current_step] + + # Get all future poses relative to the ego coordinate system + trajectory_relative_poses = convert_absolute_to_relative_poses( + current_absolute_state.rear_axle, [state.rear_axle for state in trajectory_absolute_states] + ) + + # if len(trajectory_relative_poses) != self._num_future_poses: + # raise RuntimeError(f'Expected {self._num_future_poses} num poses but got {len(trajectory_absolute_states)}') + + return Trajectory(data=trajectory_relative_poses) diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/horizon_vector_feature_builder_v2.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/horizon_vector_feature_builder_v2.py new file mode 100644 index 0000000..1f5df8d --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/horizon_vector_feature_builder_v2.py @@ -0,0 +1,215 @@ +from dataclasses import dataclass +import numpy as np +import torch + +from typing import Any, Dict, Type, List, Generator +from nuplan.common.actor_state.ego_state import EgoState +from torch.utils.data.dataloader import default_collate +import nuplan_extent.planning.training.preprocessing.features.vector_builders as vb +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpEgoState, + PreparedScenario, +) +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.planning.training.preprocessing.feature_builders.abstract_feature_builder import ( + AbstractFeatureBuilder, +) +from nuplan.planning.training.preprocessing.features.abstract_model_feature import ( + AbstractModelFeature, + FeatureDataType, +) +from nuplan_extent.planning.training.preprocessing.features.raster_builders import ( + PreparedScenarioFeatureBuilder, +) +from nuplan.planning.simulation.planner.abstract_planner import PlannerInput +from nuplan.planning.simulation.planner.abstract_planner import ( + PlannerInitialization, +) +from nuplan_extent.planning.training.preprocessing.features.vector_builders import get_global_to_local_transform, get_local_to_global_transform + +@dataclass +class HorizonVectorV2(AbstractModelFeature): + """Raster features + + Different from HorizonRaster, this class stores the data as a dictionary with + the raster name as the key and the raster data as the value. + """ + + data: Dict[str, FeatureDataType] + + def serialize(self) -> Dict[str, Any]: + return self.data + + @classmethod + def deserialize(cls, data: Dict[str, Any]) -> AbstractModelFeature: + return HorizonVectorV2(data=data) + + @classmethod + def collate(cls, batch: List[AbstractModelFeature]) -> AbstractModelFeature: + """ + Batch features together with a default_collate function + :param batch: features to be batched + :return: batched features together + """ + serialized = [sample.serialize() for sample in batch] + return cls.deserialize(serialized) + + def to_feature_tensor(self) -> AbstractModelFeature: + return self + # def to_tensor(data: FeatureDataType) -> FeatureDataType: + # if isinstance(data, np.ndarray): + # return torch.tensor(data) + # elif isinstance(data, dict): + # return {name: to_tensor(data) for name in data} + # elif isinstance(data, list): + # return [to_tensor(d) for d in data] + # else: + # return data + # return HorizonVectorV2(data=to_tensor(self.data)) + + def to_device(self, device: torch.device) -> AbstractModelFeature: + return self + # def to_device(data: FeatureDataType) -> FeatureDataType: + # if isinstance(data, torch.Tensor): + # return data.to(device=device) + # elif isinstance(data, dict): + # return {name: to_device(data) for name in data} + # elif isinstance(data, list): + # return [to_device(d) for d in data] + # else: + # return data + # return HorizonVectorV2(data=to_device(self.data)) + + def unpack(self) -> List[AbstractModelFeature]: + batch_size = list(self.data.values())[0].shape[0] + return [ + HorizonVectorV2(data={name: self.data[name][i] for name in self.data}) + for i in range(batch_size) + ] + + +class HorizonVectorFeatureBuilderV2( + AbstractFeatureBuilder, PreparedScenarioFeatureBuilder +): + """ + A raster builder designed for constructing model input features, extending functionality over the HorizonRasterFeatureBuilder by supporting + the preparation and feature extraction from prepared scenarios. Unlike its predecessor, this class outputs features as a structured dictionary + (HorizonRasterV2), accommodating more efficient feature processing. + + Key Differences: + - Supports prepare_scenario() and get_features_from_prepared_scenario() for quicker feature extraction from prepared scenarios. + - Outputs features in a dictionary format for enhanced structure and accessibility. + """ + + def __init__( + self, + agent_features: List[str], + radius: float = 150, + longitudinal_offset: float = 0, + past_time_horizon: float = 2.0, + past_num_steps: int = 4, + future_time_horizon: int = 8.0, + future_num_steps: int = 16, + num_max_agents: List[int] = [256, 128, 64], + ) -> None: + """ + Initializes the feature builder with configurations for constructing model input features, focusing on agent-related features + and trajectory sampling for both past and future states. This setup is essential for creating detailed rasters that reflect + dynamic traffic scenarios and agent behaviors. + + Parameters: + - agent_features: A list of strings identifying the features related to agents that should be included in the raster. These features + can include various attributes such as agent type, motion state, and interactions. + - num_max_agents: The maximum number of agents to include in the raster. This parameter ensures that the model's computational + load is manageable while still capturing a comprehensive view of the traffic scenario (default is set to 256). + This initialization method sets the foundation for a feature builder that is capable of capturing complex traffic scenarios + through detailed rasters, facilitating accurate and efficient model training and inference. + """ + self._radius = radius + builders = {} + builders["agents"] = vb.PastCurrentAgentsVectorBuilder( + radius=radius, + longitudinal_offset=longitudinal_offset, + past_time_horizon=past_time_horizon, + past_num_steps=past_num_steps, + future_time_horizon=future_time_horizon, + future_num_steps=future_num_steps, + agent_features=agent_features, + num_max_agents=num_max_agents, + ) + builders["ego"] = vb.PastCurrentEgoVectorBuilder( + radius=radius, + longitudinal_offset=longitudinal_offset, + past_time_horizon=past_time_horizon, + past_num_steps=past_num_steps, + future_time_horizon=future_time_horizon, + future_num_steps=future_num_steps, + ) + self._builders = builders + self._num_max_agents = num_max_agents + + @classmethod + def get_feature_unique_name(cls) -> str: + """Inherited, see superclass.""" + return "vector" + + @classmethod + def get_feature_type(cls) -> Type[AbstractModelFeature]: + """Inherited, see superclass.""" + return HorizonVectorV2 # type: ignore + + def get_features_from_scenario( + self, scenario: AbstractScenario, iteration: int = 0 + ) -> HorizonVectorV2: + iterations = range(iteration, iteration + 1) + prepared_scenario = PreparedScenario() + prepared_scenario.prepare_scenario(scenario, iterations) + for _, builder in self._builders.items(): + # builder.set_cache_parameter(self._radius, 1e-6) + builder.prepare_scenario(scenario, prepared_scenario, iterations) + ego_state = prepared_scenario.get_ego_state_at_iteration(iteration) + + vectors = {} + for name, builder in self._builders.items(): + vectors[name] = builder.get_features_from_prepared_scenario( + prepared_scenario, iteration, ego_state + ) + vectors['offset'] = prepared_scenario.get_offset() + vectors['center'] = self._builders['agents'].calc_raster_center(ego_state) + vectors['trans'] = get_local_to_global_transform(vectors['center']) + vectors['lidarpc'] = prepared_scenario._data['lidarpc'] + vectors['track_token_id_mapping'] = prepared_scenario._data['track_token_id_mapping'] + vectors['map_name'] = scenario.map_api.map_name + vectors['log_name'] = scenario.log_name + vectors['scenario_token'] = scenario.token + return HorizonVectorV2(data=vectors) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, ego_state: NpEgoState + ) -> AbstractModelFeature: + vectors = {} + for name, builder in self._builders.items(): + vector_data = builder.get_features_from_prepared_scenario( + scenario, iteration, ego_state + ) + vectors[name] = vector_data + + return HorizonVectorV2(data=vectors) + + def prepare_scenario( + self, + scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range, + ) -> None: + for _, builder in self._builders.items(): + builder.prepare_scenario(scenario, prepared_scenario, iterations) + + def get_features_from_simulation( + self, + current_input: PlannerInput, + initialization: PlannerInitialization, + ) -> HorizonVectorV2: + # TODO: implement this. Wrap current_input and initialization into a + # scenario object. And then call get_features_from_scenario. + raise NotImplementedError() diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/nexus_feature_builder.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/nexus_feature_builder.py new file mode 100644 index 0000000..e806280 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/feature_builders/nexus_feature_builder.py @@ -0,0 +1,428 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Type, Union +import numpy as np +import torch +from nuplan.common.actor_state.vehicle_parameters import get_pacifica_parameters +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.planning.training.preprocessing.features.abstract_model_feature import ( + AbstractModelFeature, + FeatureDataType, + to_tensor, +) +from nuplan.planning.training.preprocessing.utils.agents_preprocessing import ( + AgentInternalIndex, + EgoInternalIndex, +) +# WodScenario only used in WOD code path; skipped to avoid waymo_open_dataset dep +# from nuplan_extent.planning.scenario_builder.wod_db.wod_scenario import WodScenario +WodScenario = None +import nuplan_extent.planning.training.preprocessing.features.vector_builders as vb +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpAgentState as AS, +) +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpEgoState, + PreparedScenario, +) +from nuplan_extent.planning.training.preprocessing.feature_builders.horizon_vector_feature_builder_v2 import ( + HorizonVectorFeatureBuilderV2, + HorizonVectorV2, +) +from nuplan_extent.planning.training.preprocessing.features.raster_builders import ( + PreparedMapObject, +) +import pickle as pkl + +# WOD-only deps; skipped when using nuplan data +try: + import tensorflow as tf + from waymo_open_dataset.utils.sim_agents import submission_specs + from waymo_open_dataset.utils import trajectory_utils +except ImportError: + tf = None + trajectory_utils = None + class _SubmissionSpecsStub: + N_FULL_SCENARIO_STEPS = 91 # waymo constant fallback + @staticmethod + def get_sim_agent_ids(wod): + return [] + submission_specs = _SubmissionSpecsStub() + + +from ..features.scene_tensor import (SceneTensor, + SCENE_TENSOR_FEATURES,N_SCENE_TENSOR_FEATURES, + FEATURE_MEANS,FEATURE_STD, + VEH_PARAMS,EGO_WIDTH,EGO_LENGTH,CLASSES, + unnormalize_roadgraph,decode_scene_tensor,encode_agent,encode_ego) + + +class NexusFeatureBuilder(HorizonVectorFeatureBuilderV2): + def __init__( + self, + agent_features: List[str], + radius: float = 150, + longitudinal_offset: float = 0, + past_time_horizon: float = 2.0, + past_num_steps: int = 4, + future_time_horizon: int = 8.0, + future_num_steps: int = 16, + num_max_agents: List[int] = [256, 128, 64], + map_features: List[str] = ["LANE"], + map_num_max_polylines: int = 200, + map_num_points_polylines: int = 20, + map_dim_points_polyline: int = 7, # x,y + len(map_features), + ) -> None: + self._radius = radius + builders = {} + builders["agents"] = vb.PastCurrentAgentsVectorBuilder( + radius=radius, + longitudinal_offset=longitudinal_offset, + past_time_horizon=past_time_horizon, + past_num_steps=past_num_steps, + future_time_horizon=future_time_horizon, + future_num_steps=future_num_steps, + agent_features=agent_features, + num_max_agents=num_max_agents, + ) + builders["ego"] = vb.PastCurrentEgoVectorBuilder( + radius=radius, + longitudinal_offset=longitudinal_offset, + past_time_horizon=past_time_horizon, + past_num_steps=past_num_steps, + future_time_horizon=future_time_horizon, + future_num_steps=future_num_steps, + ) + builders["map"] = vb.MapVectorBuilder( + image_size=0, # not used + radius=radius, + longitudinal_offset=longitudinal_offset, + map_features=map_features, + ) + + self._builders = builders + self._num_max_agents = num_max_agents + self._map_features = map_features + self._map_num_points_polylines = map_num_points_polylines + self._map_dim_points_polyline = map_dim_points_polyline + self._map_num_max_polylines = map_num_max_polylines + + @classmethod + def get_feature_unique_name(cls) -> str: + """Inherited, see superclass.""" + return "scene_tensor" + + @classmethod + def get_feature_type(cls) -> Type[AbstractModelFeature]: + """Inherited, see superclass.""" + return SceneTensor # type: ignore + + def get_features_from_scenario( + self, scenario:AbstractScenario, iteration: int = 0 + ) -> SceneTensor: + if type(scenario) is WodScenario: + return self._compute_waymo_features(scenario) + vector_data = super().get_features_from_scenario(scenario, iteration) + return self._compute_features(vector_data) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, ego_state: NpEgoState + ) -> AbstractModelFeature: + vector_data = super().get_features_from_prepared_scenario( + scenario, iteration, ego_state + ) + return self._compute_features(vector_data) + + def _compute_waymo_features(self, scenario: WodScenario) -> SceneTensor: + # deprecated, not used + with open(scenario._pickle_path,'rb') as f: + wod = pkl.load(f) + states, dimensions, objects = [], [], [] + for track in wod.tracks: + # Iterate over a single object's states. + track_states, track_dimensions = [], [] + for state in track.states: + track_states.append((state.center_x, state.center_y, state.center_z, + state.heading, state.valid)) + track_dimensions.append((state.length, state.width, state.height)) + # Adds to the global states. + states.append(list(zip(*track_states))) + dimensions.append(list(zip(*track_dimensions))) + objects.append((track.id, track.object_type)) + + # Unpack and convert to numpy arrays. + x, y, z, heading, valid = [np.array(s) for s in zip(*states)] + length, width, height = [np.array(s) for s in zip(*dimensions)] + object_ids, object_types = [np.array(s) for s in zip(*objects)] + + logged_trajectories = { + 'x': x, 'y': y, 'z': z, 'heading': heading, + 'length': length, 'width': width, 'height': height, + 'valid': valid, 'object_id': object_ids, + 'object_type': object_types + } + + # if the scenario is a test scenario, we only need to simulate part of agents + need_predict = np.zeros(logged_trajectories['object_id'].shape, dtype=np.float32) + if scenario.split == 'testing': + sim_agent_ids = set(submission_specs.get_sim_agent_ids(wod)) + need_predict = np.isin(logged_trajectories['object_id'], list(sim_agent_ids)).astype(np.float32) + + # get the scene tensor and scene_tensor_validity + # since object_ids are necessary when submitting to waymo sim agent challenge, so we add object_id channel there + def extend_dim(array): + return np.tile(array[:, np.newaxis], (1, logged_trajectories['x'].shape[1])).astype(np.float32) + + scene_tensor = np.stack([ # x,y,z, heading, l,w,h, id,type, need_predict + logged_trajectories['x'], logged_trajectories['y'], logged_trajectories['z'], + logged_trajectories['heading'], + logged_trajectories['length'], logged_trajectories['width'], logged_trajectories['height'], + extend_dim(logged_trajectories['object_id']), extend_dim(logged_trajectories['object_type']), extend_dim(need_predict)], axis=-1) + scene_tensor_validity = logged_trajectories['valid'] + + # release memory + del(logged_trajectories) + # Move agents with need_predict == 1 to the front + need_predict_indices = np.where(scene_tensor[:, 0, -1] == 1)[0] + non_need_predict_indices = np.where(scene_tensor[:, 0, -1] == 0)[0] + + scene_tensor = np.concatenate( + [scene_tensor[need_predict_indices], scene_tensor[non_need_predict_indices]], + axis=0 + ) + scene_tensor_validity = np.concatenate( + [scene_tensor_validity[need_predict_indices], scene_tensor_validity[non_need_predict_indices]], + axis=0 + ) + + # Find the ego index + ego_id = wod.tracks[wod.sdc_track_index].id + ego_index = np.where(scene_tensor[:, 0, -3] == ego_id)[0][0] + + # Move the ego record to the first row + scene_tensor = np.concatenate( + [scene_tensor[ego_index:ego_index+1], np.delete(scene_tensor, ego_index, axis=0)], + axis=0 + ) + scene_tensor_validity = np.concatenate( + [scene_tensor_validity[ego_index:ego_index+1], np.delete(scene_tensor_validity, ego_index, axis=0)], + axis=0 + ) + # n_agents: the number of agents in the scene + # n_timesteps: the number of total timesteps in the scene + n_agents = scene_tensor.shape[0] + n_max_timesteps = submission_specs.N_FULL_SCENARIO_STEPS + n_max_agents = sum(self._num_max_agents) + # to avoid the number of agents exceeding the maximum number of agents + n_agents = min(n_agents,n_max_agents) + # Initialize tensor and valid mask with zeros + padded_scene_tensor = np.zeros((n_max_agents, n_max_timesteps, scene_tensor.shape[-1]), dtype=np.float32) + padded_valid_mask = np.zeros((n_max_agents, n_max_timesteps), dtype=np.float32) + + # Copy the original data into the initialized tensors + padded_scene_tensor[:n_agents, :scene_tensor.shape[1], :] = scene_tensor[:n_agents] + padded_valid_mask[:n_agents, :scene_tensor_validity.shape[1]] = scene_tensor_validity[:n_agents] + + # update the scene tensor and valid mask, and change to torch.Tensor + scene_tensor = padded_scene_tensor + scene_tensor_validity = padded_valid_mask + + # dim should be 3 for x,y,z in waymo open dataset + # if self._map_dim_points_polyline != 3: + # self._map_dim_points_polyline = 3 + # Initialize road graph and validity tensors + road_graph = np.zeros( + shape=( + self._map_num_max_polylines, + self._map_num_points_polylines, + self._map_dim_points_polyline, # only has x, y, z channels + ), + dtype=np.float32, + ) + road_graph_validity = np.zeros_like(road_graph) + + index = 0 + for map_feature in wod.map_features: + if index >= self._map_num_max_polylines: + break + map_type = map_feature.WhichOneof('feature_data') + if map_type in self._map_features: + # Determine the polyline or polygon attribute based on map type + poly = getattr(map_feature, map_type).polyline if map_type in ['lane', 'road_edge'] else getattr(map_feature, map_type).polygon + + # Initialize coordinates and validity arrays + poly_coords = np.zeros((self._map_num_points_polylines, 3 + len(self._map_features)), dtype=np.float32) + poly_validity = np.zeros_like(poly_coords) + num_points = len(poly) + + # Sample points from the polyline or polygon + if num_points > self._map_num_points_polylines: + indices = np.linspace(0, num_points - 1, self._map_num_points_polylines).astype(int) + for j, idx in enumerate(indices): + poly_coords[j, :3] = [poly[idx].x, poly[idx].y, poly[idx].z] + poly_validity[j] = 1 + else: + for j in range(num_points): + poly_coords[j, :3] = [poly[j].x, poly[j].y, poly[j].z] + poly_validity[j] = 1 + + # One-hot encode the map type + type_index = self._map_features.index(map_type) + poly_coords[:, 3 + type_index] = 1 + + # Assign the sampled points to the road graph and validity tensors + road_graph[index,:,:poly_coords.shape[1]] = poly_coords + road_graph_validity[index] = poly_validity + index += 1 + else: + # Ignore other map types (e.g., stop_sign, road_line) + pass + del(wod) + + return SceneTensor( + tensor=scene_tensor.astype(np.float32), + validity=scene_tensor_validity.astype(np.float32), + road_graph=road_graph.astype(np.float32), + road_graph_validity=road_graph_validity.astype(np.float32), + ) + + def _compute_features(self, vector_data: HorizonVectorV2) -> SceneTensor: + vehicles = vector_data.data["agents"]["VEHICLE"] # type: ignore + peds = vector_data.data["agents"]["PEDESTRIAN"] # type: ignore + bic = vector_data.data["agents"]["BICYCLE"] # type: ignore + ego = vector_data.data["ego"] # t x 7 tensor + n_timesteps = len(vehicles) + + # get all unique track ids + ids_veh = np.unique(vehicles[..., 0]) + ids_ped = np.unique(peds[..., 0]) + ids_bic = np.unique(bic[..., 0]) + + # n_agents = len(ids_veh) + len(ids_ped) + len(ids_bic) + n_max_agents = sum(self._num_max_agents) + + # create nan tensor + scene_tensor = np.zeros((n_max_agents, n_timesteps, N_SCENE_TENSOR_FEATURES)) + scene_tensor_validity = np.zeros((n_max_agents, n_timesteps)) + + n_agents = 0 + for i, id_ in enumerate(ids_veh): + if i >= self._num_max_agents[0]: + break + mask = vehicles[..., 0] == id_ + time_validity_ = mask.sum(axis=1).astype(bool) + if time_validity_.sum() < 5: + continue + scene_tensor[n_agents, time_validity_] = encode_agent( + "VEHICLE", + vehicles[mask], # type: ignore + ) + scene_tensor_validity[n_agents] = time_validity_ + n_agents += 1 + + for i, id_ in enumerate(ids_ped): + if i >= self._num_max_agents[1]: + break + mask = peds[..., 0] == id_ + time_validity_ = mask.sum(axis=1).astype(bool) + if time_validity_.sum() < 5: + continue + + scene_tensor[n_agents, time_validity_] = encode_agent( + "PEDESTRIAN", + peds[mask], # type: ignore + ) + scene_tensor_validity[n_agents] = time_validity_ + n_agents += 1 + + for i, id_ in enumerate(ids_bic): + if i >= self._num_max_agents[2]: + break + mask = bic[..., 0] == id_ + time_validity_ = mask.sum(axis=1).astype(bool) + if time_validity_.sum() < 5: + continue + scene_tensor[n_agents, time_validity_] = encode_agent("BICYCLE", bic[mask]) # type: ignore + scene_tensor_validity[n_agents] = time_validity_ + n_agents += 1 + + # append the ego state + + ego_state = encode_ego(ego) + scene_tensor = np.concatenate( + [np.expand_dims(ego_state, 0), scene_tensor], axis=0 + ) + # normalize the scene with x-mu/2sigma + scene_tensor = (scene_tensor - np.array(FEATURE_MEANS)) / ( + 2.0 * np.array(FEATURE_STD) + ) + scene_tensor_validity = np.concatenate( + [np.ones((1, n_timesteps)), scene_tensor_validity], axis=0 + ) + + # encode road_graph + road_graph = np.zeros( + shape=( + self._map_num_max_polylines, + self._map_num_points_polylines, + self._map_dim_points_polyline, + ), + dtype=np.float32, + ) + road_graph_validity = np.zeros_like(road_graph) + map_data = vector_data.data["map"] + + for i in range(min(self._map_num_max_polylines, len(map_data))): + road_graph[i], road_graph_validity[i] = self._encode_map_object(map_data[i]) + + # use the same normalization as for the other coordinates + road_graph[..., :2] = (road_graph[..., :2] - np.array(FEATURE_MEANS)[:2]) / ( + 2 * np.array(FEATURE_STD)[:2] + ) + + return SceneTensor( + tensor=scene_tensor.astype(np.float32), + validity=scene_tensor_validity.astype(np.float32), + road_graph=road_graph.astype(np.float32), + road_graph_validity=road_graph_validity.astype(np.float32), + ) + + def _encode_map_object(self, prepared_map_object: PreparedMapObject): + # coords = prepared_map_object.coords + n_points = prepared_map_object.coords.shape[0] + coords = np.zeros((self._map_num_points_polylines, 2), dtype=np.float32) + coords_valid = np.zeros_like(coords) + + # if n_points > self._map_num_points_polylines: + new_points = np.linspace(0, n_points - 1, self._map_num_points_polylines) + coords[:, 0] = np.interp( + new_points, np.arange(0, n_points), prepared_map_object.coords[:, 0] + ) + coords[:, 1] = np.interp( + new_points, np.arange(0, n_points), prepared_map_object.coords[:, 1] + ) + coords_valid[:, :] = 1 + # elif n_points < self._map_num_points_polylines: + # coords[:n_points] = prepared_map_object.coords + # coords_valid[:n_points] = 1.0 + + type_ = prepared_map_object.object_type + # one hot encode object type + onehot = np.zeros((self._map_num_points_polylines, len(self._map_features))) + idx = self._map_features.index(type_) + onehot[:, idx] = 1 + onehot_valid = np.ones_like(onehot) * coords_valid[:, 0:1] # n_points x 1 + # add speed limit + sl = prepared_map_object.speed_limit + speed_limit = np.full( + shape=(self._map_num_points_polylines, 1), + dtype=np.float32, + fill_value=sl or -1, + ) + speed_limit_valid = coords_valid[:, 0:1] * (1 if sl is not None else 0) + + map_array = np.concatenate([coords, onehot, speed_limit], axis=1) + map_array_valid = np.concatenate( + [coords_valid, onehot_valid, speed_limit_valid], axis=1 + ) + + return map_array, map_array_valid \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/features/__init__.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/features/raster_builders.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/raster_builders.py new file mode 100644 index 0000000..c1aeb96 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/raster_builders.py @@ -0,0 +1,1100 @@ +from abc import ABC, abstractmethod +import cv2 +import math +import numpy.typing as npt +import numpy as np +from scipy.spatial.transform import Rotation as R +from shapely.coords import CoordinateSequence +from typing import Dict, List, NamedTuple, Optional, Tuple +from nuplan.common.actor_state.state_representation import Point2D, StateSE2 +from nuplan.common.actor_state.oriented_box import OrientedBox +from nuplan.common.maps.abstract_map import AbstractMap, SemanticMapLayer +from nuplan.common.maps.abstract_map_objects import LaneGraphEdgeMapObject, PolygonMapObject, PolylineMapObject +from nuplan.planning.training.preprocessing.feature_builders.vector_builder_utils import get_route_polygon_from_roadblock_ids +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.planning.simulation.observation.observation_type import DetectionsTracks +from nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario import NuPlanScenario +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpEgoState, PreparedScenario, PreparedScenarioFeatureBuilder) +from nuplan_extent.planning.training.preprocessing.features.raster_utils import ( + generate_virtual_center, + _get_proximal_map_objects, +) +from nuplan_extent.planning.training.preprocessing.utils.route_utils import ( + route_roadblock_correction, ) +from nuplan_extent.common.geometry.oriented_box import box_to_corners + +from nuplan.common.maps.abstract_map_objects import RoadBlockGraphEdgeMapObject +from typing import Set +from nuplan.planning.training.preprocessing.feature_builders.vector_builder_utils import prune_route_by_connectivity + + +def get_roadblock_from_roadblock_ids( + map_api: AbstractMap, point: Point2D, radius: float, + route_roadblock_ids: List[str]) -> List[RoadBlockGraphEdgeMapObject]: + """ + Extract route polygon from map for route specified by list of roadblock ids. Polygon is represented as collection of + polygons of roadblocks/roadblock connectors encompassing route. + :param map_api: map to perform extraction on. + :param point: [m] x, y coordinates in global frame. + :param radius: [m] floating number about extraction query range. + :param route_roadblock_ids: ids of roadblocks/roadblock connectors specifying route. + :return: A route as sequence of roadblock/roadblock connector polygons. + """ + roadblocks: List[RoadBlockGraphEdgeMapObject] = [] + + # extract roadblocks/connectors within query radius to limit route consideration + layer_names = [ + SemanticMapLayer.ROADBLOCK, SemanticMapLayer.ROADBLOCK_CONNECTOR + ] + layers = map_api.get_proximal_map_objects(point, radius, layer_names) + roadblock_ids: Set[str] = set() + + for layer_name in layer_names: + roadblock_ids = roadblock_ids.union( + {map_object.id + for map_object in layers[layer_name]}) + # prune route by connected roadblocks within query radius + route_roadblock_ids = prune_route_by_connectivity(route_roadblock_ids, + roadblock_ids) + + for route_roadblock_id in route_roadblock_ids: + # roadblock + roadblock_obj = map_api.get_map_object(route_roadblock_id, + SemanticMapLayer.ROADBLOCK) + + # roadblock connector + if not roadblock_obj: + roadblock_obj = map_api.get_map_object( + route_roadblock_id, SemanticMapLayer.ROADBLOCK_CONNECTOR) + + if roadblock_obj: + roadblocks.append(roadblock_obj) + + return roadblocks + + +def _get_coords_xy(coords: CoordinateSequence) -> npt.NDArray[np.float64]: + """X and Y arrays from coords. + + :param coords: the coordinate sequence + :return: 2d coordinates of the vertices of the polygon. + """ + return np.array(coords) + + +def _linestring_to_coords(geometry: LaneGraphEdgeMapObject): + """Get 2d coordinates of the endpoints of line segment string. + + The line segment string is a shapely.geometry.linestring. + :param geometry: the line segment string. + :return: 2d coordinates of the endpoints of line segment string. + """ + return _get_coords_xy(geometry.baseline_path.linestring.coords) + + +def _polygon_to_coords(geometry: PolygonMapObject): + """Get 2d coordinates of the vertices of a polygon. + + The polygon is a shapely.geometry.polygon. + :param geometry: the polygon. + :return: 2d coordinates of the vertices of the polygon. + """ + return _get_coords_xy(geometry.polygon.exterior.coords) + + +def _polyline_to_coords(geometry: PolylineMapObject): + """Get 2d coordinates of the vertices of a polyline. + + :param geometry: the polyline. + :return: 2d coordinates of the vertices of the polygon. + """ + return _get_coords_xy(geometry.linestring.coords) + + +def get_deduplicated_route_roadblock_ids( + scenario: AbstractScenario, + with_route_roadblock_correction: bool = True) -> List[str]: + """Get the roadblock ids of the route without duplication. + + Sometimes there are artifacts in the route that the adjacent roadblocks are + repeated. This is a hack to remove the repeated roadblocks. + + :param scenario: scenario + :param with_route_roadblock_correction: whether to correct the route roadblocks. + In some scenario, the original route roadblocks have some artifacts. For + example, the ego car may not be on the route. This option will correct + the artifacts. + :return: roadblock ids of the route without duplication + """ + ids = scenario.get_route_roadblock_ids() + roadblock_ids = [ids[0]] + for i in ids: + if i != roadblock_ids[-1]: + roadblock_ids.append(i) + if with_route_roadblock_correction: + try: + roadblock_ids = route_roadblock_correction( + scenario.get_ego_state_at_iteration(0), scenario.map_api, + roadblock_ids) + except: + print('Route roadblock correction failed') + return roadblock_ids + + +class ShapeList(NamedTuple): + """Represents a list of shapes. + + All the coordinates are put into one single array for efficent storage + and computation. The sizes array is used to index into the coordinates + """ + + # concatenated coordinates of the points of all the shapes, shape [N, 2] + coords: npt.NDArray[np.float32] + + # number of points for each shape, shape [M], sizes.sum() == coords.shape[0] + sizes: npt.NDArray[np.int32] + + @property + def num(self): + """The number of shapes in this list.""" + return len(self.sizes) + + +class PreparedMapObject(NamedTuple): + coords: npt.NDArray[np.float32] + object_type: str + speed_limit: Optional[float] + + +def _get_extended_layer_untransformed_coords( + center: Point2D, radius: float, offset: float, map_api: AbstractMap, + map_layer_name: SemanticMapLayer, map_layer_geometry: str, + prepared_map_objects: PreparedMapObject): + """Get the untransformed coordinates of of the objects for the given layers. + + :param center: center of the raster in the coordinates of the original map + :param radius: radius of the raster in meters + :param offset: offset to be subtracted from the coordinates + :param map_api: map api + :param map_layer_name: name of the map layer + :param map_layer_geometry: geometry type of the map layer, one of ('polygon', + 'linestring'). If it is 'polygon', the coordinates of the vertices of + the polygon will be returned. If it is 'linestring', the coordinates of + the baseline paths will be returned. + :param prepared_map_objects: dict from map object is to the the prepared map + objects. New map objects will be added to this dict. + :return: list of ids of the objects for the given layers. + """ + nearest_vector_map = _get_proximal_map_objects( + map_api=map_api, + layers=[map_layer_name], + point=center, + radius=radius, + ) + + geometry = nearest_vector_map[map_layer_name] + + if map_layer_name in [SemanticMapLayer['BOUNDARIES']]: + obj_to_coords_func = _polyline_to_coords + elif map_layer_geometry == 'polygon': + obj_to_coords_func = _polygon_to_coords + elif map_layer_geometry == 'linestring': + obj_to_coords_func = _linestring_to_coords + else: + raise RuntimeError( + f'Layer geometry {map_layer_geometry} type not supported') + for geom in geometry: + if geom.id in prepared_map_objects: + continue + coords = obj_to_coords_func(geom) + coords = (coords - offset).astype(np.float32) + speed_limit = getattr(geom, 'speed_limit_mps', None) + prepared_map_objects[geom.id] = PreparedMapObject( + coords, map_layer_name.name, speed_limit + ) + + geom_ids = [geom.id for geom in geometry] + + return geom_ids + + +# This matrix transforms the ego coordinates to raster coordinates. +# The x-axis of the raster coordinate system corresponds to the y-axis of +# the ego coordinate (i.e. the left direction of the ego vehicle). The y-axis of +# the raster coordinate corresponds to the negative x-axis of the ego coordinate +# (i.e the backward direction of the ego vehicle). +_map_align_transform = np.diag([1., -1., 1.]) @ R.from_euler( + 'z', 90, degrees=True).as_matrix() + + +def get_global_to_local_transform(pose: StateSE2) -> npt.NDArray[np.float32]: + """The the transformation matrix from global to local coordinates. + + :param pose: the pose of the local coordinate system in the global coordinate system. + :return: inverse of the 3x3 2D transformation matrix + """ + c = math.cos(pose.heading) + s = math.sin(pose.heading) + x = pose.x + y = pose.y + return np.array([ + [c, s, -c * x - s * y], + [-s, c, s * x - c * y], + [0, 0, 1], + ]) + + +def get_local_to_global_transform(pose: StateSE2) -> npt.NDArray[np.float32]: + """The the transformation matrix from global to local coordinates. + + :param pose: the pose of the local coordinate system in the global coordinate system. + :return: inverse of the 3x3 2D transformation matrix + """ + c = math.cos(pose.heading) + s = math.sin(pose.heading) + x = pose.x + y = pose.y + return np.array([ + [c, -s, x], + [s, c, y], + [0, 0, 1], + ]) + + +def transform_to_pixel_coords(untransformed_coords: npt.NDArray[np.float32], + center: StateSE2, radius: float, image_size: int, + bit_shift: int): + """Transform global coordinates to pixel coordinates. + + Note that the resulted coordinates are the actual pixel locations multiplied + by 2**bit_shift. bit_shift is for cv2.fillPoly/cv2.polylines to work with + float coordinates. + + :param untransformed_coords: global coordinates + :param center: the pose of the local coordinate system in the global + coordinate system. + :param radius: radius of the raster in meters + :param image_size: size of the raster image in pixels + :param bit_shift: bit shift for converting float to int + """ + + if len(untransformed_coords) == 0: + return [] + resolution = (2 * radius) / image_size + scale = 2**bit_shift / resolution + global_transform = get_global_to_local_transform(center) + # By default the map is right-oriented, this makes it top-oriented. + transform = _map_align_transform @ global_transform + mat = (transform[:2, :2].T * scale).astype(np.float32) + vec = transform[:2, 2] + radius + # Previously, the raster is generated with a different _map_align_transform + # without multiplying diag(1,-1, 1). And the result is flipped vertically. + # (See raster_utils.get_roadmap_raster for example). + # The current way achieves the flip directly by changing _map_align_transform. + # However, this results in a one pixel vertical shift. The following line + # is to compensate for this shift so that the generated raster is compatible + # with the previously trainied model. + vec[1] -= resolution + vec = (vec * scale).astype(np.float32) + object_coords = (untransformed_coords @ mat + vec).astype(np.int64) + return object_coords + + +def draw_polygon_image(polygons: ShapeList, colors: List[float], + image_size: int, center: StateSE2, + radius: float) -> npt.NDArray[np.float32]: + """Draw polygons on the raster. + + :param polygons: polygons to be drawn. The coordinates are in the global + frame. + :param colors: colors of the polygons + :param image_size: size of the raster image in pixels + :param center: the pose of the local coordinate system in the global + coordinate system. + :param radius: radius of the raster in meters + """ + raster: npt.NDArray[np.float32] = np.zeros((image_size, image_size), + dtype=np.float32) + if polygons.coords.size == 0: + return raster + + bit_shift = 10 + coords = transform_to_pixel_coords(polygons.coords, center, radius, + image_size, bit_shift) + start = 0 + for color, size in zip(colors, polygons.sizes): + cv2.fillPoly( + raster, + coords[start:start + size][None], + color=color, + shift=bit_shift, + lineType=cv2.LINE_AA) + start += size + return raster + + +def draw_polyline_image(polylines: ShapeList, colors: List[float], + thickness: int, image_size: int, center: StateSE2, + radius: float) -> npt.NDArray[np.float32]: + """Draw polylines on the raster. + + :param polylines: polygons to be drawn. The coordinates are in the global + frame. + :param colors: colors of the polygons + :param image_size: size of the raster image in pixels + :param center: the pose of the local coordinate system in the global + coordinate system. + :param radius: radius of the raster in meters + """ + raster: npt.NDArray[np.float32] = np.zeros((image_size, image_size), + dtype=np.float32) + if polylines.coords.size == 0: + return raster + bit_shift = 10 + coords = transform_to_pixel_coords(polylines.coords, center, radius, + image_size, bit_shift) + start = 0 + for color, size in zip(colors, polylines.sizes): + cv2.polylines( + raster, [coords[start:start + size]], + isClosed=False, + color=color, + shift=bit_shift, + thickness=thickness, + lineType=cv2.LINE_AA) + start += size + return raster + + +def _to_shape_list(coords: List[npt.NDArray], offset: npt.NDArray + ) -> Tuple[npt.NDArray[np.float32], npt.NDArray[np.int32]]: + """Convert a list of coordinates to a ShapeList. + + :param coords: a list of coordinates, each element is a numpy array of shape [N, 2] + :param offset: offset to be subtracted from the coordinates + """ + if len(coords) == 0: + return ShapeList( + np.empty((0, 2), dtype=np.float32), np.empty((0, ), + dtype=np.int32)) + sizes = np.array([len(c) for c in coords], dtype=np.int32) + coords = np.concatenate(coords, axis=0) + coords = (coords - offset).astype(np.float32) + return ShapeList(coords, sizes) + + +def _concat_shape_list(shape_list: List[ShapeList]) -> ShapeList: + """Concatenate a list of ShapeList into one ShapeList.""" + coords = np.concatenate([s.coords for s in shape_list], axis=0) + sizes = np.concatenate([s.sizes for s in shape_list], axis=0) + return ShapeList(coords, sizes) + + +class RasterBuilderBase(PreparedScenarioFeatureBuilder): + """The base class for raster builders. + + :param image_size: size of the raster image in pixels + :param radius: radius of the raster in meters + :param ego_longitudinal_offset: the center of the raster is `longitudinal_offset * radius` + meters in front of the rear axle of ego vehicle. 0 means the center is + at the rear axle. + """ + + def __init__(self, image_size: int, radius: float, + longitudinal_offset: float): + super().__init__() + self._image_size = image_size + self._radius = radius + self._longitudinal_offset = longitudinal_offset + self._cache_enabled = True + # see set_cache_parameter for explanations about the following two parameters + self._cache_grid_step = self._radius / 2 + self._cache_radius = self._radius * 2.0 + + def set_cache_parameter(self, cache_grid_step: float, + cache_radius: float) -> None: + """Setup cache parameters. + + The map features are cached based on the discretized center of the raster. + If two raster has same discretized center, they will share the same cache. + The discretized center is calculated as `(round(x / cache_grid_step), round(y / cache_grid_step))`. + In order for the same cached feature to cover different raster at different + centers, the cache radius should be larger than the radius of the raster. + The default cache_grid_step is radius / 2, and the default cache_radius is + radius * 1.5. + + :param cache_grid_step: grid step for the cache + :param cache_radius: radius for the cache + """ + self._cache_grid_step = cache_grid_step + self._cache_radius = cache_radius + + def calc_raster_center(self, ego_state: NpEgoState) -> StateSE2: + """Calculate the center of the raster. + + The center of the raster is `longitudinal_offset * radius` meters in front + of the rear axle of ego_state. + + :param ego_state: ego state + """ + return generate_virtual_center( + StateSE2(*ego_state.rear_axle_pose.tolist()), self._radius, + self._longitudinal_offset) + + def calc_cache_key(self, center: Point2D) -> Tuple[int, int]: + """Calculate cache key. + + The cache key is the discretized center of the raster and it is used + for retrieving the map objects from the cache. + + :param center: center of the raster in the coordinates of prepared scenario + :return: cache key for retrieving the map objects in the cache. + """ + step = self._cache_grid_step + grid_x = int(math.floor(center.x / step + 0.5)) + grid_y = int(math.floor(center.y / step + 0.5)) + return grid_x, grid_y + + def calc_cache_key_and_center(self, center: Point2D, offset: npt.NDArray[2] + ) -> Tuple[Tuple[int, int], Point2D]: + """Calculate cache key and map center for getting map objects from the map. + + :param center: center of the raster in the coordinates of the prepared scenario + :param offset: offset for shifting the coordinates for the prepared scenario + :return: + - cache key for storing/retrieving the map objects in the cache. + - the center for retrieving map objects (in the original map coordinate) + The caller should use the returned center and self._cache_radius to + get map objects from the map. + """ + step = self._cache_grid_step + grid_x = int(math.floor(center.x / step + 0.5)) + grid_y = int(math.floor(center.y / step + 0.5)) + # Avoid numpy types since Point2D members are float + x0 = grid_x * step + float(offset[0]) + y0 = grid_y * step + float(offset[1]) + return (grid_x, grid_y), Point2D(x0, y0) + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + pass + + +class MapObjectRasterBuilder(RasterBuilderBase): + """The base class for raster builders that use map objects. + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param map_features: list of map features to be used + """ + + def __init__(self, image_size: int, radius: float, + longitudinal_offset: float, map_features: List[str]): + super().__init__(image_size, radius, longitudinal_offset) + self._map_features = map_features + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + map_api = scenario.map_api + for iteration in iterations: + ego_state = prepared_scenario.get_ego_state_at_iteration(iteration) + center = self.calc_raster_center(ego_state) + self.prepare_scenario_at_center(map_api, prepared_scenario, center) + + def prepare_scenario_at_center(self, map_api: AbstractMap, + prepared_scenario: PreparedScenario, + center: Point2D) -> None: + """Prepare map objects at the given center. + + :param map_api: map api + :param prepared_scenario: prepared scenario + :param center: center of the map object in the coordinates of prepared scenario + """ + for feature_name in self._map_features: + self.prepare_map_objects(map_api, prepared_scenario, center, + feature_name, 'polygon') + + def prepare_map_objects(self, map_api: AbstractMap, + scenario: PreparedScenario, center: StateSE2, + feature_name: str, geometry: str) -> None: + """Prepare map object polygons/polylines at the given center. + + Also prepare features for speed limit. + + Two features are prepared: + - map_object_{geometry}_{feature_name} (Dict[str, PreparedMapObject]): + polygons/linestring of the map objects. Each polygon/linestring is a list + of 2d coordinates, with origin at `scenario.get_offset()`. + - map_object_{geometry}_{feature_name}_ids (List[str]): + the ids of the object around `center`. + + :param map_api: map api + :param scenario: prepared scenario + :param center: center of the map object + :param feature_name: feature name + :param geometry: geometry type of the map object, either "polygon" or "linestring" + """ + geometry_feature_name = f'map_object_{geometry}_{feature_name}' + geometry_feature_ids_name = f'map_object_{geometry}_{feature_name}_ids' + offset = scenario.get_offset() + cache_key, center = self.calc_cache_key_and_center(center, offset) + if scenario.feature_exists_at_center(geometry_feature_ids_name, + cache_key): + return + if scenario.feature_exists(geometry_feature_name): + prepared_map_objects = scenario.get_feature(geometry_feature_name) + else: + prepared_map_objects = {} + scenario.add_feature(geometry_feature_name, prepared_map_objects) + obj_ids = _get_extended_layer_untransformed_coords( + center, self._cache_radius, offset, map_api, + SemanticMapLayer[feature_name], geometry, prepared_map_objects) + scenario.add_feature_at_center(geometry_feature_ids_name, obj_ids, + cache_key) + + +class EgoRasterBuilder(RasterBuilderBase): + """The ego layer of the raster + + It draws the extent of the ego car at the origin. + + Cached Features: None + + Note that this ego layer is slightly different from raster_utils.get_ego_raster() + because of using cv2.fillPoly instead of cv2.rectangle. + + TODO: get ego_width/ego_front_length/ego_rear_length from EgoState.car_footprint.vehicle_parameters + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param ego_width: width of the ego car + :param ego_front_length: front length (rear-axle to front) of the ego car + :param ego_rear_length: rear length (rear-axle to back) of the ego car + """ + + def __init__(self, image_size: int, radius: float, + longitudinal_offset: float, ego_width: float, + ego_front_length: float, ego_rear_length: float): + super().__init__(image_size, radius, longitudinal_offset) + self._ego_width = ego_width + self._ego_front_length = ego_front_length + self._ego_rear_length = ego_rear_length + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + x = self._radius * (1 - self._longitudinal_offset * 2) + x0 = x - self._ego_rear_length + x1 = x + self._ego_front_length + y0 = -self._ego_width / 2 + y1 = self._ego_width / 2 + center = StateSE2(self._radius, 0, 0) + polygons = np.array([[x0, y0], [x0, y1], [x1, y1], [x1, y0]], + dtype=np.float32) + polygons = ShapeList(polygons, np.array([4], dtype=np.int32)) + return draw_polygon_image( + polygons=polygons, + colors=[1.0], + image_size=self._image_size, + center=center, + radius=self._radius) + + +def _get_prepared_coords(scenario: PreparedScenario, feature_name: str, + cache_key: Tuple[int, int]): + """Get the prepared coordinates of the map objects from PreparedScenario. + + :param scenario: prepared scenario + :param feature_name: feature name + :param cache_key: cache key + :return: + - coordinates of the map objects + - ids of the map objects + - dict from map object id to the prepared map objects + """ + prepared_objects = scenario.get_feature(feature_name) + obj_ids = scenario.get_feature_at_center(feature_name + '_ids', cache_key) + return (prepared_objects[id].coords + for id in obj_ids), obj_ids, prepared_objects + + +class RoadmapRasterBuilder(MapObjectRasterBuilder): + """Map layer of the raster by converting vector map to raster map. + + Cached Features: + map_object_polygons_{feature_name} (ShapeList): polygons of the map objects. + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param map_features: list of map features to be used + """ + + def __init__(self, image_size: int, radius: float, + longitudinal_offset: float, + map_feature_to_color_dict: Dict[str, float]): + super().__init__(image_size, radius, longitudinal_offset, + list(map_feature_to_color_dict.keys())) + self._map_feature_to_color_dict = map_feature_to_color_dict + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + all_polygons = [] + colors = [] + center = self.calc_raster_center(ego_state) + cache_key = self.calc_cache_key(center) + all_coords = [] + for feature_name, color in self._map_feature_to_color_dict.items(): + coords, obj_ids, _ = _get_prepared_coords( + scenario, 'map_object_polygon_' + feature_name, cache_key) + all_coords.extend(coords) + colors.extend([color] * len(obj_ids)) + all_polygons = ShapeList( + coords=np.concatenate(all_coords, axis=0), + sizes=np.array([len(c) for c in all_coords])) + return draw_polygon_image(all_polygons, colors, self._image_size, + center, self._radius) + + +class SpeedLimitRasterBuilder(MapObjectRasterBuilder): + """Raster representing the speed limit information of the map + + The speed is encoded as different colors for different map objects. + + Cached Features: + map_object_polygons_{feature_name} (ShapeList): polygons of the map objects. + map_object_speed_limit_{feature_name} (List[None|float]): speed limit of the map objects. + + feature_name is either "LANE" or "LANE_CONNECTOR". + + Note that speed information is not always available for all map objects. Those + speed limits will be None. + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param none_speed_limit: the speed limit for None speed limit. + :param max_speed_normalizer: the speed used to normalize the speed limit. + The normalized speed limit is `speed_limit / max_speed_normalizer`. + """ + + def __init__(self, + image_size: int, + radius: float, + longitudinal_offset: float, + none_speed_limit: float = 0, + max_speed_normalizer: float = 16.0): + super().__init__(image_size, radius, longitudinal_offset, + ["LANE", "LANE_CONNECTOR"]) + self._max_speed_normalizer = max_speed_normalizer + self._none_speed_limit = none_speed_limit + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + all_coords = [] + colors = [] + center = self.calc_raster_center(ego_state) + cache_key = self.calc_cache_key(center) + for feature_name in self._map_features: + coords, obj_ids, prepared_objects = _get_prepared_coords( + scenario, 'map_object_polygon_' + feature_name, cache_key) + all_coords.extend(coords) + speed_limits = [(prepared_objects[id].speed_limit + or self._none_speed_limit) for id in obj_ids] + colors.extend([ + speed_limit / self._max_speed_normalizer + for speed_limit in speed_limits + ]) + all_polygons = ShapeList( + coords=np.concatenate(all_coords, axis=0), + sizes=np.array([len(c) for c in all_coords])) + return draw_polygon_image(all_polygons, colors, self._image_size, + center, self._radius) + + +class RouteRasterBuilder(RasterBuilderBase): + """Raster representing the navigation route. + + Cached Features: + route_roadblock_polygons (ShapeList): polygons of the roadblocks on the route. + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param with_route_roadblock_correction: whether to correct the route roadblocks. + In some scenario, the original route roadblocks have some artifacts. For + example, the ego car may not be on the route. This option will correct + the artifacts. + """ + + def __init__(self, + image_size: int, + radius: float, + longitudinal_offset: float, + with_route_roadblock_correction: float = True): + super().__init__(image_size, radius, longitudinal_offset) + self._with_route_roadblock_correction = with_route_roadblock_correction + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + map_api = scenario.map_api + route_roadblock_ids: Tuple[str] = get_deduplicated_route_roadblock_ids( + scenario, self._with_route_roadblock_correction) + offset = prepared_scenario.get_offset() + for iteration in iterations: + ego_state = prepared_scenario.get_ego_state_at_iteration(iteration) + center = self.calc_raster_center(ego_state) + cache_key, center = self.calc_cache_key_and_center(center, offset) + if prepared_scenario.feature_exists_at_center( + 'route_roadblock_polygons', cache_key): + continue + block_polygons = get_route_polygon_from_roadblock_ids( + map_api, center, self._cache_radius, + route_roadblock_ids).to_vector() + block_polygons = _to_shape_list(block_polygons, offset) + prepared_scenario.add_feature_at_center('route_roadblock_polygons', + block_polygons, cache_key) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + center = self.calc_raster_center(ego_state) + cache_key = self.calc_cache_key(center) + polygons = scenario.get_feature_at_center('route_roadblock_polygons', + cache_key) + return draw_polygon_image(polygons, [1.0] * polygons.num, + self._image_size, center, self._radius) + + +class DrivableAreaRasterBuilder(MapObjectRasterBuilder): + """Raster representing the drivable area. + + Cached features: + map_object_polygons_DRIVABLE_AREA (ShapeList): polygons of the drivable area. + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + """ + + def __init__(self, image_size: int, radius: float, + longitudinal_offset: float): + super().__init__(image_size, radius, longitudinal_offset, + ['DRIVABLE_AREA']) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + center = self.calc_raster_center(ego_state) + cache_key = self.calc_cache_key(center) + coords = list( + _get_prepared_coords(scenario, 'map_object_polygon_DRIVABLE_AREA', + cache_key)[0]) + polygons = ShapeList( + coords=np.concatenate(coords, axis=0), + sizes=np.array([len(c) for c in coords])) + colors = [1.0] * polygons.num + return draw_polygon_image(polygons, colors, self._image_size, center, + self._radius) + + +class BaselinePathsRasterBuilder(MapObjectRasterBuilder): + """Raster representing the baseline paths. + + Cached features: + map_object_linestring_{feature_name} (ShapeList): polylines of the baseline + paths, where feature_name is either "LANE" or "LANE_CONNECTOR". + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param line_thickness: thickness of the baseline paths in pixels. + """ + + def __init__(self, image_size: int, radius: float, + longitudinal_offset: float, line_thickness: int): + super().__init__(image_size, radius, longitudinal_offset, + ['LANE', 'LANE_CONNECTOR']) + self._line_thickness = line_thickness + + def prepare_scenario_at_center(self, map_api: AbstractMap, + prepared_scenario: PreparedScenario, + center: Point2D) -> None: + for feature_name in self._map_features: + self.prepare_map_objects(map_api, prepared_scenario, center, + feature_name, 'linestring') + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + all_coords = [] + center = self.calc_raster_center(ego_state) + cache_key = self.calc_cache_key(center) + for feature_name in self._map_features: + all_coords.extend( + _get_prepared_coords(scenario, + 'map_object_linestring_' + feature_name, + cache_key)[0]) + if len(all_coords) == 0: + return np.zeros((self._image_size, self._image_size), dtype=np.float32) + all_polylines = ShapeList( + coords=np.concatenate(all_coords, axis=0), + sizes=np.array([len(c) for c in all_coords])) + colors = [1.] * len(all_polylines.sizes) + return draw_polyline_image(all_polylines, colors, self._line_thickness, + self._image_size, center, self._radius) + + +class EgoSpeedRasterBuilder(RasterBuilderBase): + """Raster representing with normlized speed of ego car. + + It is raster with all the pixels with a same value equal to the normalized + speed of the ego car. + + The speed is obtained from EgoState.agent.velocity. + + Cached Features: None + + Note that the speed from EgoState is slightly different from that calculated + based on the current and previous location of the ego vehicle, which is used + by `raster_utils.get_speed_raster`. + + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the virtual center + :param max_speed_normalizer: the speed used to normalize the speed limit. + The normalized speed limit is `speed / max_speed_normalizer`. + """ + + def __init__(self, + image_size: int, + radius: float, + longitudinal_offset: float, + max_speed_normalizer: float = 16.0): + super().__init__(image_size, radius, longitudinal_offset) + self._max_speed_normalizer = max_speed_normalizer + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + return np.full((self._image_size, self._image_size), + (ego_state.vel_lon**2 + ego_state.vel_lat**2)**0.5 / + self._max_speed_normalizer, + dtype=np.float32) + + +class TrafficLightRasterBuilder(RasterBuilderBase): + """ + A raster builder that creates a raster representation for traffic lights in the environment. + + This builder generates an image where traffic lights and their states are represented. Currently, it initializes an empty raster image with no traffic lights represented, serving as a placeholder for future implementations where traffic lights will be visually encoded based on their state and relevance to the ego vehicle. + + Parameters: + - image_size (int): The height and width of the square raster image in pixels. + - radius (float): The observation radius around the ego vehicle to include in the raster, in meters. Traffic lights outside this radius are not included. + - longitudinal_offset (float): The offset from the center of the ego vehicle towards the front of the vehicle where the observation radius begins, in meters. + """ + + def __init__(self, + image_size: int, + radius: float, + longitudinal_offset: float): + super().__init__(image_size, radius, longitudinal_offset) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + return np.full((self._image_size, self._image_size), + 0.0, + dtype=np.float32) + + +class PastCurrentAgentsRasterBuilder(RasterBuilderBase): + """Raster representing the past and current agents. + + Cached Features: + tracked_object_boxes: Dict[int, np.ndarray[n, 5]): boxes of the tracked + object for each iteration. Key is iteration. Each box is reparesented + by 5 numbers: center_x, center_y, heading, half_length, half_width. + ego_state: Dict[int, NpEgoState]: ego states for iterations before 0, + up to `past_time_horizon`. + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the raster + :param past_time_horizon: [s] time horizon of past agents + :param past_num_steps: number of past steps to sample + :param relative_overlay: If False, each agent is represented a series of boxes + corresponding to their past and current pose. If True, each agent is represented + as a series of boxes, where each box represents the pose of the agent + relative to the pose of the ego vehicle at the corresponding iteration. + """ + + def __init__(self, + image_size: int, + radius: float, + longitudinal_offset: float, + past_time_horizon: float, + past_num_steps: int, + relative_overlay: bool = False): + super().__init__(image_size, radius, longitudinal_offset) + self._past_time_horizon = past_time_horizon + self._past_num_steps = past_num_steps + self._relative_overlay = relative_overlay + self._key_name = "tracked_object_boxes" + self._agent_type = ['vehicle', 'pedestrian', 'bicycle'] + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + offset = prepared_scenario.get_offset() + interval = scenario.database_interval + + if self._past_time_horizon > 0: + history_window = int(self._past_time_horizon / interval) + assert history_window % self._past_num_steps == 0, ( + f"history window {history_window} must be divisible by " + f"past_num_steps {self._past_num_steps}") + history_step = history_window // self._past_num_steps + else: + history_window = 0 + history_step = 1 + + # 1. get all the history iteration and current iteration for iterations + all_iterations = set() + for iteration in iterations: + all_iterations.update( + range(iteration - history_window, iteration + 1, history_step)) + all_iterations = sorted(all_iterations) + + # 2. find the earliest unprepared iteration + earliest_unprepared_iteration = None + for iteration in all_iterations: + if not prepared_scenario.feature_exists_at_iteration( + self._key_name, iteration): + earliest_unprepared_iteration = iteration + break + + # 3. Get past tracked objects + if earliest_unprepared_iteration is not None and earliest_unprepared_iteration < 0: + num_samples = -earliest_unprepared_iteration + if num_samples == 1 and isinstance(scenario, NuPlanScenario): + # 0.5 * iterval is due to an artifact of NuPlanScenario.get_past_tracked_object() + # that when num_samples=1, it actually gets a sample at one + # iteration before the given iteration. This is caused by + # scenario_utils.sample_indices_with_time_horizon() + # See nuplan issue https://github.com/motional/nuplan-devkit/issues/348 + # TODO: remove this hack when the issue is fixed. + time_horizon = 0.5 * interval + else: + time_horizon = num_samples * interval + past_detections = list( + scenario.get_past_tracked_objects( + iteration=0, + time_horizon=time_horizon, + num_samples=num_samples)) + assert len(past_detections) == num_samples + past_ego_states = list( + scenario.get_ego_past_trajectory( + iteration=0, + time_horizon=time_horizon, + num_samples=num_samples)) + + # 4. prepare polygons for all iterations + for iteration in all_iterations: + if prepared_scenario.feature_exists_at_iteration( + self._key_name, iteration): + continue + if iteration < 0: + detections = past_detections[iteration] + past_ego_state = past_ego_states[iteration] + prepared_scenario.add_ego_state_at_iteration( + past_ego_state, iteration) + else: + detections = scenario.get_tracked_objects_at_iteration( + iteration) + polygons = self._get_detection_boxes(detections, offset) + prepared_scenario.add_feature_at_iteration(self._key_name, + polygons, iteration) + + def _get_detection_boxes(self, detections: DetectionsTracks, + offset) -> npt.NDArray[np.float32]: + if len(detections.tracked_objects) == 0: + return np.empty((0, 5), dtype=np.float32) + x0 = float(offset[0]) + y0 = float(offset[1]) + + def _extract(box: OrientedBox) -> np.ndarray: + center = box.center + return (center.x - x0, center.y - y0, center.heading, + box.half_length, box.half_width) + def _in_type(tracked_object_type) -> bool: + return tracked_object_type.fullname in self._agent_type + boxes = [_extract(o.box) for o in detections.tracked_objects if _in_type(o.tracked_object_type)] + return np.array(boxes, dtype=np.float32) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + all_boxes = [] + all_colors = [] + step_interval = int(self._past_time_horizon / + scenario.database_interval / self._past_num_steps) + for i in range(self._past_num_steps + 1): + iter = iteration - (self._past_num_steps - i) * step_interval + boxes = scenario.get_feature_at_iteration(self._key_name, + iter) + if boxes.size > 0: + if self._relative_overlay: + prev_ego_state = scenario.get_ego_state_at_iteration(iter) + boxes = self._adjust_boxes_relative_position( + boxes, prev_ego_state, ego_state) + all_boxes.append(boxes) + all_colors.extend( + [(i + 1) / (self._past_num_steps + 1)] * boxes.shape[0]) + + if len(all_boxes) > 0: + all_boxes = np.concatenate(all_boxes, axis=0) + coords = box_to_corners(all_boxes).reshape(-1, 2) + else: + coords = np.empty((0, 2), dtype=np.float32) + center = self.calc_raster_center(ego_state) + return draw_polygon_image( + ShapeList(coords, np.array([4] * len(all_boxes), dtype=np.int32)), + all_colors, self._image_size, center, self._radius) + + def _adjust_boxes_relative_position(self, boxes, prev_ego_state, + ego_state): + boxes = boxes.copy() + current_center = self.calc_raster_center(ego_state) + prev_center = self.calc_raster_center(prev_ego_state) + trans1 = get_global_to_local_transform(prev_center) + trans2 = get_local_to_global_transform(current_center) + trans = (trans2 @ trans1).astype(np.float32) + boxes[:, :2] = boxes[:, :2] @ trans[:2, :2].T + trans[:2, 2] + dh = current_center.heading - prev_center.heading + boxes[:, 2] += dh + + return boxes + +class StaticAgentsRasterBuilder(PastCurrentAgentsRasterBuilder): + """ + A raster builder that creates a raster representation for static agents in the environment. + + This builder generates an image where static agents (like parked cones, barriers, etc.) are represented. Currently, it initializes an empty raster image with no agents represented, serving as a placeholder for future implementations where static agents will be visually encoded. + + Parameters: + - image_size (int): The height and width of the square raster image in pixels. + - radius (float): The observation radius around the ego vehicle to include in the raster, in meters. Agents outside this radius are not included. + - longitudinal_offset (float): The offset from the center of the ego vehicle towards the front of the vehicle where the observation radius begins, in meters. + """ + def __init__(self, image_size: int, radius: float, longitudinal_offset: float, past_time_horizon: float, past_num_steps: int, relative_overlay: bool = False): + super().__init__(image_size, radius, longitudinal_offset, past_time_horizon, past_num_steps, relative_overlay) + self._agent_type = ['traffic_cone', 'barrier', 'czone_sign', 'generic_object'] diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/features/raster_utils.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/raster_utils.py new file mode 100644 index 0000000..6346bd5 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/raster_utils.py @@ -0,0 +1,2486 @@ +from __future__ import annotations + +from typing import Callable, List, Tuple, Optional, Dict, Generator, Union +import copy +import math +from array import array +from collections import defaultdict, deque + +import cv2 +import numpy as np +import numpy.typing as npt +from scipy.spatial.transform import Rotation as R + +import shapely.geometry as geom +from nuplan.common.actor_state.agent_state import AgentState +from nuplan.common.actor_state.ego_state import EgoState +from nuplan.common.actor_state.oriented_box import OrientedBox +from nuplan.common.actor_state.state_representation import Point2D, StateSE2 +from nuplan.common.actor_state.tracked_objects import TrackedObjects +from nuplan.common.maps.abstract_map import AbstractMap, SemanticMapLayer, MapObject +from nuplan.common.maps.nuplan_map.polygon_map_object import NuPlanPolygonMapObject +from nuplan.common.maps.nuplan_map.polyline_map_object import NuPlanPolylineMapObject +from nuplan.common.maps.nuplan_map.lane import NuPlanLane +from nuplan.common.maps.nuplan_map.nuplan_map import NuPlanMap +from nuplan.common.maps.nuplan_map.roadblock import NuPlanRoadBlock +from nuplan.planning.simulation.observation.observation_type import \ + DetectionsTracks +from nuplan.planning.training.preprocessing.feature_builders.vector_builder_utils import \ + get_route_polygon_from_roadblock_ids +from nuplan.planning.training.preprocessing.features.raster_utils import ( + _cartesian_to_projective_coords, _draw_linestring_image, + _draw_polygon_image, _linestring_to_coords, _polygon_to_coords) +from nuplan.common.actor_state.tracked_objects_types import TrackedObjectType +from nuplan.common.maps.maps_datatypes import TrafficLightStatusData +from nuplan.common.maps.maps_datatypes import TrafficLightStatusType +from nuplan.common.maps.abstract_map_objects import PolylineMapObject + +BASELINE_TL_COLOR = { + TrafficLightStatusType.RED: (1, 0, 0), + TrafficLightStatusType.YELLOW: (1, 1, 0), + TrafficLightStatusType.GREEN: (0, 1, 0), + # Also the deafult color for baseline path + TrafficLightStatusType.UNKNOWN: (0, 0, 1), +} + + +def generate_virtual_center(center: StateSE2, radius: float, + longitudinal_offset: float) -> StateSE2: + """Generate virtual ego center + + Args: + ego_state (StateSE2): input SE2 center [center or real_axle]. + radius (float): [m] the radius of the square raster map. + longitudinal_offset (float): longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + + Returns: + StateSE2: SE2 state of virtual ego center + """ + if longitudinal_offset == 0: + return center + virtual_center = copy.deepcopy(center) + center_offset = [ + 2 * radius * longitudinal_offset * np.cos(virtual_center.heading), + 2 * radius * longitudinal_offset * np.sin(virtual_center.heading) + ] + virtual_center.x += center_offset[0] + virtual_center.y += center_offset[1] + return virtual_center + + +def calc_raster_center(ego_state: EgoState, radius: float, + longitudinal_offset: float) -> StateSE2: + """Calculate the center of the raster. + + The center of the raster is `longitudinal_offset * radius` meters in front + of the rear axle of ego_state. + + :param ego_state: ego state + """ + return generate_virtual_center(ego_state.rear_axle, radius, + longitudinal_offset) + + +def get_route_raster( + ego_state: EgoState, + route_roadblock_ids: List[str], + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + feature_color: Optional[float] = 1.0, + with_coords: bool = False, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct the route layer of the raster by converting roadblock ids to raster map. + :param ego_state: SE2 state of ego. + :param route_roadblock_ids: roadblock ids along with the route + :param map_api: map api. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param feature_color: feature value fill in road block polygon + :return route_raster: the constructed map raster layer. + """ + # Assume the raster has a square shape. + assert (x_range[1] - x_range[0]) == ( + y_range[1] - + y_range[0]), f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}' + + radius = (x_range[1] - x_range[0]) / 2 + route_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + global_transform = np.linalg.inv(virtual_center.as_matrix()) + + # By default the map is right-oriented, this makes it top-oriented. + map_align_transform = R.from_euler( + 'z', 90, degrees=True).as_matrix().astype(np.float32) + transform = map_align_transform @ global_transform + block_polylines = get_route_polygon_from_roadblock_ids( + map_api, virtual_center.point, radius, + route_roadblock_ids).to_vector() + coords = [(transform @ _cartesian_to_projective_coords( + np.array(polylines)).T).T[:, :2] for polylines in block_polylines] + route_raster = _draw_polygon_image(route_raster, coords, radius, + resolution, feature_color) + + # Flip the agents_raster along the horizontal axis. + route_raster = np.flip(route_raster, axis=0) + route_raster = np.ascontiguousarray(route_raster, dtype=np.float32) + if with_coords: + return route_raster, coords + return route_raster + + +def get_past_current_agents_raster( + agents_raster: npt.NDArray[np.float32], + ego_state: EgoState, + detections: DetectionsTracks, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + polygon_bit_shift: int = 9, + color_value: Optional[float] = 1.0, + longitudinal_offset: Optional[float] = 0.0, +): + """ + Construct the history agents layer of the raster by transforming all detected boxes around the agent + and creating polygons of them in a raster grid. + :param ego_state: current state of ego. + :param detections: list of 3D bounding box of detected agents. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param polygon_bit_shift: bit shift of the polygon used in opencv. + :return: constructed agents raster layer. + """ + + width, height = raster_shape + radius = (x_range[1] - x_range[0]) / 2 + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + + ego_to_global = virtual_center.as_matrix() + global_to_ego = np.linalg.inv(ego_to_global) + + north_aligned_transform = StateSE2(0, 0, np.pi / 2).as_matrix() + + for tracked_object in detections.tracked_objects: + # Transform the box relative to agent. + raster_object_matrix = north_aligned_transform @ global_to_ego @ tracked_object.center.as_matrix( + ) + raster_object_pose = StateSE2.from_matrix(raster_object_matrix) + # Filter out boxes outside the raster. + valid_x = -radius < raster_object_pose.y < radius + valid_y = -radius < raster_object_pose.x < radius + if not (valid_x and valid_y): + continue + + # Get the 2D coordinate of the detected agents. + raster_oriented_box = OrientedBox( + raster_object_pose, tracked_object.box.length, + tracked_object.box.width, tracked_object.box.height) + box_bottom_corners = raster_oriented_box.all_corners() + x_corners = np.asarray( + [corner.x for corner in box_bottom_corners]) # type: ignore + y_corners = np.asarray( + [corner.y for corner in box_bottom_corners]) # type: ignore + + # Discretize + y_corners = (y_corners + radius) / (2 * radius) * height + x_corners = (x_corners + radius) / (2 * radius) * width + + box_2d_coords = np.stack([x_corners, y_corners], + axis=1) # type: ignore + box_2d_coords = np.expand_dims(box_2d_coords, axis=0) + + # Draw the box as a filled polygon on the raster layer. + box_2d_coords = (box_2d_coords * 2**polygon_bit_shift).astype(np.int32) + cv2.fillPoly( + agents_raster, + box_2d_coords, + color=color_value, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + + return agents_raster + + +def get_static_agents_raster( + agents_raster: npt.NDArray[np.float32], + ego_state: EgoState, + detections: DetectionsTracks, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + polygon_bit_shift: int = 9, + color_value: Optional[float] = 1.0, + longitudinal_offset: Optional[float] = 0.0, +): + """ + Construct the history agents layer of the raster by transforming all detected boxes around the agent + and creating polygons of them in a raster grid. + :param ego_state: SE2 state of ego. + :param detections: list of 3D bounding box of detected agents. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param polygon_bit_shift: bit shift of the polygon used in opencv. + :return: constructed agents raster layer. + """ + xmin, xmax = x_range + ymin, ymax = y_range + width, height = raster_shape + + # ego_to_global = ego_state.rear_axle.as_matrix() + radius = (x_range[1] - x_range[0]) / 2 + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + + ego_to_global = virtual_center.as_matrix() + global_to_ego = np.linalg.inv(ego_to_global) + + north_aligned_transform = StateSE2(0, 0, np.pi / 2).as_matrix() + + for tracked_object in detections.tracked_objects: + if tracked_object.tracked_object_type not in [TrackedObjectType.TRAFFIC_CONE, TrackedObjectType.BARRIER, TrackedObjectType.CZONE_SIGN, TrackedObjectType.GENERIC_OBJECT]: + continue + # print(tracked_object.tracked_object_type) + # Transform the box relative to agent. + raster_object_matrix = north_aligned_transform @ global_to_ego @ tracked_object.center.as_matrix( + ) + raster_object_pose = StateSE2.from_matrix(raster_object_matrix) + # Filter out boxes outside the raster. + valid_x = x_range[0] < raster_object_pose.x < x_range[1] + valid_y = y_range[0] < raster_object_pose.y < y_range[1] + if not (valid_x and valid_y): + continue + + # Get the 2D coordinate of the detected agents. + raster_oriented_box = OrientedBox( + raster_object_pose, tracked_object.box.length, + tracked_object.box.width, tracked_object.box.height) + box_bottom_corners = raster_oriented_box.all_corners() + x_corners = np.asarray( + [corner.x for corner in box_bottom_corners]) # type: ignore + y_corners = np.asarray( + [corner.y for corner in box_bottom_corners]) # type: ignore + + # Discretize + y_corners = (y_corners - ymin) / (ymax - ymin) * height # type: ignore + x_corners = (x_corners - xmin) / (xmax - xmin) * width # type: ignore + + box_2d_coords = np.stack([x_corners, y_corners], + axis=1) # type: ignore + box_2d_coords = np.expand_dims(box_2d_coords, axis=0) + + # Draw the box as a filled polygon on the raster layer. + box_2d_coords = (box_2d_coords * 2**polygon_bit_shift).astype(np.int32) + cv2.fillPoly( + agents_raster, + box_2d_coords, + color=color_value, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + + return agents_raster + + +def get_speed_raster( + past_trajectory: npt.NDArray[np.float32], + raster_shape: Tuple[float, float], + feature_time_interval: float, + max_speed_normalizer: float, +) -> npt.NDArray[np.float32]: + """ + Construct speed raster with normlized speed filling the full grid. + :param past_trajectory: past trajectory of ego vehicle. + :param raster_shape: shape of the target raster. + :param max_speed_normalizer: use max speed to normalize current speed + :return: constructed speed raster layer. + """ + ego_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + ego_raster[:, :] = np.hypot(past_trajectory[-1, 0], past_trajectory[-1, 1]) + + ego_raster = np.ascontiguousarray(ego_raster, dtype=np.float32) + ego_raster /= feature_time_interval + ego_raster /= max_speed_normalizer + return ego_raster + + +def get_target_raster( + future_trajectory: npt.NDArray[np.float32], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[float, float], +) -> npt.NDArray[np.float32]: + """ + Construct future target of ego vehicle on raster by drawing a pixel in the grid. + :param future_trajectory: future trajectory of ego vehicle. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :return: constructed speed raster layer. + """ + ego_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + xmin, xmax = x_range + ymin, ymax = y_range + width, height = raster_shape + + # Discretize + target_y = (future_trajectory[-1, 0] - ymin) / \ + (ymax - ymin) * height # type: ignore + target_x = (future_trajectory[-1, 1] - xmin) / \ + (xmax - xmin) * width # type: ignore + + target_x = int(np.clip(target_x, 0, height - 1)) + target_y = int(np.clip(target_y, 0, width - 1)) + + cv2.circle( + ego_raster, (target_x, target_y), radius=0, color=1.0, thickness=-1) + ego_raster = np.flip(ego_raster, axis=0) + ego_raster = np.flip(ego_raster, axis=1) + ego_raster = np.ascontiguousarray(ego_raster, dtype=np.float32) + return ego_raster + + +def get_augmented_ego_raster( + raster_shape: Tuple[int, int], + ego_longitudinal_offset: float, + ego_width_pixels: float, + ego_front_length_pixels: float, + ego_rear_length_pixels: float, + offset_yaw: float, + offset_xy: Tuple[float, float], + polygon_bit_shift: int = 9, +) -> npt.NDArray[np.float32]: + """ + Construct the ego layer of the raster by drawing a polygon of the ego's extent in the middle of the grid. + :param raster_shape: shape of the target raster. + :param ego_longitudinal_offset: [%] offset percentage to place the ego vehicle in the raster. + :param ego_width_pixels: width of the ego vehicle in pixels. + :param ego_front_length_pixels: distance between the rear axle and the front bumper in pixels. + :param ego_rear_length_pixels: distance between the rear axle and the rear bumper in pixels. + :param yaw: offset heading of ego vehicle on the raster map. + :param offset: [m] offset distance of ego vehicle on the raster map. + :param polygon_bit_shift: bit shift of the polygon used in opencv. + :return: constructed ego raster layer. + """ + ego_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + # Construct a rectangle representing the ego vehicle in the center of the + # raster. + map_x_center = int(raster_shape[1] * 0.5) + map_y_center = int(raster_shape[0] * (0.5 + ego_longitudinal_offset)) + ego_top_left = [-ego_width_pixels // 2, -ego_front_length_pixels, 1] + ego_bottom_left = [ego_width_pixels // 2, -ego_front_length_pixels, 1] + ego_bottom_right = [ego_width_pixels // 2, +ego_rear_length_pixels, 1] + ego_top_right = [-ego_width_pixels // 2, +ego_rear_length_pixels, 1] + corners = np.array( + [ego_top_left, ego_bottom_left, ego_bottom_right, ego_top_right]) + # TR matrix + tr_matrix = np.array([[ + np.cos(offset_yaw), + np.sin(offset_yaw), offset_xy[0] + map_x_center + ], [-np.sin(offset_yaw), + np.cos(offset_yaw), offset_xy[1] + map_y_center], [0, 0, 1]]) + corners = np.dot(tr_matrix, corners.T).T + + box_2d_coords = np.expand_dims(corners[:, :2], axis=0) + + # Draw the box as a filled polygon on the raster layer. + box_2d_coords = (box_2d_coords * 2**polygon_bit_shift).astype(np.int32) + cv2.fillPoly( + ego_raster, + box_2d_coords, + color=1.0, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + ego_raster = np.asarray(ego_raster) + ego_raster = np.ascontiguousarray(ego_raster, dtype=np.float32) + return ego_raster + + +def get_fut_agents_raster( + ego_state: EgoState, + tracked_objects: List[DetectionsTracks], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + polygon_bit_shift: int = 9, +): + """ + Construct the future agents layer of the raster by transforming all detected boxes around the agent + and creating polygons of them in a raster grid. + + :param ego_state: SE2 state of ego. + :param tracked_objects: list of detected tracks. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param polygon_bit_shift: bit shift of the polygon used in opencv. + :return: constructed agents raster layer. + """ + xmin, xmax = x_range + ymin, ymax = y_range + width, height = raster_shape + + ego_to_global = ego_state.rear_axle.as_matrix() + global_to_ego = np.linalg.inv(ego_to_global) + + north_aligned_transform = StateSE2(0, 0, np.pi / 2).as_matrix() + agents_raster = np.zeros(raster_shape, dtype=np.float32) + + for tracked_object in tracked_objects: + # Transform the box relative to agent. + raster_object_matrix = north_aligned_transform @ global_to_ego @ tracked_object.center.as_matrix( + ) + raster_object_pose = StateSE2.from_matrix(raster_object_matrix) + # Filter out boxes outside the raster. + valid_x = x_range[0] < raster_object_pose.x < x_range[1] + valid_y = y_range[0] < raster_object_pose.y < y_range[1] + if not (valid_x and valid_y): + continue + + # Get the 2D coordinate of the detected agents. + raster_oriented_box = OrientedBox( + raster_object_pose, tracked_object.box.length, + tracked_object.box.width, tracked_object.box.height) + box_bottom_corners = raster_oriented_box.all_corners() + x_corners = np.asarray( + [corner.x for corner in box_bottom_corners]) # type: ignore + y_corners = np.asarray( + [corner.y for corner in box_bottom_corners]) # type: ignore + + # Discretize + y_corners = (y_corners - ymin) / (ymax - ymin) * height # type: ignore + x_corners = (x_corners - xmin) / (xmax - xmin) * width # type: ignore + + box_2d_coords = np.stack([x_corners, y_corners], + axis=1) # type: ignore + box_2d_coords = np.expand_dims(box_2d_coords, axis=0) + + # Draw the box as a filled polygon on the raster layer. + value = tracked_object.tracked_object_type.value + 1 + box_2d_coords = (box_2d_coords * 2**polygon_bit_shift).astype(np.int32) + cv2.fillPoly( + agents_raster, + box_2d_coords, + color=value, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + + # Flip the agents_raster along the horizontal axis. + agents_raster = np.asarray(agents_raster) + agents_raster = np.flip(agents_raster, axis=0) + agents_raster = np.ascontiguousarray(agents_raster, dtype=np.float32) + + return agents_raster + + +def filter_tracked_objects(tracked_objects_lst: List[TrackedObjects], + reverse: bool) -> List[TrackedObjects]: + selected_tracked_agents_lst = [] + if reverse: + anchor_tracked_objects = tracked_objects_lst[-1] + candidate_tracked_objects_lst = tracked_objects_lst[:-1] + else: + anchor_tracked_objects = tracked_objects_lst[0] + candidate_tracked_objects_lst = tracked_objects_lst[1:] + + valid_track_token_set = set() + for tracked_agent in anchor_tracked_objects.get_agents(): + valid_track_token_set.add(tracked_agent.track_token) + + for i, tracked_objects in enumerate(candidate_tracked_objects_lst): + tracked_agents_inside_anchor = [] + for tracked_object in tracked_objects: + if tracked_object.track_token in valid_track_token_set: + tracked_agents_inside_anchor.append(tracked_object) + selected_tracked_agents_lst.append(tracked_agents_inside_anchor) + + return selected_tracked_agents_lst + + +def get_drivable_area_raster( + focus_agent: Union[AgentState, EgoState], + map_api: AbstractMap, + map_features: Dict[str, int], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Constructs a raster map of the drivable area around the focus agent. + + Args: + focus_agent (AgentState, EgoState): The state of the agent. + map_api: An instance of a map API to query map data. + map_features: A dictionary of map features to be drawn and their color for encoding. + x_range: A tuple of the minimum and maximum range from the edges of the grid in the x direction, in meters. + y_range: A tuple of the minimum and maximum range from the edges of the grid in the y direction, in meters. + raster_shape: A tuple of the shape of the target raster (assumed to be square). + resolution: The pixel size in meters. + longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + + Returns: + A NumPy array of the constructed drivable area raster layer. + + Raises: + AssertionError: If the x and y ranges do not form a square shape. + + """ + # Ensure the raster has a square shape. + assert (x_range[1] - x_range[0]) == ( + y_range[1] - y_range[0] + ), f"Raster shape is assumed to be square but got width: {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}" + + # Compute the radius of the raster. + radius = (x_range[1] - x_range[0]) / 2 + + # Initialize the raster map to all zeros. + drivable_area_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + # Get the coordinates of the drivable area around the focus agent. + if isinstance(map_api, NuPlanMap): + # Current NuPlanMap does not support nuplan native function _get_layer_coords. + coords, _, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer['DRIVABLE_AREA'], 'polygon', + radius, longitudinal_offset) + else: + # If map_api does not support _get_layer_coords function, just add additional if_else conditions. + coords, _, = _get_layer_coords(focus_agent, map_api, + SemanticMapLayer['DRIVABLE_AREA'], + 'polygon', radius, longitudinal_offset) + + # Encode the drivable area polygon in the raster map. + feature_color = 1.0 + drivable_area_raster = _draw_polygon_image( + drivable_area_raster, coords, radius, resolution, feature_color) + + # Flip the raster map along the horizontal axis to match image conventions. + drivable_area_raster = np.flip(drivable_area_raster, axis=0) + + # Ensure the raster map is contiguous and has the correct data type. + drivable_area_raster = np.ascontiguousarray( + drivable_area_raster, dtype=np.float32) + + return drivable_area_raster + + +def _polyline_to_coords( + geometry: List[PolylineMapObject]) -> List[Tuple[array[float]]]: + """Get 2d coordinates of the vertices of a polyline. + + :param geometry: the polyline. + :return: 2d coordinates of the vertices of the polygon. + """ + return [element.linestring.coords.xy for element in geometry] + + +def get_interior_edges( + map_api: AbstractMap, + route_id: str, +) -> List[NuPlanLane]: + """ + Function returns lanes(no lane connectors) when getting an input id of road block or road block connector + :param map_api: An instance of a map API to query map data. + :param route_id: A route roadblock id. + :return: List of filtered roadblock interior_edges + """ + roadblock = map_api._get_roadblock(route_id) + if roadblock: + return roadblock.interior_edges + else: + roadblock_connector = map_api._get_roadblock_connector(route_id) + if roadblock_connector: + return roadblock_connector.interior_edges + else: + raise ValueError("Should be road_block or road_block connector") + + +def get_map_object_raster( + focus_agent: EgoState, + map_api: AbstractMap, + map_feature_name: str, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + route_roadblock_ids: List[str], + draw_ego_route_separately: bool = False, +) -> npt.NDArray[np.float32]: + """ + Constructs a raster map of the map_objects area around the focus agent. + + Args: + focus_agent: The state of the agent representing the ego vehicle. + map_api: An instance of a map API to query map data. + map_feature_names: List of str + x_range: A tuple of the minimum and maximum range from the edges of the grid in the x direction, in meters. + y_range: A tuple of the minimum and maximum range from the edges of the grid in the y direction, in meters. + raster_shape: A tuple of the shape of the target raster (assumed to be square). + resolution: The pixel size in meters. + route_roadblock_ids: route block id of the current map. + draw_ego_route_separately: whether to extract self-route objects by route block ids and save in a different channel. + + Returns: + A NumPy array of the constructed map_objects area raster layer. + + Raises: + AssertionError: check the shape of data, and validation of input + + """ + # Ensure the raster has a square shape. + # because nuplan map_api _get_extended_layer_coords requires square input + assert (x_range[1] - x_range[0]) == ( + y_range[1] - y_range[0] + ), f"Raster shape is assumed to be square but got width: {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}" + + # Compute the radius of the raster. + radius = (x_range[1] - x_range[0]) / 2 + + # Initialize the raster map to all zeros. + if draw_ego_route_separately: + map_objects: npt.NDArray[np.float32] = np.zeros((*raster_shape, 2), + dtype=np.float32) + else: + map_objects: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + self_map_objects: npt.NDArray[np.float32] = np.zeros((*raster_shape, 1), + dtype=np.float32) + other_map_objects: npt.NDArray[np.float32] = np.zeros((*raster_shape, 1), + dtype=np.float32) + + # get proximal coords. Raster objects are represented as coords, and we can draw linestrings or polygons with coords. + # _get_extended_layer_coords in hoplan here implemented more layers than + # nuplan version. + coords, ids, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer[map_feature_name], 'polygon', + radius) # here must polygon no matter what + + # here piece of code is for boundaries only + # if draw_ego_route_separately is true, we will select some of the coords from them. we will at first get lanes, + # then check whether the lane's related block id is in the route_block_ids, and retained if yes. + # at last, we filtered the result in previous get_coords to ensure no + # outlier values. + if map_feature_name == 'BOUNDARIES': + lane_ids_by_routeblock_ids = [ + interior_edge.id for route_id in route_roadblock_ids + for interior_edge in get_interior_edges(map_api, route_id) + ] + lane_ids_by_mapapi_and_route_ids = [] + self_coords = [] + self_ids = [] + other_coords = [] + other_ids = [] + for map_layer_name in ['LANE', 'LANE_CONNECTOR']: + mp_coords, mp_ids, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer[map_layer_name], + 'polygon', radius) + for index in range(len(mp_ids)): + lane_id = mp_ids[index] + if map_layer_name == 'LANE': + cnt_lane = map_api._get_lane(lane_id) + elif map_layer_name == 'LANE_CONNECTOR': + cnt_lane = map_api._get_lane_connector(lane_id) + else: + raise TypeError("Can't do for none lane type") + if cnt_lane.id in lane_ids_by_routeblock_ids: + lane_ids_by_mapapi_and_route_ids.append( + cnt_lane.left_boundary.id) + lane_ids_by_mapapi_and_route_ids.append( + cnt_lane.right_boundary.id) + # coords and ids are 1-1 map, so then must have same length + assert len(coords) == len(ids) + for index in range(len(ids)): + if ids[index] in lane_ids_by_mapapi_and_route_ids: + self_coords.append(coords[index]) + self_ids.append(ids[index]) + else: + other_coords.append(coords[index]) + other_ids.append(ids[index]) + + # for different features, we use different drawing methods. Some of them are drawed by plygon, + # others are drawed by linestring. + if map_feature_name in ["ROADBLOCK"]: + # Encode the drivable area polygon in the raster map. + feature_color = 1.0 + map_objects = _draw_polygon_image(map_objects, coords, radius, + resolution, feature_color) + + elif map_feature_name in ["CARPARK_AREA", "WALKWAYS"]: + ids = np.asarray(ids) + lane_colors: npt.NDArray[np.uint8] = np.full( + len(ids), 1, dtype=np.uint8) + map_objects = _draw_linestring_image( + image=map_objects, + object_coords=coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=1, + lane_colors=lane_colors, + bit_shift=13, + ) + elif map_feature_name in ["BOUNDARIES"]: + + self_ids = np.asarray(self_ids) + self_colors: npt.NDArray[np.uint8] = np.full( + len(self_ids), 1, dtype=np.uint8) + + other_ids = np.asarray(other_ids) + other_colors: npt.NDArray[np.uint8] = np.full( + len(other_ids), 1, dtype=np.uint8) + # make in two parts for both draw_ego_route_separately is true or false + + self_map_objects = _draw_linestring_image( + image=self_map_objects, + object_coords=self_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=1, + lane_colors=self_colors, + bit_shift=13, + ) + + other_map_objects = _draw_linestring_image( + image=other_map_objects, + object_coords=other_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=1, + lane_colors=other_colors, + bit_shift=13, + ) + # if self, draw a 6-channel with different color; if not, draw a + # 3-channel with same color and overriden style + if draw_ego_route_separately: + map_objects = np.concatenate((other_map_objects, self_map_objects), + axis=2) + else: + # Convert images to grayscale for bitwise operations + gray1 = cv2.cvtColor(other_map_objects, cv2.COLOR_BGR2GRAY) + gray2 = cv2.cvtColor(self_map_objects, cv2.COLOR_BGR2GRAY) + + # Combine the two images using bitwise operations + mask = cv2.bitwise_or(gray1, gray2) + map_objects = cv2.bitwise_and( + other_map_objects, self_map_objects, mask=mask) + else: + raise TypeError( + "Not implemented Error: select between polygon and linestring!") + + # Flip the raster map along the horizontal axis to match image conventions. + map_objects = np.flip(map_objects, axis=0) + + # Ensure the raster map is contiguous and has the correct data type. + map_objects = np.ascontiguousarray(map_objects, dtype=np.float32) + + return map_objects + + +def get_speed_limit_raster( + focus_agent: EgoState, + map_api: AbstractMap, + map_feature_names: List[str], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + max_speed_normalizer: float, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct a raster map layer of speed limit information by converting a vector map to a raster map. + :param focus_agent: AgentState representing the ego vehicle. + :param map_api: An instance of a map api. + :param map_feature_names: A list of names of map features to be drawn and their corresponding colors for encoding. + :param x_range: A tuple representing the minimum and maximum range from the edges of the grid in the x direction, in meters. + :param y_range: A tuple representing the minimum and maximum range from the edges of the grid in the y direction, in meters. + :param raster_shape: A tuple representing the desired shape of the target raster. + :param resolution: The pixel size in meters. + :param max_speed_normalizer: use max speed to normalize current speed + :param longitudinal_offset: The longitudinal offset of the ego vehicle from the center of the raster map. + :return: The constructed speed limit map raster layer. + """ + # Assume the raster has a square shape. + assert (x_range[1] - x_range[0]) == ( + y_range[1] - + y_range[0]), f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}' + + radius = (x_range[1] - x_range[0]) / 2 + speed_limit_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for feature_name in map_feature_names: + coords, _, speed_limits = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer[feature_name], 'polygon', + radius, longitudinal_offset) + for i in range(len(speed_limits)): + speed_limit = speed_limits[i] + speed_limit_raster = _draw_polygon_image(speed_limit_raster, + [coords[i]], radius, + resolution, speed_limit) + + # Flip the agents_raster along the horizontal axis. + speed_limit_raster = np.flip(speed_limit_raster, axis=0) + speed_limit_raster = np.ascontiguousarray( + speed_limit_raster, dtype=np.float32) + + # Normalize the speed limit raster. + speed_limit_raster /= max_speed_normalizer + return speed_limit_raster + + +def _get_extended_layer_coords( + ego_state: EgoState, + map_api: AbstractMap, + map_layer_name: SemanticMapLayer, + map_layer_geometry: str, + radius: float, + longitudinal_offset: float = 0.0, +) -> Tuple[List[npt.NDArray[np.float64]], List[str], List[Union[float, None]]]: + """ + Construct the map layer of the raster by converting vector map to raster map, based on the focus agent. + :param ego_state: the focus agent used for raster generating. + :param map_api: map api + :param map_layer_name: name of the vector map layer to create a raster from. + :param map_layer_geometry: geometric primitive of the vector map layer. i.e. either polygon or linestring. + :param radius: [m] the radius of the square raster map. + :return + object_coords: the list of 2d coordinates which represent the shape of the map. + lane_ids: the list of ids for the map objects. + speed_limits: the speed limit of each lane. A None value indicates that + speed limit is not available for that lane. + """ + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + ego_position = Point2D(virtual_center.x, virtual_center.y) + nearest_vector_map = _get_proximal_map_objects( + map_api=map_api, + layers=[map_layer_name], + point=ego_position, + radius=radius, + ) + + geometry = nearest_vector_map[map_layer_name] + + if len(geometry): + global_transform = np.linalg.inv(virtual_center.as_matrix()) + + # By default the map is right-oriented, this makes it top-oriented. + map_align_transform = R.from_euler( + 'z', 90, degrees=True).as_matrix().astype(np.float32) + transform = map_align_transform @ global_transform + + if map_layer_name in [SemanticMapLayer['BOUNDARIES']]: + _object_coords = _polyline_to_coords(geometry) + elif map_layer_geometry == 'polygon': + _object_coords = _polygon_to_coords(geometry) + elif map_layer_geometry == 'linestring': + # This is actually baseline_path.linestring + # TODO: make a better way to choose which to_coords to use. + _object_coords = _linestring_to_coords(geometry) + else: + raise RuntimeError( + f'Layer geometry {map_layer_geometry} type not supported') + + object_coords: List[npt.NDArray[np.float64]] = [ + np.vstack(coords).T for coords in _object_coords + ] + object_coords = [ + (transform @ _cartesian_to_projective_coords(coords).T).T[:, :2] + for coords in object_coords + ] + lane_speed_limits = [ + lane.speed_limit_mps if hasattr(lane, 'speed_limit_mps') else None + for lane in geometry + ] + lane_ids = [lane.id for lane in geometry] + else: + object_coords = [] + lane_ids = [] + lane_speed_limits = [] + + return object_coords, lane_ids, lane_speed_limits + + +def _wod_lane_to_3d_coords(geometry: List[PolylineMapObject]) -> List[Tuple[Tuple(float)]]: + """Get 3d coordinates from a wod lane polyline. + + :param map_feature: the map feature of wod lane. + :return: 3d coordinates of the polyline. + """ + all_coords = [] + for map_object in geometry: + if len(map_object.map_feature.lane.polyline) == 1: # handle only one point polyline situation + init_x, init_y, init_z = map_object.map_feature.lane.polyline[0].x, map_object.map_feature.lane.polyline[0].y, map_object.map_feature.lane.polyline[0].z + all_coords.append([(init_x, init_y, init_z), (init_x - 1e-3, init_y - 1e-3, init_z)]) + else: + points = [(point.x, point.y, point.z) for point in map_object.map_feature.lane.polyline] + for i in range(0, len(points), 10): + sub_points = points[i:i + 10] + if i + 11 >= len(points): + all_coords.append(tuple(points[i:])) + else: + all_coords.append(tuple(sub_points)) + return all_coords + + +def _get_wod_layer_3d_coords( + ego_state: EgoState, + map_api: AbstractMap, + map_layer_name: SemanticMapLayer, + map_layer_geometry: str, + radius: float, + longitudinal_offset: float = 0.0, +) -> Tuple[List[npt.NDArray[np.float64]], List[str], List[Union[float, None]]]: + """ + Construct the map layer of the raster by converting vector map to raster map, based on the focus agent. + :param ego_state: the focus agent used for raster generating. + :param map_api: map api + :param map_layer_name: name of the vector map layer to create a raster from. + :param map_layer_geometry: geometric primitive of the vector map layer. i.e. either polygon or linestring. + :param radius: [m] the radius of the square raster map. + :return + object_coords: the list of 2d coordinates which represent the shape of the map. + object_z: the z value of every point in the lane. + """ + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + ego_position = Point2D(virtual_center.x, virtual_center.y) + nearest_vector_map = _get_proximal_map_objects( + map_api=map_api, + layers=[map_layer_name], + point=ego_position, + radius=radius, + ) + + geometry = nearest_vector_map[map_layer_name] + + if len(geometry): + global_transform = np.linalg.inv(virtual_center.as_matrix()) + + # By default the map is right-oriented, this makes it top-oriented. + map_align_transform = R.from_euler( + 'z', 90, degrees=True).as_matrix().astype(np.float32) + transform = map_align_transform @ global_transform + + if map_layer_geometry == 'linestring': + # This is actually baseline_path.linestring + # TODO: make a better way to choose which to_coords to use. + _object_coords = _wod_lane_to_3d_coords(geometry) + else: + raise RuntimeError( + f'Layer geometry {map_layer_geometry} type not supported') + + object_coords: List[npt.NDArray[np.float64]] = [ + np.vstack(coords) for coords in _object_coords + ] + object_z = [coords[:,2] - 0.0 for coords in object_coords] + object_coords = [ + (transform @ _cartesian_to_projective_coords(coords[:,:2]).T).T[:, :2] + for coords in object_coords + ] + else: + object_coords = [] + object_z = [] + + return object_coords, object_z + + +def _get_proximal_map_objects(map_api: AbstractMap, point: Point2D, + radius: float, layers: List[SemanticMapLayer] + ) -> Dict[SemanticMapLayer, List[MapObject]]: + """Get nearby map objects within the given radius. + + `NuPlanMap.get_proximal_map_object()` does not work for certain layers ( + e.g, `DRIVABLE_AREA` and `BOUNDARIES`). + + This function is a workaround for that. + + :param map_api: map api. + :param point: center point. + :param radius: [m] radius. + :param layers: List of semantic map layers. + :return object_map: a dictionary of map objects. + """ + if all(layer in map_api.get_available_map_objects() for layer in layers): + return map_api.get_proximal_map_objects(point, radius, layers) + + x_min, x_max = point.x - radius, point.x + radius + y_min, y_max = point.y - radius, point.y + radius + patch = geom.box(x_min, y_min, x_max, y_max) + + object_map: Dict[SemanticMapLayer, List[MapObject]] = defaultdict(list) + + for layer in layers: + object_map[layer] = _get_proximity_map_object(map_api, patch, layer) + + return object_map + + +def _get_proximity_map_object(map_api: AbstractMap, patch: geom.Polygon, + layer: SemanticMapLayer) -> List[MapObject]: + """Gets nearby lanes within the given patch. + + Similar to `NuPlanMap.get_proximal_map_object()`, but only works for + `DRIVABLE_AREA` and `BOUNDARIES`. + + :param patch: The area to be checked. + :param layer: desired layer to check. + :return: A list of map objects. + """ + layer_df = map_api._get_vector_map_layer(layer) + map_object_ids = layer_df[layer_df['geometry'].intersects(patch)]['fid'] + if layer == SemanticMapLayer.DRIVABLE_AREA: + return [NuPlanPolygonMapObject(i, layer_df) for i in map_object_ids] + elif layer == SemanticMapLayer.BOUNDARIES: + return [NuPlanPolylineMapObject(i) for i in map_object_ids] + else: + raise ValueError(f"Unsupported layer: {layer}") + + +def get_traffic_light_dict_from_generator( + tl_generator: Generator[TrafficLightStatusData, None, None], +) -> Dict[TrafficLightStatusType, List[str]]: + """ + This function simply converts data format. From generator to dict. + :param tl_generator: the generator got from map_api. + :return: the dict for latter process. + """ + traffic_light_by_iter_list = list(tl_generator) + # 4 stands for 4 types: red, yellow, green and unknown. + traffic_light_by_iter_dict = { + TrafficLightStatusType(i_enum): [] + for i_enum in range(4) + } + for traffic_light_by_iter in traffic_light_by_iter_list: + traffic_light_by_iter_dict[traffic_light_by_iter.status].append( + traffic_light_by_iter.lane_connector_id) + return traffic_light_by_iter_dict + + +def _draw_polygon_image_by_array_colors( + image: npt.NDArray[np.float32], + object_coords: List[npt.NDArray[np.float64]], + radius: float, + resolution: float, + array_colors: npt.NDArray[np.uint8], + bit_shift: int = 12, +) -> npt.NDArray[np.float32]: + """ + Draw a map feature consisting of polygons using a list of its coordinates. + :param image: the raster map on which the map feature will be drawn + :param object_coords: the coordinates that represents the shape of the map feature. + :param radius: the radius of the square raster map. + :param resolution: [m] pixel size in meters. + :param color: color of the map feature. + :param bit_shift: bit shift of the polygon used in opencv. + :return: the resulting raster map with the map feature. + """ + assert len(object_coords) == len(array_colors) + if len(object_coords): + for coords, lane_color in zip(object_coords, array_colors): + index_coords = (radius + coords) / resolution + shifted_index_coords = (index_coords * 2**bit_shift).astype( + np.int64) + # Add int() before lane_color to address the cv2 error: color + # should be numeric + lane_color = int(lane_color) if np.isscalar(lane_color) else [ + int(item) for item in lane_color + ] # type: ignore + cv2.fillPoly( + image, + shifted_index_coords[None], + color=lane_color, + shift=bit_shift, + lineType=cv2.LINE_AA) + + return image + + +def get_lane_colors( + lane_ids: List[str], + traffic_light_connectors: Dict[TrafficLightStatusType, List[str]], +) -> npt.NDArray[np.unit8]: + """ + Get lane color from lane_connector color dict. + :param lane_ids: the list of lane_ids which we want the color for + :param traffic_light_connectors: our dict for traffic light information + :return: lane_colors array for input lanes. + """ + # Get a list indicating the color of each lane + lane_ids = [int(x) for x in lane_ids] + lane_ids = np.asarray(lane_ids) # type: ignore + lane_colors: npt.NDArray[np.uint8] = np.full( + (len(lane_ids), 3), + BASELINE_TL_COLOR[TrafficLightStatusType.UNKNOWN], + dtype=np.uint8) + + # If we have valid traffic light informaiton for intersection connectors + if len(traffic_light_connectors) > 0: + # here the for-loop is itered 4 times, for 4 types. + for tl_status in TrafficLightStatusType: + if tl_status != TrafficLightStatusType.UNKNOWN and len( + traffic_light_connectors[tl_status]) > 0: + # lanes_in_tl_status is a 0-1 array to indicate where to draw + # colors + lanes_in_tl_status = np.isin( + lane_ids, traffic_light_connectors[tl_status]) + # draw colors to where lanes_in_tl_status is 1 to get + # lane_colors + lane_colors[lanes_in_tl_status] = BASELINE_TL_COLOR[tl_status] + return lane_colors + +def draw_arrow_triangle(image, x, y, heading, length, base_width, filled_color): + """ + Draw a filled, arrow-like triangle on an image to represent direction. + + :param image: The image to draw on + :param x: The x-coordinate of the triangle's base center + :param y: The y-coordinate of the triangle's base center + :param heading: The heading angle of the triangle in degrees + :param length: The length of the triangle (from base to tip) + :param base_width: The width of the triangle's base + """ + # Convert heading to radians + heading_rad = np.deg2rad(heading) + + # Calculate the triangle's vertices + tip = (int(x + length * np.cos(heading_rad)), int(y + length * np.sin(heading_rad))) + base_left = (int(x - (base_width / 2) * np.sin(heading_rad)), int(y + (base_width / 2) * np.cos(heading_rad))) + base_right = (int(x + (base_width / 2) * np.sin(heading_rad)), int(y - (base_width / 2) * np.cos(heading_rad))) + + # Combine the points into an array + triangle_cnt = np.array([tip, base_left, base_right]) + + # Draw the filled triangle + cv2.fillPoly(image, [triangle_cnt], filled_color) # Blue color in BGR + return image + + +def draw_traffic_light_at_connector_start( + traffic_light_raster, + lane_ids, + baseline_paths_coords, + radius, + resolution, + traffic_light_connectors +) -> npt.NDArray[np.unit8]: + """ + Get lane color from lane_connector color dict. + :param lane_ids: the list of lane_ids which we want the color for + :param traffic_light_connectors: our dict for traffic light information + :return: lane_colors array for input lanes. + """ + # Get a list indicating the color of each lane + lane_ids = [int(x) for x in lane_ids] + traffic_index = 1 + for traffic_light_status, traffic_lane_ids in traffic_light_connectors.items(): + # if TrafficLightStatusType.UNKNOWN != traffic_light_status: + for traffic_lane_id in traffic_lane_ids: + if traffic_lane_id in lane_ids: + lane_index = lane_ids.index(traffic_lane_id) + lane_coords = baseline_paths_coords[lane_index] + traffic_light_raster[...,0] = _draw_linestring_image( + image=traffic_light_raster[...,0], + object_coords=[lane_coords], + radius=radius, + resolution=resolution, + baseline_path_thickness=1, + lane_colors=[traffic_index], + ) + heading = np.arctan2(lane_coords[1][1] - lane_coords[0][1], lane_coords[1][0] - lane_coords[0][0]) + x = round((radius + lane_coords[0][0]) / resolution) + y = round((radius + lane_coords[0][1]) / resolution) + traffic_light_raster = cv2.circle(traffic_light_raster, (int(x), int(y)), 4, traffic_index, thickness=-1) + traffic_index += 1 + return traffic_light_raster.squeeze(-1) + +def get_traffic_light_circle_raster( + ego_state: EgoState, + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + traffic_light_connectors: Dict[TrafficLightStatusType, List[str]], + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}') + + radius = (x_range[1] - x_range[0]) / 2 + + traffic_light_raster: npt.NDArray[np.float32] = np.zeros((*raster_shape, 1), dtype=np.float32) + + baseline_paths_coords = [] + lane_ids = [] + for map_features in ['LANE', 'LANE_CONNECTOR']: + baseline_paths_coord, lane_id = _get_layer_coords( + ego_state=ego_state, + map_api=map_api, + map_layer_name=SemanticMapLayer[map_features], + map_layer_geometry='linestring', + radius=radius, + longitudinal_offset=longitudinal_offset, + ) + baseline_paths_coords += baseline_paths_coord + lane_ids += lane_id + + # get lane_colors for the two type. + traffic_light_raster = draw_traffic_light_at_connector_start( + traffic_light_raster, + lane_ids, + baseline_paths_coords, + radius, + resolution, + traffic_light_connectors) + traffic_light_raster = np.flip(traffic_light_raster, axis=0) + traffic_light_raster = np.ascontiguousarray( + traffic_light_raster, dtype=np.float32) + return traffic_light_raster + + + +def get_traffic_light_raster( + ego_state: EgoState, + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + traffic_light_connectors: Dict[TrafficLightStatusType, List[str]], + route_roadblock_ids: List[str], + draw_by_polygon_tl: bool = True, + draw_ego_route_separately_tl: bool = True, + baseline_path_thickness: int = 1, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Mainly this function help draw traffic light color onto baseline path. + Construct the baseline paths layer by converting vector map to raster map. + This function is for agents raster model, it has 3 channels for baseline path. + Support polygon/linestring, support self/other different color. + :param focus_agent: agent state representing ego. + :param map_api: map api + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param traffic_light_connectors: a dict mapping tl status type to a list of lane ids in this status. + :param route_roadblock_ids: route block id of the current map. + :param draw_by_polygon_tl: whether to build the raster map as polygon or not. If not, build as linestring. + :param draw_ego_route_separately_tl: whether to extract self-route traffic light by route block ids. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :param longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + :return baseline_paths_raster: the constructed baseline paths layer. + """ + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}') + + radius = (x_range[1] - x_range[0]) / 2 + + other_paths_raster: npt.NDArray[np.float32] = np.zeros((*raster_shape, 3), + dtype=np.float32) + self_paths_raster: npt.NDArray[np.float32] = np.zeros((*raster_shape, 3), + dtype=np.float32) + + # if draw_ego_route_separately_tl, draw a 6-channel pic; if not, draw a + # 3-channel one + if draw_ego_route_separately_tl: + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + (*raster_shape, 6), dtype=np.float32) + else: + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + (*raster_shape, 3), dtype=np.float32) + + for map_features in ['LANE', 'LANE_CONNECTOR']: + baseline_paths_coords, lane_ids, _ = _get_extended_layer_coords( + ego_state=ego_state, + map_api=map_api, + map_layer_name=SemanticMapLayer[map_features], + map_layer_geometry='polygon', + radius=radius, + longitudinal_offset=longitudinal_offset, + ) + + self_lane_ids = [] + self_coords = [] + other_lane_ids = [] + other_coords = [] + # split lane_ids and baseline_paths_coords into two parts: self_ and + # other_ + for index in range(len(lane_ids)): + lane_id = lane_ids[index] + coord = baseline_paths_coords[index] + if map_features == 'LANE': + cnt_lane = map_api._get_lane(lane_id) + elif map_features == 'LANE_CONNECTOR': + cnt_lane = map_api._get_lane_connector(lane_id) + else: + raise TypeError("Can't do for none lane type") + cnt_block_id = cnt_lane.get_roadblock_id() + # judge whether lane_ids and baseline_paths_coords are in route_roadblock_ids, + # to see if it's self_ or other_ + if cnt_block_id in route_roadblock_ids: + self_lane_ids.append(lane_id) + self_coords.append(coord) + else: + other_lane_ids.append(lane_id) + other_coords.append(coord) + # get lane_colors for the two type. + other_lane_colors = get_lane_colors(other_lane_ids, + traffic_light_connectors) + self_lane_colors = get_lane_colors(self_lane_ids, + traffic_light_connectors) + + # for both draw_ego_route_separately_tl is true and false, we make the raster by two parts. + # But if draw_ego_route_separately_tl is true, we use different colors. + if draw_by_polygon_tl: + # draw twice with different color, one for self and one for other + # for other + other_paths_raster = _draw_polygon_image_by_array_colors( + other_paths_raster, other_coords, radius, resolution, + other_lane_colors) + + # for self + self_paths_raster = _draw_polygon_image_by_array_colors( + self_paths_raster, self_coords, radius, resolution, + self_lane_colors) + + else: # default as linestring + # draw for other + other_paths_raster = _draw_linestring_image( + image=other_paths_raster, + object_coords=other_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + lane_colors=other_lane_colors, + ) + # draw for self + self_paths_raster = _draw_linestring_image( + image=self_paths_raster, + object_coords=self_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + lane_colors=self_lane_colors, + ) + + # if self, draw a 6-channel with different color; if not, draw a 3-channel + # with same color and overriden style + if draw_ego_route_separately_tl: + baseline_paths_raster = np.concatenate( + (other_paths_raster, self_paths_raster), axis=2) + else: + # Convert images to grayscale for bitwise operations + gray1 = cv2.cvtColor(other_paths_raster, cv2.COLOR_BGR2GRAY) + gray2 = cv2.cvtColor(self_paths_raster, cv2.COLOR_BGR2GRAY) + + # Combine the two images using bitwise operations + mask = cv2.bitwise_or(gray1, gray2) + baseline_paths_raster = cv2.bitwise_and( + other_paths_raster, self_paths_raster, mask=mask) + + # Flip the agents_raster along the horizontal axis. + baseline_paths_raster = np.flip(baseline_paths_raster, axis=0) + baseline_paths_raster = np.ascontiguousarray( + baseline_paths_raster, dtype=np.float32) + return baseline_paths_raster + + +def get_wod_roadmap_raster( + focus_agent: AgentState, + map_api: AbstractMap, + map_features: Dict[str, int], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + linestring_thickness: int = 1, +) -> npt.NDArray[np.float32]: + """ + Construct the map layer of the raster by converting vector map to raster map. + :param focus_agent: agent state representing ego. + :param map_api: map api. + :param map_features: name of map features to be drawn and its color for encoding. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :return roadmap_raster: the constructed map raster layer. + """ + # Assume the raster has a square shape. + assert (x_range[1] - x_range[0]) == ( + y_range[1] - + y_range[0]), f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}' + + radius = (x_range[1] - x_range[0]) / 2 + roadmap_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for feature_name, feature_color in map_features.items(): + if feature_name in ["BASELINE_PATHS", "EXTENDED_PUDO"]: + coords, line_ids = _get_layer_coords( + focus_agent, map_api, SemanticMapLayer[feature_name], 'linestring', radius) + lane_colors: npt.NDArray[np.uint8] = np.ones( + len(line_ids)).astype(np.uint8) + roadmap_raster = _draw_linestring_image( + image=roadmap_raster, + object_coords=coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=linestring_thickness, + lane_colors=lane_colors) + else: + coords, _, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer[feature_name], + 'polygon', radius) + roadmap_raster = _draw_polygon_image( + roadmap_raster, coords, radius, resolution, feature_color) + + # Flip the agents_raster along the horizontal axis. + roadmap_raster = np.flip(roadmap_raster, axis=0) + roadmap_raster = np.ascontiguousarray(roadmap_raster, dtype=np.float32) + + return roadmap_raster + + +def get_wod_baseline_paths_raster( + ego_state: AgentState, + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + baseline_path_thickness: int = 1, +) -> npt.NDArray[np.float32]: + """ + Construct the baseline paths layer by converting vector map to raster map. + This funciton is for ego raster model, the baselin path only has one channel. + :param ego_state: SE2 state of ego. + :param map_api: map api + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :return baseline_paths_raster: the constructed baseline paths layer. + """ + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}') + + radius = (x_range[1] - x_range[0]) / 2 + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for map_features in ['LANE']: + baseline_paths_coords, lane_ids, _ = _get_extended_layer_coords( + ego_state=ego_state, + map_api=map_api, + map_layer_name=SemanticMapLayer[map_features], + map_layer_geometry='linestring', + radius=radius, + ) + lane_colors: npt.NDArray[np.uint8] = np.ones(len(lane_ids)).astype( + np.uint8) + baseline_paths_raster = _draw_linestring_image( + image=baseline_paths_raster, + object_coords=baseline_paths_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + lane_colors=lane_colors, + ) + + # Flip the agents_raster along the horizontal axis. + baseline_paths_raster = np.flip(baseline_paths_raster, axis=0) + baseline_paths_raster = np.ascontiguousarray( + baseline_paths_raster, dtype=np.float32) + return baseline_paths_raster + + +def get_wod_baseline_z_raster( + ego_state: AgentState, + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + baseline_path_thickness: int = 1, +) -> npt.NDArray[np.float32]: + """ + Construct the baseline paths layer by converting vector map to raster map. + This funciton is for ego raster model, the baselin path only has one channel. + :param ego_state: SE2 state of ego. + :param map_api: map api + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :return baseline_paths_raster: the constructed baseline paths layer. + """ + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}') + + radius = (x_range[1] - x_range[0]) / 2 + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for map_feature in ['LANE']: + baseline_paths_coords, baseline_path_z = _get_wod_layer_3d_coords( + ego_state=ego_state, + map_api=map_api, + map_layer_name=SemanticMapLayer[map_feature], + map_layer_geometry='linestring', + radius=radius, + ) + + lane_colors: npt.NDArray[np.uint8] = np.zeros(len(baseline_paths_coords)).astype( + np.uint8) + for i in range(len(baseline_paths_coords)): + lane_colors[i] = int(np.clip((np.mean(baseline_path_z[i]) / 5 * 128) + 128, 0, 255)) + + baseline_paths_raster = _draw_linestring_image( + image=baseline_paths_raster, + object_coords=baseline_paths_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + lane_colors=lane_colors, + ) + + # Flip the agents_raster along the horizontal axis. + baseline_paths_raster = np.flip(baseline_paths_raster, axis=0) + baseline_paths_raster = np.ascontiguousarray( + baseline_paths_raster, dtype=np.float32) + return baseline_paths_raster + + +def get_agents_raster( + ego_state: EgoState, + tracked_objects: List[TrackedObjects], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + polygon_bit_shift: int = 9, + with_instance_mask: bool = False, + longitudinal_offset: float = 0.0, +): + """ + Construct the agents layer of the raster by transforming all detected boxes around the agent + and creating polygons of them in a raster grid, and also can create the corresponding instance mask. + + :param ego_state: SE2 state of ego. + :param tracked_objects: list of TrackedObjects. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param polygon_bit_shift: bit shift of the polygon used in opencv. + :param with_instance_mask: whether to return instance mask. + :param longitudinal_offset: [m] longitudinal offset of the virtual center. + :return: constructed agents raster layer. + """ + xmin, xmax = x_range + ymin, ymax = y_range + width, height = raster_shape + + # ego_to_global = ego_state.rear_axle.as_matrix() + radius = (x_range[1] - x_range[0]) / 2 + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + + ego_to_global = virtual_center.as_matrix() + global_to_ego = np.linalg.inv(ego_to_global) + + north_aligned_transform = StateSE2(0, 0, np.pi / 2).as_matrix() + agents_raster = np.zeros(raster_shape, dtype=np.float32) + if with_instance_mask: + instances_raster = np.zeros(raster_shape, dtype=np.float32) + + for tracked_object in tracked_objects: + # Transform the box relative to agent. + raster_object_matrix = north_aligned_transform @ global_to_ego @ tracked_object.center.as_matrix( + ) + raster_object_pose = StateSE2.from_matrix(raster_object_matrix) + # Filter out boxes outside the raster. + valid_x = x_range[0] < raster_object_pose.x < x_range[1] + valid_y = y_range[0] < raster_object_pose.y < y_range[1] + if not (valid_x and valid_y): + continue + + # Get the 2D coordinate of the detected agents. + raster_oriented_box = OrientedBox( + raster_object_pose, tracked_object.box.length, + tracked_object.box.width, tracked_object.box.height) + box_bottom_corners = raster_oriented_box.all_corners() + x_corners = np.asarray( + [corner.x for corner in box_bottom_corners]) # type: ignore + y_corners = np.asarray( + [corner.y for corner in box_bottom_corners]) # type: ignore + + # Discretize + y_corners = (y_corners - ymin) / (ymax - ymin) * height # type: ignore + x_corners = (x_corners - xmin) / (xmax - xmin) * width # type: ignore + + box_2d_coords = np.stack([x_corners, y_corners], + axis=1) # type: ignore + box_2d_coords = np.expand_dims(box_2d_coords, axis=0) + + # Draw the box as a filled polygon on the raster layer. + value = tracked_object.tracked_object_type.value + 1 + box_2d_coords = (box_2d_coords * 2**polygon_bit_shift).astype(np.int32) + cv2.fillPoly( + agents_raster, + box_2d_coords, + color=value, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + if with_instance_mask: + value = tracked_object.metadata.track_id + cv2.fillPoly( + instances_raster, + box_2d_coords, + color=value, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + + # Flip the agents_raster along the horizontal axis. + agents_raster = np.asarray(agents_raster) + agents_raster = np.flip(agents_raster, axis=0) + agents_raster = np.ascontiguousarray(agents_raster, dtype=np.float32) + + if with_instance_mask: + instances_raster = np.asarray(instances_raster) + instances_raster = np.flip(instances_raster, axis=0) + instances_raster = np.ascontiguousarray( + instances_raster, dtype=np.uint16) + return agents_raster, instances_raster + return agents_raster + + +def calculate_tilt_angle( + point_a: Tuple[float, float], + point_b: Tuple[float, float], +) -> float: + """ + Calculate the tilt angle for 2 given points. + :param point_a: the first point to be calculate. + :param point_b: the second point to be calculate. + :return: the resulting tilt angle in rad. + """ + x1, y1 = point_a + x2, y2 = point_b + + # Check for the same points + if x1 == x2 and y1 == y2: + return 0.0 + # raise ValueError("The points are the same, tilt angle cannot be calculated.") + + # Calculate the difference in x and y coordinates + dx = x2 - x1 + dy = y2 - y1 + + # Calculate tilt angle in radians + tilt_angle = math.atan2(dy, dx) + + return tilt_angle + + +def _draw_linestring_image_polar_direction( + image: npt.NDArray[np.float32], + object_coords: npt.NDArray[np.float64], + radius: float, + resolution: float, + baseline_path_thickness: int, + bit_shift: int = 13, +) -> npt.NDArray[np.float32]: + """ + Draw a map feature consisting of linestring using a list of its coordinates. + :param image: the raster map on which the map feature will be drawn + :param object_coords: the coordinates that represents the shape of the map feature. + :param radius: the radius of the square raster map. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :param bit_shift: bit shift of the polylines used in opencv. + :return: the resulting raster map with the map feature. + """ + index_coords = (radius + object_coords) / resolution + points = (index_coords * 2**bit_shift).astype(np.int64) + num_segments = len(points) - 1 + + for i in range(num_segments): + pt1 = tuple(points[i]) + pt2 = tuple(points[i + 1]) + + # Calculate the color for the current segment + segment_color = calculate_tilt_angle( + pt1, pt2) + 2 * np.pi # result ranging from pi to 3pi + + # Draw the segment + cv2.line( + image, + pt1, + pt2, + segment_color, + baseline_path_thickness, + lineType=cv2.LINE_AA, + shift=bit_shift) + return image + + +def align_edges( + edges: Union[List[NuPlanLane], List[NuPlanRoadBlock]], + ids: List[str], +) -> Union[Dict[NuPlanLane, int], Dict[NuPlanRoadBlock, int]]: + """ + Align the edges in an order of layer. + :param point_a: the edges to be calculated. + :param point_b: the ids of the edges. + :return: a dict of aligned edges by incoming edges and outgoing edges. + """ + # Create a dictionary for easy edge lookup by ID + edge_dict = {edge.id: edge for edge in edges if edge.id in ids} + + # Filter the edges to include only those in the ids list + for edge_id, edge in edge_dict.items(): + edge.incoming_edges = [e for e in edge.incoming_edges if e.id in ids] + edge.outgoing_edges = [e for e in edge.outgoing_edges if e.id in ids] + edge_dict[edge_id] = edge + + # Initialize layer assignment + layers = {} + + # BFS for layer assignment + def assign_layers(start_edge): + queue = deque([(start_edge, 0)]) + + while queue: + edge, layer = queue.popleft() + + if edge.id in layers: + layers[edge.id] = max(layer, layers[edge.id]) + continue + + if edge.id not in layers: # or layer < layers[edge.id] + layers[edge.id] = layer + for next_edge in edge.outgoing_edges: + # can not use next_edge directly, because only in the dict its + # attributes incoming and outgoing are pruned + queue.append((edge_dict[next_edge.id], layer + 1)) + + # Find all nodes with no incoming edges and start BFS from them + no_incoming = [ + edge for edge in edge_dict.values() if not edge.incoming_edges + ] + for edge in no_incoming: + assign_layers(edge) + + # If there are still nodes with no layer assigned, run BFS on them + for edge in edge_dict.values(): + if edge.id not in layers: + assign_layers(edge) + + return layers + + +def _draw_linestring_image_gradient( + image: npt.NDArray[np.float32], + object_coords: npt.NDArray[np.float64], + radius: float, + resolution: float, + baseline_path_thickness: int, + color_range: tuple[npt.NDArray[np.float32]], + bit_shift: int = 13, +) -> npt.NDArray[np.float32]: + """ + Draw a map feature consisting of linestring using a list of its coordinates. + :param image: the raster map on which the map feature will be drawn + :param object_coords: the coordinates that represents the shape of the map feature. + :param radius: the radius of the square raster map. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :param color_range: the range of color used for this line. + :param bit_shift: bit shift of the polylines used in opencv. + :return: the resulting raster map with the map feature. + """ + index_coords = (radius + object_coords) / resolution + points = (index_coords * 2**bit_shift).astype(np.int64) + num_segments = len(points) - 1 + + for i in range(num_segments): + pt1 = tuple(points[i]) + pt2 = tuple(points[i + 1]) + + # Calculate the color for the current segment + if num_segments > 1: + t = i / (num_segments - 1) + else: + t = 0 + segment_color = color_range[0] * (1 - t) + color_range[1] * t + + # Draw the segment + cv2.line( + image, + pt1, + pt2, + segment_color, + baseline_path_thickness, + lineType=cv2.LINE_AA, + shift=bit_shift) + return image + + +def get_gradient_lane_raster( + focus_agent: EgoState, + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + baseline_path_thickness: int = 1, + longitudinal_offset: Optional[float] = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct the baseline paths layer by converting vector map to raster map. + This funciton is for lane raster. Draw the lane raster so that the color gradient indicates the direction. + :param focus_agent: The state of the agent representing the ego vehicle. + :param map_api: map api + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :param longitudinal_offset: [m] the longitudinal offset of the baseline path. + :return baseline_paths_raster: the constructed baseline paths layer. + """ + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}') + + radius = (x_range[1] - x_range[0]) / 2 + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + lane_coords, lane_ids, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer['LANE'], 'linestring', radius, + longitudinal_offset) + + lane_connector_coords, lane_connector_ids, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer['LANE_CONNECTOR'], 'linestring', + radius, longitudinal_offset) + + coords = lane_coords + lane_connector_coords + ids = lane_ids + lane_connector_ids + + edges = [ + map_api._get_lane(lane_id) + if lane_id in lane_ids else map_api._get_lane_connector(lane_id) + for lane_id in ids + ] + edge_dict = {edge.id: edge for edge in edges if edge.id in ids} + layer_dict = align_edges(edges, ids) + assert len(ids) == len(edges) == len(layer_dict) == len(edge_dict) + + assert min(layer_dict.values()) == 0 + # +1 because layer is 0-index, +1 because n+1 colors to form a range for n targets + colors = np.linspace(0.0001, 0.9999, + max(layer_dict.values()) + 2).astype(np.float32) + for lane_id, layer_index in layer_dict.items(): + index = ids.index(lane_id) + drawing = coords[index] + color_range = colors[layer_index:layer_index + 2] + baseline_paths_raster = _draw_linestring_image_gradient( + image=baseline_paths_raster, + object_coords=drawing, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + color_range=color_range, + ) + + # Flip the agents_raster along the horizontal axis. + baseline_paths_raster = np.flip(baseline_paths_raster, axis=0) + baseline_paths_raster = np.ascontiguousarray( + baseline_paths_raster, dtype=np.float32) + return baseline_paths_raster + + +def get_polor_direction_lane_raster( + focus_agent: EgoState, + map_api: AbstractMap, + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + baseline_path_thickness: int = 1, + longitudinal_offset: Optional[float] = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct the baseline paths layer by converting vector map to raster map. + This funciton is for lane raster, the color indicates the rad value of the yaw of each position of the lane. + :param focus_agent: The state of the agent representing the ego vehicle. + :param map_api: map api + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :param longitudinal_offset: [m] the longitudinal offset of the baseline path. + :return baseline_paths_raster: the constructed baseline paths layer. + """ + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}') + + radius = (x_range[1] - x_range[0]) / 2 + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + lane_coords, lane_ids, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer['LANE'], 'linestring', radius, + longitudinal_offset) + + lane_connector_coords, lane_connector_ids, _ = _get_extended_layer_coords( + focus_agent, map_api, SemanticMapLayer['LANE_CONNECTOR'], 'linestring', + radius, longitudinal_offset) + + coords = lane_coords + lane_connector_coords + ids = lane_ids + lane_connector_ids + + for coord, id in zip(coords, ids): + baseline_paths_raster = _draw_linestring_image_polar_direction( + image=baseline_paths_raster, + object_coords=coord, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + ) + + # Flip the agents_raster along the horizontal axis. + baseline_paths_raster = np.flip(baseline_paths_raster, axis=0) + baseline_paths_raster = np.ascontiguousarray( + baseline_paths_raster, dtype=np.float32) + return baseline_paths_raster + + +def rotate_dx_dy_in_complex_space( + input_raster: npt.NDArray[np.float32], + phi: float, +) -> npt.NDArray[np.float32]: + """ + :param inp_raster: input raster to be rotated + :param phi: the angle to be rotated. counterclockwise, in radians. + """ + return_raster = np.zeros(input_raster.shape) + cos_phi = np.cos(phi) + sin_phi = np.sin(phi) + return_raster[0] = input_raster[0] * cos_phi - input_raster[1] * sin_phi + return_raster[1] = input_raster[1] * cos_phi + input_raster[0] * sin_phi + return return_raster + + +def rotate_tilt_angle( + input_raster: npt.NDArray[np.float32], + phi: float, +): + """ + Align the values after rotating a raster of tilt angle, and ensure the range is (pi,3pi) and 0 for non-occupancy + :param inp_raster: input raster to be rotated + :param phi: the angle to be rotated. counterclockwise, in radians. + """ + non_zero_mask = input_raster != 0.0 + # only modify values in non_zero_mask + input_raster[non_zero_mask] = (input_raster[non_zero_mask] + phi) % ( + 2 * np.pi) + np.pi + return input_raster + + +def get_mission_goal_raster( + target_relative_pose: npt.NDArray[np.float32], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[float, float], + draw_at_bound_each: bool, +) -> npt.NDArray[np.float32]: + """ + Construct mission goal of the current scenario. + :param future_trajectory: future trajectory of ego vehicle. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param draw_at_bound_each: whether to draw the mission goal at the boundary of each frame. + :return: constructed mission goal raster layer. + """ + target_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + xmin, xmax = x_range + ymin, ymax = y_range + width, height = raster_shape + + # Discretize + target_y = (target_relative_pose[-1, 0] - ymin) / \ + (ymax - ymin) * height # type: ignore + target_x = (target_relative_pose[-1, 1] - xmin) / \ + (xmax - xmin) * width # type: ignore + + target_x, target_y = target_x.astype(np.int64), target_y.astype(np.int64) + + if draw_at_bound_each: + target_x = np.clip(target_x, 0, height - 1) + target_y = np.clip(target_y, 0, width - 1) + cv2.circle( + target_raster, (target_x, target_y), + radius=0, + color=1.0, + thickness=-1) + else: + if 0 <= target_x < height and 0 <= target_y < width: + cv2.circle( + target_raster, (target_x, target_y), + radius=0, + color=1.0, + thickness=-1) + + target_raster = np.flip(target_raster, axis=0) + target_raster = np.ascontiguousarray(target_raster, dtype=np.float32) + return target_raster + + +def _get_layer_coords( + ego_state: Union[AgentState, EgoState], + map_api: AbstractMap, + map_layer_name: SemanticMapLayer, + map_layer_geometry: str, + radius: float, + longitudinal_offset: float = 0.0, +) -> Tuple[List[npt.NDArray[np.float64]], List[str]]: + """ + Construct the map layer of the raster by converting vector map to raster map, based on the focus agent. + :param ego_state (AgentState, EgoState): current state of focus agent. + :param map_api: map api + :param map_layer_name: name of the vector map layer to create a raster from. + :param map_layer_geometry: geometric primitive of the vector map layer. i.e. either polygon or linestring. + :param radius: [m] the radius of the square raster map. + :param longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + :return + object_coords: the list of 2d coordinates which represent the shape of the map. + lane_ids: the list of ids for the map objects. + """ + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + ego_position = Point2D(virtual_center.x, virtual_center.y) + nearest_vector_map = map_api.get_proximal_map_objects( + layers=[map_layer_name], + point=ego_position, + radius=radius, + ) + geometry = nearest_vector_map[map_layer_name] + + if len(geometry): + global_transform = np.linalg.inv(virtual_center.as_matrix()) + + # By default the map is right-oriented, this makes it top-oriented. + map_align_transform = R.from_euler( + 'z', 90, degrees=True).as_matrix().astype(np.float32) + transform = map_align_transform @ global_transform + + if map_layer_geometry == 'polygon': + _object_coords = _polygon_to_coords(geometry) + elif map_layer_geometry == 'linestring': + _object_coords = _linestring_to_coords(geometry) + else: + raise RuntimeError( + f'Layer geometry {map_layer_geometry} type not supported') + + object_coords: List[npt.NDArray[np.float64]] = [ + np.vstack(coords).T for coords in _object_coords + ] + object_coords = [ + (transform @ _cartesian_to_projective_coords(coords).T).T[:, :2] + for coords in object_coords + ] + + lane_ids = [lane.id for lane in geometry] + else: + object_coords = [] + lane_ids = [] + + return object_coords, lane_ids + + +def get_baseline_paths_raster( + ego_state: Union[AgentState, EgoState], + map_api: AbstractMap, + map_feature_names: List[str], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + baseline_path_thickness: int = 1, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct the baseline paths layer by converting vector map to raster map. + This funciton is for ego raster model, the baselin path only has one channel. + :param focus_agent (AgentState, EgoState): current state of focus agent. + :param map_api: map api + :param map_feature_names: name of the vector map layer to create a raster from. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param baseline_path_thickness: [pixel] the thickness of polylines used in opencv. + :param longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + :return baseline_paths_raster: the constructed baseline paths layer. + """ + # Assume the raster has a square shape. + if (x_range[1] - x_range[0]) != (y_range[1] - y_range[0]): + raise ValueError( + f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}' + ) + + radius = (x_range[1] - x_range[0]) / 2 + baseline_paths_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for map_features in map_feature_names: + baseline_paths_coords, lane_ids = _get_layer_coords( + ego_state=ego_state, + map_api=map_api, + map_layer_name=SemanticMapLayer[map_features], + map_layer_geometry='linestring', + radius=radius, + longitudinal_offset=longitudinal_offset, + ) + lane_colors: npt.NDArray[np.uint8] = np.ones(len(lane_ids)).astype( + np.uint8) + baseline_paths_raster = _draw_linestring_image( + image=baseline_paths_raster, + object_coords=baseline_paths_coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=baseline_path_thickness, + lane_colors=lane_colors, + ) + + # Flip the agents_raster along the horizontal axis. + baseline_paths_raster = np.flip(baseline_paths_raster, axis=0) + baseline_paths_raster = np.ascontiguousarray( + baseline_paths_raster, dtype=np.float32) + return baseline_paths_raster + + +def get_p3c_roadmap_raster( + focus_agent: Union[AgentState, EgoState], + map_api: AbstractMap, + map_features: Dict[str, int], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + linestring_thickness: int = 1, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct the map layer of the raster by converting vector map to raster map. + :param focus_agent (AgentState, EgoState): current state of agent. + :param map_api: map api. + :param map_features: name of map features to be drawn and its color for encoding. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param linestring_thickness: thickness of linestring + :param longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + :return roadmap_raster: the constructed map raster layer. + """ + # Assume the raster has a square shape. + assert (x_range[1] - x_range[0]) == ( + y_range[1] - + y_range[0]), f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}' + + radius = (x_range[1] - x_range[0]) / 2 + roadmap_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for feature_name, feature_color in map_features.items(): + if feature_name in ['BOUNDARIES']: + coords, _ = _get_layer_coords( + focus_agent, map_api, SemanticMapLayer[feature_name], + 'linestring', radius, longitudinal_offset) + roadmap_raster = _draw_linestring_image( + image=roadmap_raster, + object_coords=coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=linestring_thickness, + lane_colors=[feature_color for i in range(len(coords))]) + elif feature_name in ['LANE_EDGE']: + coords, colors = get_lane_edge_layer_coords( + focus_agent, map_api, radius, longitudinal_offset) + roadmap_raster = _draw_linestring_image( + image=roadmap_raster, + object_coords=coords, + radius=radius, + resolution=resolution, + baseline_path_thickness=linestring_thickness, + lane_colors=colors) + + else: + coords, _ = _get_layer_coords( + focus_agent, map_api, SemanticMapLayer[feature_name], + 'polygon', radius, longitudinal_offset) + roadmap_raster = _draw_polygon_image( + image=roadmap_raster, + object_coords=coords, + radius=radius, + resolution=resolution, + color=feature_color) + + roadmap_raster = np.flip(roadmap_raster, axis=0) + roadmap_raster = np.ascontiguousarray(roadmap_raster, dtype=np.float32) + return roadmap_raster + + +def get_p3c_goal_raster(ego_state: Union[AgentState, EgoState], + coords: List[float], + x_range: Tuple[float, float], + raster_shape: Tuple[int, int], + longitudinal_offset: float = 0.0, + polygon_bit_shift: int = 9, + color_value: int = 1): + """ + Construct the map layer of the raster by converting vector map to raster map. + + Args: + focus_agent (AgentState, EgoState): current state of agent. + coords (List[float]): coordinates of goal + x_range (Tuple[float, float]): [m] min and max range from the edges of the grid in x direction. + raster_shape (Tuple[int, int]): shape of the target raster. + longitudinal_offset (float, optional): [-0.5, 0.5] longitudinal offset of ego center. Defaults to 0.0. + polygon_bit_shift (int, optional): bit shift of the polygon used in opencv. Defaults to 9. + color_value (int, optional): pixel value of goal. Defaults to 1. + + Returns: + goal raster: the constructed goal raster layer. + """ + radius = (x_range[1] - x_range[0]) / 2 + goal_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + global_transform = np.linalg.inv(virtual_center.as_matrix()) + north_aligned_transform = StateSE2(0, 0, np.pi / 2).as_matrix() + # map_align_transform = R.from_euler('z', 90, degrees=True).as_matrix().astype(np.float32) + transform = north_aligned_transform @ global_transform + trans_coords = StateSE2.from_matrix(transform @ coords.as_matrix()) + length, width, height = 2, 2, 2 + raster_oriented_box = OrientedBox(trans_coords, length, width, height) + box_bottom_corners = raster_oriented_box.all_corners() + x_corners = np.asarray( + [corner.x for corner in box_bottom_corners]) # type: ignore + y_corners = np.asarray( + [corner.y for corner in box_bottom_corners]) # type: ignore + + x_corners = (x_corners + radius) / (2 * radius) * raster_shape[0] + y_corners = (y_corners + radius) / (2 * radius) * raster_shape[1] + + box_2d_coords = np.stack([x_corners, y_corners], axis=1) # type: ignore + box_2d_coords = np.expand_dims(box_2d_coords, axis=0) + + # Draw the box as a filled polygon on the raster layer. + box_2d_coords = (box_2d_coords * 2**polygon_bit_shift).astype(np.int32) + + cv2.fillPoly( + goal_raster, + box_2d_coords, + color=color_value, + shift=polygon_bit_shift, + lineType=cv2.LINE_AA) + goal_raster = np.flip(goal_raster, axis=0) + goal_raster = np.ascontiguousarray(goal_raster, dtype=np.float32) + + return goal_raster + + +def get_lane_edge_layer_coords( + ego_state: Union[AgentState, EgoState], + map_api: AbstractMap, + radius: float, + longitudinal_offset: float = 0.0, +) -> Tuple[List[npt.NDArray[np.float64]], List[str]]: + """ + Construct the lane edge layer of the raster by converting vector map to raster map, based on the agent. + :param ego_state (AgentState, EgoState): current state of agent. + :param map_api: map api + :param radius: [m] the radius of the square raster map. + :param longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center + :return + object_coords: the list of 2d coordinates which represent the shape of the map. + lane_ids: the list of ids for the map objects. + """ + type_dict = {0: 3, 2: 3, 512: 8} + virtual_center = calc_raster_center(ego_state, radius, longitudinal_offset) + ego_position = Point2D(virtual_center.x, virtual_center.y) + + nearest_vector_map = map_api.get_proximal_map_objects( + layers=[SemanticMapLayer.LANE], + point=ego_position, + radius=radius, + ) + geometry = nearest_vector_map[SemanticMapLayer.LANE] + + if len(geometry): + global_transform = np.linalg.inv(virtual_center.as_matrix()) + + # By default the map is right-oriented, this makes it top-oriented. + map_align_transform = R.from_euler( + 'z', 90, degrees=True).as_matrix().astype(np.float32) + transform = map_align_transform @ global_transform + origin_object_coords = [] + _coords_type = [] + for element in geometry: + lane_left_edge = [ + line.linestring.coords.xy for line in element.left_boundary + ] + lane_right_edge = [ + line.linestring.coords.xy for line in element.right_boundary + ] + origin_object_coords = origin_object_coords + lane_left_edge + lane_right_edge + lane_left_edge_type = [ + type_dict[line.type] for line in element.left_boundary + ] + lane_right_edge_type = [ + type_dict[line.type] for line in element.right_boundary + ] + _coords_type = _coords_type + lane_left_edge_type + lane_right_edge_type + non_zero_index = [ + index for (index, value) in enumerate(_coords_type) if value != 8 + ] + _object_coords = [ + origin_object_coords[index] for index in non_zero_index + ] + _coords_type = [_coords_type[index] for index in non_zero_index] + + object_coords: List[npt.NDArray[np.float64]] = [ + np.vstack(coords).T for coords in _object_coords + ] + object_coords = [ + (transform @ _cartesian_to_projective_coords(coords).T).T[:, :2] + for coords in object_coords + ] + else: + object_coords = [] + _coords_type = [] + + return object_coords, _coords_type + + +def get_traj_raster(vcs_xy: np.ndarray, + raster_shape: Tuple[int, int], + target_pixel_size: float = 0.0, + longitudinal_offset: float = 0.0, + wp_thickness: int = 3): + """ + Construct the pred traj layer of the raster by converting vector map to raster map. + + Args: + vcs_xy (np.ndarray): vcs coordinates + raster_shape (Tuple[int, int]): A tuple of the shape of the target raster (assumed to be square) + target_pixel_size (float, optional): target pixel size. Defaults to 0.0. + longitudinal_offset (float, optional): [-0.5, 0.5] longitudinal offset of ego center. + wp_thickness (int, optional): pixel size of waypoint. Defaults to 3. + + Returns: + the constructed pred traj raster + """ + img = np.zeros(raster_shape).astype(np.uint8) + for [vcs_x, vcs_y] in vcs_xy: + + map_y_center = int(raster_shape[1] * 0.5) + map_x_center = int(raster_shape[0] * (0.5 + longitudinal_offset)) + + bev_x = -int(vcs_x / target_pixel_size) + map_x_center + bev_y = -int(vcs_y / target_pixel_size) + map_y_center + cv2.circle(img, (bev_y, bev_x), wp_thickness, 1, -1) + + return img + + +def get_roadmap_raster( + focus_agent: EgoState, + map_api: AbstractMap, + map_features: Dict[str, int], + x_range: Tuple[float, float], + y_range: Tuple[float, float], + raster_shape: Tuple[int, int], + resolution: float, + longitudinal_offset: float = 0.0, +) -> npt.NDArray[np.float32]: + """ + Construct the map layer of the raster by converting vector map to raster map. + :param focus_agent: agent state representing ego. + :param map_api: map api. + :param map_features: name of map features to be drawn and its color for encoding. + :param x_range: [m] min and max range from the edges of the grid in x direction. + :param y_range: [m] min and max range from the edges of the grid in y direction. + :param raster_shape: shape of the target raster. + :param resolution: [m] pixel size in meters. + :param longitudinal_offset: [-0.5, 0.5] longitudinal offset of ego center. + :return roadmap_raster: the constructed map raster layer. + """ + # Assume the raster has a square shape. + assert (x_range[1] - x_range[0]) == ( + y_range[1] - + y_range[0]), f'Raster shape is assumed to be square but got width: \ + {y_range[1] - y_range[0]} and height: {x_range[1] - x_range[0]}' + + radius = (x_range[1] - x_range[0]) / 2 + roadmap_raster: npt.NDArray[np.float32] = np.zeros( + raster_shape, dtype=np.float32) + + for feature_name, feature_color in map_features.items(): + coords, _ = _get_layer_coords(focus_agent, map_api, + SemanticMapLayer[feature_name], + 'polygon', radius, longitudinal_offset) + roadmap_raster = _draw_polygon_image(roadmap_raster, coords, radius, + resolution, feature_color) + + # Flip the agents_raster along the horizontal axis. + roadmap_raster = np.flip(roadmap_raster, axis=0) + roadmap_raster = np.ascontiguousarray(roadmap_raster, dtype=np.float32) + + return roadmap_raster diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/features/scene_tensor.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/scene_tensor.py new file mode 100644 index 0000000..bfd6860 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/scene_tensor.py @@ -0,0 +1,241 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Type, Union +import numpy as np +import torch +from nuplan.common.actor_state.vehicle_parameters import get_pacifica_parameters +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.planning.training.preprocessing.features.abstract_model_feature import ( + AbstractModelFeature, + FeatureDataType, + to_tensor, +) +from nuplan.planning.training.preprocessing.utils.agents_preprocessing import ( + AgentInternalIndex, + EgoInternalIndex, +) +# WodScenario unused in nuplan pipeline; import skipped to avoid waymo_open_dataset dep +# from nuplan_extent.planning.scenario_builder.wod_db.wod_scenario import WodScenario +import nuplan_extent.planning.training.preprocessing.features.vector_builders as vb +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpAgentState as AS, +) +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpEgoState, + PreparedScenario, +) + +from nuplan_extent.planning.training.preprocessing.features.raster_builders import ( + PreparedMapObject, +) +import numpy as np +# import tensorflow as tf # unused; skipped to avoid tensorflow dep + + +SCENE_TENSOR_FEATURES = [ + "x", + "y", + "cos(yaw)", + "sin(yaw)", + "vx", + "vy", + "l", + "w", +] +N_SCENE_TENSOR_FEATURES = len(SCENE_TENSOR_FEATURES) +VEH_PARAMS = get_pacifica_parameters() +EGO_WIDTH = VEH_PARAMS.width +EGO_LENGTH = VEH_PARAMS.front_length + VEH_PARAMS.rear_length +CLASSES = ["EGO", "VEHICLE", "PEDESTRIAN", "BICYCLE"] + +FEATURE_MEANS = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.5, 2.0] +FEATURE_STD = [52.0, 52.0, 0.5, 0.5, 2.0, 2.0, 2.5, 0.8] # [70.0, 70.0, 0.5, 0.5, 10.0, 10.0, 2.5, 0.8] + +OLD_FEATURE_MEANS = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.5, 2.0] +OLD_FEATURE_STD = [52.0, 52.0, 0.5, 0.5, 2.0, 2.0, 2.5, 0.8] + + +@dataclass +class SceneTensor(AbstractModelFeature): + tensor: FeatureDataType + validity: FeatureDataType + road_graph: FeatureDataType + road_graph_validity: FeatureDataType + attack_mask: FeatureDataType + + def __init__(self, tensor, validity, road_graph, road_graph_validity, attack_mask=None): + self.tensor = tensor + self.validity = validity + self.road_graph = road_graph + self.road_graph_validity = road_graph_validity + if attack_mask is not None: + self.attack_mask = attack_mask + else: + self.attack_mask = np.zeros_like(self.validity) if isinstance(self.validity, np.ndarray) else torch.zeros_like(self.validity) + if self.tensor.shape[-1] == 9: + self.attack_mask = self.tensor[...,-1] + self.tensor = self.tensor[...,:-1] + + def serialize(self) -> Dict[str, Any]: + return { + "tensor": self.tensor, + "validity": self.validity, + "road_graph": self.road_graph, + "road_graph_validity": self.road_graph_validity, + "attack_mask": self.attack_mask, + } + + @classmethod + def deserialize(cls, data: Dict[str, Any]) -> AbstractModelFeature: + return SceneTensor( + tensor=data["tensor"], + validity=data["validity"], + road_graph=data["road_graph"], + road_graph_validity=data["road_graph_validity"], + ) + + def to_feature_tensor(self) -> AbstractModelFeature: + return SceneTensor( + tensor=to_tensor(self.tensor), + validity=to_tensor(self.validity), + road_graph=to_tensor(self.road_graph), + road_graph_validity=to_tensor(self.road_graph_validity), + attack_mask=to_tensor(self.attack_mask), + ) + + def to_device(self, device: torch.device) -> AbstractModelFeature: + self.tensor = to_tensor(self.tensor).to(device=device) + self.validity = to_tensor(self.validity).to(device=device) + self.road_graph = to_tensor(self.road_graph).to(device=device) + self.road_graph_validity = to_tensor(self.road_graph_validity).to(device=device) + self.attack_mask = to_tensor(self.attack_mask).to(device=device) + + return self + + def unpack(self) -> List[AbstractModelFeature]: + if len(self.tensor.shape) == 3: + return [self] + else: + return [ + SceneTensor( + tensor=self.tensor[i], + validity=self.validity[i], + road_graph=self.road_graph[i], + road_graph_validity=self.road_graph_validity[i], + attack_mask=self.attack_mask[i], + ) + for i in range(self.tensor.shape[0]) + ] + + @classmethod + def collate(cls, batch: List["SceneTensor"]) -> "SceneTensor": # type: ignore + """ + Batch features together with a default_collate function + :param batch: features to be batched + :return: batched features together + """ + largest_n_actors = max([sample.tensor.shape[0] for sample in batch]) + # pad the tensors + for sample in batch: + n_actors = sample.tensor.shape[0] + if n_actors < largest_n_actors: + pad = torch.zeros( + ( + largest_n_actors - n_actors, + sample.tensor.shape[1], + N_SCENE_TENSOR_FEATURES, + ) + ) + pad_validity = torch.zeros( + (largest_n_actors - n_actors, sample.tensor.shape[1]) + ) + sample.tensor = torch.concat([sample.tensor, pad], dim=0) + sample.validity = torch.concat([sample.validity, pad_validity], dim=0) + + return cls( + tensor=torch.stack([sample.tensor for sample in batch]), + validity=torch.stack([sample.validity for sample in batch]), + road_graph=torch.stack([sample.road_graph for sample in batch]), + road_graph_validity=torch.stack( + [sample.road_graph_validity for sample in batch] + ), + attack_mask=torch.stack([sample.attack_mask for sample in batch]), + ) + + +def unnormalize_roadgraph(road_graph: Union[np.ndarray, torch.Tensor]): + if isinstance(road_graph, torch.Tensor): + road_graph[..., :2] = ( + road_graph[..., :2] * 2 * torch.tensor(FEATURE_STD,device=road_graph.device)[:2] + + torch.tensor(FEATURE_MEANS,device=road_graph.device)[:2] + ) + else: + road_graph[..., :2] = ( + road_graph[..., :2] * 2 * np.array(FEATURE_STD)[:2] + + np.array(FEATURE_MEANS)[:2] + ) + return road_graph + + +def decode_scene_tensor( + scene_tensor: Union[np.ndarray, torch.Tensor], +) -> Union[np.ndarray, torch.Tensor]: + if isinstance(scene_tensor, torch.Tensor): + return scene_tensor * 2.0 * torch.tensor( + FEATURE_STD[:scene_tensor.shape[-1]], device=scene_tensor.device + ) + torch.tensor(FEATURE_MEANS[:scene_tensor.shape[-1]], device=scene_tensor.device) + else: + return scene_tensor * 2.0 * np.array(FEATURE_STD[:scene_tensor.shape[-1]]) + np.array(FEATURE_MEANS[:scene_tensor.shape[-1]]) + +def encode_scene_tensor( + scene_tensor: Union[np.ndarray, torch.Tensor], +) -> Union[np.ndarray, torch.Tensor]: + if isinstance(scene_tensor, torch.Tensor): + return (scene_tensor - torch.tensor(FEATURE_MEANS[:scene_tensor.shape[-1]], device=scene_tensor.device)) / (2.0 * torch.tensor(FEATURE_STD[:scene_tensor.shape[-1]], device=scene_tensor.device)) + else: + return (scene_tensor - np.array(FEATURE_MEANS[:scene_tensor.shape[-1]])) / ( 2.0 * np.array(FEATURE_STD)) + +def encode_agent( + cls: str, + agent_state: AS, +) -> np.ndarray: + """ + Encode agent data into a feature tensor. + """ + + state = np.stack( + [ + agent_state[:, AgentInternalIndex.x()], + agent_state[:, AgentInternalIndex.y()], + np.cos(agent_state[:, AgentInternalIndex.heading()]), + np.sin(agent_state[:, AgentInternalIndex.heading()]), + agent_state[:, AgentInternalIndex.vx()], + agent_state[:, AgentInternalIndex.vy()], + agent_state[:, AgentInternalIndex.length()], + agent_state[:, AgentInternalIndex.width()], + ], + axis=1, + ) + return state + + +def encode_ego( + ego_state: NpEgoState, +) -> np.ndarray: + + state = np.stack( + [ + ego_state[:, EgoInternalIndex.x()], + ego_state[:, EgoInternalIndex.y()], + np.cos(ego_state[:, EgoInternalIndex.heading()]), + np.sin(ego_state[:, EgoInternalIndex.heading()]), + ego_state[:, EgoInternalIndex.vx()], + ego_state[:, EgoInternalIndex.vy()], + np.full(ego_state.shape[0], EGO_LENGTH), + np.full(ego_state.shape[0], EGO_WIDTH), + ], + axis=1, + ) + return state + + + diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/features/tokenized_objects/state_type_v1_1.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/tokenized_objects/state_type_v1_1.py new file mode 100644 index 0000000..80c8ce8 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/tokenized_objects/state_type_v1_1.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +import sys +from enum import Enum +from typing import Set, Tuple +import numpy as np + + +class VocabularyStateType(Enum): + """Enum of classification types for TrackedObject with integer ranges.""" + + EGO = (0, 0), 'ego', 0 + AGENTS = (1, 521), 'agents', 1 + CLASS_TYPE = (522, 524), 'class_type', 2 + X = (525, 1524), 'x', 3 # 1000, 0.2, -100, 100 + Y = (1525, 2524), 'y', 4 # 1000, 0.2, -100, 100 + HEADING = (2525, 2724), 'heading', 5, # 200, np.pi/100, -np.pi, np.pi + VX = (2725, 2924), 'vx', 6 # 200, 0.25, -25, 25 + VY = (2925, 3124), 'vy', 7 # 200, 0.25, -25, 25 + WIDTH = (3125, 3139), 'width', 8 # 15 + LENGTH = (3140, 3169), 'length', 9 #30 + BOS_TOKEN = (3170, 3170), 'bos_token', 10 + NEWBORN_BEGIN_TOKEN = (3171, 3171), 'newborn_begin_token', 11 + TRAFFIC_LIGHT_END_TOKEN = (3172, 3172), 'traffic_light_end_token', 12 + PAD_TOKEN = (3173, 3173), 'pad_token', 13 + + @property + def num_agent_attributes(self) -> str: + return 3 + + @property + def vocal_size(self) -> int: + return self.PAD_TOKEN.end+1 + + @property + def x_range(self) -> Tuple[float, float]: + return (-100, 100) + + @property + def y_range(self) -> Tuple[float, float]: + return (-100, 100) + + @property + def heading_range(self) -> Tuple[float, float]: + return (-np.pi, np.pi) + + @property + def vx_range(self) -> Tuple[float, float]: + return (-25, 25) + + @property + def vy_range(self) -> Tuple[float, float]: + return (-25, 25) + + @property + def width_range(self) -> Tuple[float, float]: + return (0, 7) + + @property + def length_range(self) -> Tuple[float, float]: + return (0, 15) + + @property + def x_step(self) -> float: + return (self.x_range[1] - self.x_range[0])/self.nx + + @property + def y_step(self) -> float: + return (self.y_range[1] - self.y_range[0])/self.ny + + @property + def heading_step(self) -> float: + return (self.heading_range[1] - self.heading_range[0])/self.nh + + @property + def vx_step(self) -> float: + return (self.vx_range[1] - self.vx_range[0])/self.nvx + + @property + def vy_step(self) -> float: + return (self.vy_range[1] - self.vy_range[0])/self.nvy + + @property + def width_step(self) -> float: + return (self.width_range[1] - self.width_range[0])/self.nw + + @property + def length_step(self) -> float: + return (self.length_range[1] - self.length_range[0])/self.nl + + @property + def nx(self) -> int: + return self.X.end - self.X.start + 1 + + @property + def ny(self) -> int: + return self.Y.end - self.Y.start + 1 + + @property + def nh(self) -> int: + return self.HEADING.end - self.HEADING.start + 1 + + @property + def nvx(self) -> int: + return self.VX.end - self.VX.start + 1 + + @property + def nvy(self) -> int: + return self.VY.end - self.VY.start + 1 + + @property + def nw(self) -> int: + return self.WIDTH.end - self.WIDTH.start + 1 + + @property + def nl(self) -> int: + return self.LENGTH.end - self.LENGTH.start + 1 + + @property + def ntl(self) -> int: + return self.TRAFFIC_LIGHT.end - self.TRAFFIC_LIGHT.start + 1 + + @property + def nagents(self) -> int: + return self.AGENTS.end - self.AGENTS.start + 1 + + @property + def start(self) -> int: + """Get the start value of the range.""" + return self.value[0][0] + + @property + def end(self) -> int: + """Get the end value of the range.""" + return self.value[0][1] + + @property + def index(self) -> int: + """Get the index of the range.""" + return self.value[2] + + @classmethod + def index_to_state(cls, index: int) -> VocabularyStateType: + """Convert an index to its corresponding VocabularyStateType.""" + for state in cls: + if state.index == index: + return state + raise ValueError(f"No VocabularyStateType found for index {index}") + + def __contains__(self, value) -> bool: + """Check if a number is within the range of this enum member.""" + if isinstance(value, VocabularyStateType): + return self.start <= value.start <= self.end + elif isinstance(value, int): + return self.start <= value <= self.end + else: + raise TypeError("Unsupported type for containment check") + + def get_sampling_mask(self): + sampling_mask = np.zeros(self.vocal_size) + sampling_mask[self.start:self.end+1] = 1 + return sampling_mask > 0 + + +class PositionalStateType(Enum): + """Enum of classification types for TrackedObject.""" + + TRAFFIC_LIGHT_STATE = 1, 'traffic_light_state' + NEWBORN_STATE = 2, 'newborn_state' + NORMAL_STATE = 3, 'normal_state' + + def __contains__(self, pos_state: PositionalStateType) -> bool: + """Check if a number is within the range of this enum member.""" + return pos_state.value == self.value \ No newline at end of file diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/features/vector_builders.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/vector_builders.py new file mode 100644 index 0000000..47c7361 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/features/vector_builders.py @@ -0,0 +1,727 @@ +import cv2 +import math +import os +import numpy.typing as npt +import numpy as np +from scipy.spatial.transform import Rotation as R +from typing import List, NamedTuple, Optional, Tuple +from copy import deepcopy +from nuplan.common.actor_state.tracked_objects_types import TrackedObjectType +from nuplan.planning.training.preprocessing.utils.agents_preprocessing import ( + AgentInternalIndex, + EgoInternalIndex, +) +from nuplan.common.actor_state.state_representation import Point2D, StateSE2 +from nuplan.common.maps.abstract_map import AbstractMap +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.planning.simulation.observation.observation_type import DetectionsTracks +from nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario import NuPlanScenario +from nuplan_extent.planning.scenario_builder.prepared_scenario import ( + NpEgoState, + NpAgentState, + PreparedScenario, + PreparedScenarioFeatureBuilder, +) +from nuplan_extent.planning.training.preprocessing.features.raster_builders import ( + MapObjectRasterBuilder, + _get_prepared_coords, +) +from nuplan_extent.planning.training.preprocessing.features.raster_utils import ( + generate_virtual_center, +) +from third_party.CAT.advgen.utils_scenegen import Scenarios + +class ShapeList(NamedTuple): + """Represents a list of shapes. + + All the coordinates are put into one single array for efficent storage + and computation. The sizes array is used to index into the coordinates + """ + + # concatenated coordinates of the points of all the shapes, shape [N, 2] + coords: npt.NDArray[np.float32] + + # number of points for each shape, shape [M], sizes.sum() == coords.shape[0] + sizes: npt.NDArray[np.int32] + + @property + def num(self): + """The number of shapes in this list.""" + return len(self.sizes) + + +class PreparedMapObject(NamedTuple): + coords: npt.NDArray[np.float32] + object_type: str + speed_limit: Optional[float] + + +# This matrix transforms the ego coordinates to raster coordinates. +# The x-axis of the raster coordinate system corresponds to the y-axis of +# the ego coordinate (i.e. the left direction of the ego vehicle). The y-axis of +# the raster coordinate corresponds to the negative x-axis of the ego coordinate +# (i.e the backward direction of the ego vehicle). +_map_align_transform = np.diag([1., -1., 1.]) @ R.from_euler( + 'z', 90, degrees=True).as_matrix() + + +def get_global_to_local_transform(pose: StateSE2) -> npt.NDArray[np.float32]: + """The the transformation matrix from global to local coordinates. + + :param pose: the pose of the local coordinate system in the global coordinate system. + :return: inverse of the 3x3 2D transformation matrix + """ + c = math.cos(pose.heading) + s = math.sin(pose.heading) + x = pose.x + y = pose.y + return np.array([ + [c, s, -c * x - s * y], + [-s, c, s * x - c * y], + [0, 0, 1], + ]) + + +def get_local_to_global_transform(pose: StateSE2) -> npt.NDArray[np.float32]: + """The the transformation matrix from global to local coordinates. + + :param pose: the pose of the local coordinate system in the global coordinate system. + :return: inverse of the 3x3 2D transformation matrix + """ + c = math.cos(pose.heading) + s = math.sin(pose.heading) + x = pose.x + y = pose.y + return np.array([ + [c, -s, x], + [s, c, y], + [0, 0, 1], + ]) + + +def transform_to_pixel_coords(untransformed_coords: npt.NDArray[np.float32], + center: StateSE2, radius: float, image_size: int, + bit_shift: int): + """Transform global coordinates to pixel coordinates. + + Note that the resulted coordinates are the actual pixel locations multiplied + by 2**bit_shift. bit_shift is for cv2.fillPoly/cv2.polylines to work with + float coordinates. + + :param untransformed_coords: global coordinates + :param center: the pose of the local coordinate system in the global + coordinate system. + :param radius: radius of the raster in meters + :param image_size: size of the raster image in pixels + :param bit_shift: bit shift for converting float to int + """ + + if len(untransformed_coords) == 0: + return [] + resolution = (2 * radius) / image_size + scale = 2**bit_shift / resolution + global_transform = get_global_to_local_transform(center) + # By default the map is right-oriented, this makes it top-oriented. + transform = _map_align_transform @ global_transform + mat = (transform[:2, :2].T * scale).astype(np.float32) + vec = transform[:2, 2] + radius + # Previously, the raster is generated with a different _map_align_transform + # without multiplying diag(1,-1, 1). And the result is flipped vertically. + # (See raster_utils.get_roadmap_raster for example). + # The current way achieves the flip directly by changing _map_align_transform. + # However, this results in a one pixel vertical shift. The following line + # is to compensate for this shift so that the generated raster is compatible + # with the previously trainied model. + vec[1] -= resolution + vec = (vec * scale).astype(np.float32) + object_coords = (untransformed_coords @ mat + vec).astype(np.int64) + return object_coords + + +def draw_polygon_image(polygons: ShapeList, colors: List[float], + image_size: int, center: StateSE2, + radius: float) -> npt.NDArray[np.float32]: + """Draw polygons on the raster. + + :param polygons: polygons to be drawn. The coordinates are in the global + frame. + :param colors: colors of the polygons + :param image_size: size of the raster image in pixels + :param center: the pose of the local coordinate system in the global + coordinate system. + :param radius: radius of the raster in meters + """ + raster: npt.NDArray[np.float32] = np.zeros((image_size, image_size), + dtype=np.float32) + if polygons.coords.size == 0: + return raster + + bit_shift = 10 + coords = transform_to_pixel_coords(polygons.coords, center, radius, + image_size, bit_shift) + start = 0 + for color, size in zip(colors, polygons.sizes): + cv2.fillPoly( + raster, + coords[start:start + size][None], + color=color, + shift=bit_shift, + lineType=cv2.LINE_AA) + start += size + return raster + +class VectorBuilderBase(PreparedScenarioFeatureBuilder): + """The base class for raster builders. + + :param image_size: size of the raster image in pixels + :param radius: radius of the raster in meters + :param ego_longitudinal_offset: the center of the raster is `longitudinal_offset * radius` + meters in front of the rear axle of ego vehicle. 0 means the center is + at the rear axle. + """ + + def __init__(self, radius: float, + longitudinal_offset: float): + super().__init__() + self._radius = radius + self._longitudinal_offset = longitudinal_offset + self._cache_enabled = True + # see set_cache_parameter for explanations about the following two parameters + self._cache_grid_step = self._radius / 2 + self._cache_radius = self._radius * 2.5 + + def set_cache_parameter(self, cache_grid_step: float, + cache_radius: float) -> None: + """Setup cache parameters. + + The map features are cached based on the discretized center of the raster. + If two raster has same discretized center, they will share the same cache. + The discretized center is calculated as `(round(x / cache_grid_step), round(y / cache_grid_step))`. + In order for the same cached feature to cover different raster at different + centers, the cache radius should be larger than the radius of the raster. + The default cache_grid_step is radius / 2, and the default cache_radius is + radius * 2.5. + + :param cache_grid_step: grid step for the cache + :param cache_radius: radius for the cache + """ + self._cache_grid_step = cache_grid_step + self._cache_radius = cache_radius + + def calc_raster_center(self, ego_state: NpEgoState) -> StateSE2: + """Calculate the center of the raster. + + The center of the raster is `longitudinal_offset * radius` meters in front + of the rear axle of ego_state. + + :param ego_state: ego state + """ + return generate_virtual_center( + StateSE2(*ego_state.rear_axle_pose.tolist()), self._radius, + self._longitudinal_offset) + + def calc_cache_key(self, center: Point2D) -> Tuple[int, int]: + """Calculate cache key. + + The cache key is the discretized center of the raster and it is used + for retrieving the map objects from the cache. + + :param center: center of the raster in the coordinates of prepared scenario + :return: cache key for retrieving the map objects in the cache. + """ + step = self._cache_grid_step + grid_x = int(math.floor(center.x / step + 0.5)) + grid_y = int(math.floor(center.y / step + 0.5)) + return grid_x, grid_y + + def calc_cache_key_and_center(self, center: Point2D, offset: npt.NDArray[2] + ) -> Tuple[Tuple[int, int], Point2D]: + """Calculate cache key and map center for getting map objects from the map. + + :param center: center of the raster in the coordinates of the prepared scenario + :param offset: offset for shifting the coordinates for the prepared scenario + :return: + - cache key for storing/retrieving the map objects in the cache. + - the center for retrieving map objects (in the original map coordinate) + The caller should use the returned center and self._cache_radius to + get map objects from the map. + """ + step = self._cache_grid_step + grid_x = int(math.floor(center.x / step + 0.5)) + grid_y = int(math.floor(center.y / step + 0.5)) + # Avoid numpy types since Point2D members are float + x0 = grid_x * step + float(offset[0]) + y0 = grid_y * step + float(offset[1]) + return (grid_x, grid_y), Point2D(x0, y0) + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + pass + + +class PastCurrentAgentsVectorBuilder(VectorBuilderBase): + """Raster representing the past and current agents. + + Cached Features: + tracked_object_boxes: Dict[int, np.ndarray[n, 5]): boxes of the tracked + object for each iteration. Key is iteration. Each box is reparesented + by 5 numbers: center_x, center_y, heading, half_length, half_width. + ego_state: Dict[int, NpEgoState]: ego states for iterations before 0, + up to `past_time_horizon`. + :param image_size: size of the raster image + :param radius: radius of the raster + :param longitudinal_offset: longitudinal offset of the raster + :param past_time_horizon: [s] time horizon of past agents + :param past_num_steps: number of past steps to sample + :param relative_overlay: If False, each agent is represented a series of boxes + corresponding to their past and current pose. If True, each agent is represented + as a series of boxes, where each box represents the pose of the agent + relative to the pose of the ego vehicle at the corresponding iteration. + """ + + def __init__(self, + radius: float, + longitudinal_offset: float, + past_time_horizon: float, + past_num_steps: int, + future_time_horizon: float, + future_num_steps: int, + agent_features: List[str] = ["VEHICLE", "PEDESTRIAN", "CYCLIST"], + num_max_agents: List[int] = [256,128,32], + relative_overlay: bool = False): + super().__init__(radius, longitudinal_offset) + self._past_time_horizon = past_time_horizon + self._past_num_steps = past_num_steps + self._future_time_horizon = future_time_horizon + self._future_num_steps = future_num_steps + self._agent_features = agent_features + self._num_max_agents = num_max_agents + self._relative_overlay = relative_overlay + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + offset = prepared_scenario.get_offset() + interval = scenario.database_interval + + if self._past_time_horizon > 0: + history_window = int(self._past_time_horizon / interval) + assert history_window % self._past_num_steps == 0, ( + f"history window {history_window} must be divisible by " + f"past_num_steps {self._past_num_steps}") + history_step = history_window // self._past_num_steps + else: + history_window = 0 + history_step = 1 + + if self._future_time_horizon > 0: + future_window = int(self._future_time_horizon / interval) + assert future_window % self._future_num_steps == 0, ( + f"future window {future_window} must be divisible by " + f"future_num_steps {self._future_num_steps}") + future_step = future_window // self._future_num_steps + assert ( + history_step == future_step + ), f"history_step {history_step} must be equal to future_step " + else: + future_window = 0 + future_step = 1 + + # 1. get all the history/current/future iteration for iterations + all_iterations = set() + for iteration in iterations: + all_iterations.update( + range(iteration - history_window, iteration + 1 + future_window, history_step)) + all_iterations = sorted(all_iterations) + + # 2. find the earliest unprepared iteration + earliest_unprepared_iteration = None + for iteration in all_iterations: + if not prepared_scenario.feature_exists_at_iteration( + "vectorized_tracked_object_boxes", iteration): + earliest_unprepared_iteration = iteration + break + + # 3. Get past tracked objects + if earliest_unprepared_iteration is not None and earliest_unprepared_iteration < 0: + num_samples = -earliest_unprepared_iteration + if num_samples == 1 and isinstance(scenario, NuPlanScenario): + # 0.5 * iterval is due to an artifact of NuPlanScenario.get_past_tracked_object() + # that when num_samples=1, it actually gets a sample at one + # iteration before the given iteration. This is caused by + # scenario_utils.sample_indices_with_time_horizon() + # See nuplan issue https://github.com/motional/nuplan-devkit/issues/348 + # TODO: remove this hack when the issue is fixed. + time_horizon = 0.5 * interval + else: + time_horizon = num_samples * interval + past_detections = list( + scenario.get_past_tracked_objects( + iteration=0, + time_horizon=time_horizon, + num_samples=num_samples)) + assert len(past_detections) == num_samples + past_ego_states = list( + scenario.get_ego_past_trajectory( + iteration=0, + time_horizon=time_horizon, + num_samples=num_samples)) + past_lidarpc = list(scenario._find_matching_lidar_pcs(0, num_samples, time_horizon, False)) + # 4. prepare polygons for all iterations + track_token_id_mapping = {feature_name:{} for feature_name in self._agent_features} + prepared_scenario._data['lidarpc'] = [] + for iteration in all_iterations: + if prepared_scenario.feature_exists_at_iteration( + "vectorized_tracked_object_boxes", iteration): + continue + if iteration < 0: + detections = past_detections[iteration] + past_ego_state = past_ego_states[iteration] + prepared_scenario.add_ego_state_at_iteration( + past_ego_state, iteration) + cur_lidarpc = past_lidarpc[iteration].token + else: + detections = scenario.get_tracked_objects_at_iteration( + iteration) + future_ego_state = scenario.get_ego_state_at_iteration( + iteration) + prepared_scenario.add_ego_state_at_iteration( + future_ego_state, iteration) + cur_lidarpc = scenario._lidarpc_tokens[iteration] + vector_data, track_token_id_mapping = self._get_vector_data( + detections, offset, track_token_id_mapping + ) + prepared_scenario._data['lidarpc'].append(cur_lidarpc) + prepared_scenario.add_feature_at_iteration('vectorized_tracked_object_boxes', + vector_data, iteration) + prepared_scenario._data['track_token_id_mapping'] = track_token_id_mapping + prepared_scenario._data['map_name'] = scenario.map_api.map_name + def _get_vector_data( + self, detections: DetectionsTracks, offset, track_token_id_mapping + ) -> npt.NDArray[np.float32]: + x0 = float(offset[0]) + y0 = float(offset[1]) + vector_data = {} + for i,feature_name in enumerate(self._agent_features): + object_type = TrackedObjectType[feature_name] + agents = detections.tracked_objects.get_tracked_objects_of_type(object_type) + output = np.zeros((self._num_max_agents[i], AgentInternalIndex.dim()), dtype=np.float32) * np.nan + max_agent_id = len(track_token_id_mapping[feature_name]) + + for idx, agent in enumerate(agents): + # print(idx, self._num_max_agents) + if idx >= self._num_max_agents[i]: + continue + if agent.track_token not in track_token_id_mapping[feature_name]: + track_token_id_mapping[feature_name][agent.track_token] = max_agent_id + max_agent_id += 1 + track_token_int = track_token_id_mapping[feature_name][agent.track_token] + + output[idx, AgentInternalIndex.track_token()] = float(track_token_int) + output[idx, AgentInternalIndex.vx()] = agent.velocity.x + output[idx, AgentInternalIndex.vy()] = agent.velocity.y + output[idx, AgentInternalIndex.heading()] = agent.center.heading + output[idx, AgentInternalIndex.width()] = agent.box.width + output[idx, AgentInternalIndex.length()] = agent.box.length + output[idx, AgentInternalIndex.x()] = agent.center.x - x0 + output[idx, AgentInternalIndex.y()] = agent.center.y - y0 + vector_data[feature_name] = output + return vector_data, track_token_id_mapping + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> npt.NDArray[np.float32]: + + step_interval = int(self._past_time_horizon / + scenario.database_interval / self._past_num_steps) + center = self.calc_raster_center(ego_state) + history_vector_data = {} + for i in range(self._past_num_steps + 1 + self._future_num_steps): + iter = iteration - (self._past_num_steps - i) * step_interval + vector_data = scenario.get_feature_at_iteration('vectorized_tracked_object_boxes', + iter) + vector_data = deepcopy(vector_data) + for class_name, class_vector_data in vector_data.items(): + class_vector_data = class_vector_data.view(NpAgentState) + valid_num = np.sum(~np.isnan(class_vector_data).any(axis=-1)) + if valid_num > 0: + class_vector_data = self._transform_global_to_local(class_vector_data, center) + vector_data[class_name] = class_vector_data + history_vector_data[class_name] = history_vector_data.get(class_name, []) + [class_vector_data] + for class_name, class_vector_data in history_vector_data.items(): + history_vector_data[class_name] = np.stack(class_vector_data, axis=0) + return history_vector_data + + def _transform_global_to_local(self, class_vector_data, center): + trans = get_global_to_local_transform(center) + class_vector_data.transform(trans, center.heading) + return class_vector_data + + +class PastCurrentAdvAgentsVectorBuilder(PastCurrentAgentsVectorBuilder): + def __init__(self, + radius: float, + longitudinal_offset: float, + past_time_horizon: float, + past_num_steps: int, + future_time_horizon: float, + future_num_steps: int, + adv_path: str, + use_adv_data: bool = True, + agent_features: List[str] = ["VEHICLE", "PEDESTRIAN", "CYCLIST"], + num_max_agents: List[int] = [256,128,32], + relative_overlay: bool = False): + super().__init__(radius, longitudinal_offset, past_time_horizon, past_num_steps, future_time_horizon, future_num_steps, agent_features, num_max_agents, relative_overlay) + self.use_adv_data = use_adv_data + self.adv_path = adv_path + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + offset = prepared_scenario.get_offset() + interval = scenario.database_interval + + if self._past_time_horizon > 0: + history_window = int(self._past_time_horizon / interval) + assert history_window % self._past_num_steps == 0, ( + f"history window {history_window} must be divisible by " + f"past_num_steps {self._past_num_steps}") + history_step = history_window // self._past_num_steps + else: + history_window = 0 + history_step = 1 + + if self._future_time_horizon > 0: + future_window = int(self._future_time_horizon / interval) + assert future_window % self._future_num_steps == 0, ( + f"future window {future_window} must be divisible by " + f"future_num_steps {self._future_num_steps}") + future_step = future_window // self._future_num_steps + assert history_step == future_step, ( + f"history_step {history_step} must be equal to future_step ") + else: + future_window = 0 + future_step = 1 + + # 1. get all the history/current/future iteration for iterations + all_iterations = set() + for iteration in iterations: + all_iterations.update( + range(iteration - history_window, iteration + 1 + future_window, history_step)) + all_iterations = sorted(all_iterations) + + # 2. find the earliest unprepared iteration + earliest_unprepared_iteration = None + for iteration in all_iterations: + if not prepared_scenario.feature_exists_at_iteration( + "vectorized_tracked_object_boxes", iteration): + earliest_unprepared_iteration = iteration + break + + # 3. Get past tracked objects + if earliest_unprepared_iteration is not None and earliest_unprepared_iteration < 0: + num_samples = -earliest_unprepared_iteration + if num_samples == 1 and isinstance(scenario, NuPlanScenario): + # 0.5 * iterval is due to an artifact of NuPlanScenario.get_past_tracked_object() + # that when num_samples=1, it actually gets a sample at one + # iteration before the given iteration. This is caused by + # scenario_utils.sample_indices_with_time_horizon() + # See nuplan issue https://github.com/motional/nuplan-devkit/issues/348 + # TODO: remove this hack when the issue is fixed. + time_horizon = 0.5 * interval + else: + time_horizon = num_samples * interval + past_detections = list( + scenario.get_past_tracked_objects( + iteration=0, + time_horizon=time_horizon, + num_samples=num_samples)) + assert len(past_detections) == num_samples + past_ego_states = list( + scenario.get_ego_past_trajectory( + iteration=0, + time_horizon=time_horizon, + num_samples=num_samples)) + # 4. check adv info + if self.use_adv_data and os.path.exists(self.adv_path): + adv_data_path=self.adv_path + scenarios_pkl=Scenarios(adv_data_path) + adv_state=None + adv_token=None + adv_id = None + collision_anchor=None + collison_index=None + if scenario.token in scenarios_pkl.tokens: + _,scenario_pkl=scenarios_pkl.get_env(scenario.token) + if 'objects_of_interest' in scenario_pkl['metadata'] and len(scenario_pkl['metadata']['objects_of_interest'])==2: + adv_token=scenario_pkl['metadata']['objects_of_interest'][1] + adv_state=scenario_pkl['tracks'][adv_token]['state'] + collison_index=scenario_pkl['metadata']['collision_index'] + collision_anchor=collison_index//5*5 + # 5. prepare polygons for all iterations + track_token_id_mapping = {feature_name:{} for feature_name in self._agent_features} + for iteration in all_iterations: + if prepared_scenario.feature_exists_at_iteration( + "vectorized_tracked_object_boxes", iteration): + continue + if iteration < 0: + detections = past_detections[iteration] + past_ego_state = past_ego_states[iteration] + prepared_scenario.add_ego_state_at_iteration( + past_ego_state, iteration) + else: + detections = scenario.get_tracked_objects_at_iteration( + iteration) + future_ego_state = scenario.get_ego_state_at_iteration( + iteration) + prepared_scenario.add_ego_state_at_iteration( + future_ego_state, iteration) + vector_data, track_token_id_mapping = self._get_vector_data( + detections, + offset, + track_token_id_mapping + ) + # modify raw scenario by adv vehicle + if self.use_adv_data and os.path.exists(self.adv_path) and adv_token is not None and collision_anchor is not None: + adv_timestep=iteration-earliest_unprepared_iteration + if adv_timestep <= 90: + if adv_timestep==collision_anchor: + adv_timestep=collison_index + if adv_token not in track_token_id_mapping['VEHICLE']: + track_token_id_mapping['VEHICLE'][adv_token]=len(track_token_id_mapping['VEHICLE']) + if adv_id is None: + adv_id=track_token_id_mapping['VEHICLE'][adv_token] + current_ids=vector_data['VEHICLE'][:,AgentInternalIndex.track_token()] + if float(adv_id) in current_ids: + jusitfied_adv_id = np.where(current_ids == float(adv_id))[0][0] + else: + jusitfied_adv_id = len(current_ids[~np.isnan(current_ids)]) + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.track_token()]=float(adv_id) + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.vx()]=adv_state['velocity'][adv_timestep][0] + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.vy()]=adv_state['velocity'][adv_timestep][1] + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.heading()]=adv_state['heading'][adv_timestep] + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.width()]=adv_state['width'][adv_timestep][0] + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.length()]=adv_state['length'][adv_timestep][0] + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.x()]=adv_state['position'][adv_timestep][0] + vector_data['VEHICLE'][jusitfied_adv_id][AgentInternalIndex.y()]=adv_state['position'][adv_timestep][1] + prepared_scenario.add_feature_at_iteration('vectorized_tracked_object_boxes', + vector_data, iteration) + return {'adv_id':adv_id, 'collision_index':collison_index} + +class PastCurrentEgoVectorBuilder(VectorBuilderBase): + """ + """ + + def __init__(self, + radius: float, + longitudinal_offset: float, + past_time_horizon: float, + past_num_steps: int, + future_time_horizon: float, + future_num_steps: int, + relative_overlay: bool = False): + super().__init__(radius, longitudinal_offset) + self._past_time_horizon = past_time_horizon + self._past_num_steps = past_num_steps + self._future_time_horizon = future_time_horizon + self._future_num_steps = future_num_steps + self._relative_overlay = relative_overlay + + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + pass + + def _get_ego_array( + self, + ego_state: NpEgoState, + ) -> npt.NDArray[np.float32]: + ego_state = ego_state.to_nuplan_ego_state() + output = np.zeros((EgoInternalIndex.dim()), dtype=np.float32) * np.nan + output[EgoInternalIndex.x()] = ego_state.rear_axle.x + output[EgoInternalIndex.y()] = ego_state.rear_axle.y + output[EgoInternalIndex.heading()] = ego_state.rear_axle.heading + output[EgoInternalIndex.vx()] = ego_state.dynamic_car_state.rear_axle_velocity_2d.x + output[EgoInternalIndex.vy()] = ego_state.dynamic_car_state.rear_axle_velocity_2d.y + output[EgoInternalIndex.ax()] = ego_state.dynamic_car_state.rear_axle_acceleration_2d.x + output[EgoInternalIndex.ay()] = ego_state.dynamic_car_state.rear_axle_acceleration_2d.y + return output + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + current_ego_state: NpEgoState) -> npt.NDArray[np.float32]: + step_interval = int(self._past_time_horizon / + scenario.database_interval / self._past_num_steps) + current_center = self.calc_raster_center(current_ego_state) + ego_array_history = [] + for i in range(self._past_num_steps + 1 + self._future_num_steps): + iter = iteration - (self._past_num_steps - i) * step_interval + ego_state = scenario.get_ego_state_at_iteration(iter) + ego_state = deepcopy(ego_state) + ego_state = self._transform_global_to_local(ego_state, current_center) + ego_array = self._get_ego_array(ego_state) + ego_array_history.append(ego_array) + return np.stack(ego_array_history, axis=0) + def _transform_global_to_local(self, ego_array, center): + trans = get_global_to_local_transform(center) + ego_array.transform(trans, center.heading) + return ego_array + + +class MapVectorBuilder(MapObjectRasterBuilder): + # TODO: add traffic lights here somewhere + def prepare_scenario_at_center( + self, map_api: AbstractMap, prepared_scenario: PreparedScenario, center: Point2D + ) -> None: + for feature_name in self._map_features: + geometry = ( + "linestring" + if feature_name in ["LANE", "LANE_CONNECTOR"] + else "polygon" + ) + self.prepare_map_objects( + map_api, prepared_scenario, center, feature_name, geometry + ) + + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, ego_state: NpEgoState + ) -> npt.NDArray[np.float32]: + center = self.calc_raster_center(ego_state) + cache_key = self.calc_cache_key(center) + all_objects = [] + for feature_name in self._map_features: + geometry = ( + "linestring" + if feature_name in ["LANE", "LANE_CONNECTOR"] + else "polygon" + ) + + _, _, prepared_objects = _get_prepared_coords( + scenario, f"map_object_{geometry}_" + feature_name, cache_key + ) + + all_objects.extend(prepared_objects.values()) + + trans = get_global_to_local_transform(center) + # for all coords we need to translate to local coordinate system' + out = [] + for po in all_objects: + transformed_coords = self._transform( + po.coords[:, 0], po.coords[:, 1], trans + ) # Nx3 + # remove all objects that are far away + if np.linalg.norm(transformed_coords, axis=1).min() > self._radius: + continue + + out.append( + PreparedMapObject( + transformed_coords[:, :2], po.object_type, po.speed_limit + ) + ) + + return out + + @staticmethod + def _transform(x, y, trans): + xy = np.stack([x, y], axis=-1) @ trans[:2, :2].T + trans[:2, 2] + return xy diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/utils/other_utils.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/utils/other_utils.py new file mode 100644 index 0000000..a66e4f4 --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/utils/other_utils.py @@ -0,0 +1,14 @@ +import numba +import numpy as np + + +def normalize_angle(angle: np.ndarray): + return (angle + np.pi) % (2 * np.pi) - np.pi + + +@numba.njit +def rotate_round_z_axis(points: np.ndarray, angle: float): + rotate_mat = np.array( + [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]] + ) + return points @ rotate_mat diff --git a/projects/BWM/nuplan_extent/planning/training/preprocessing/utils/route_utils.py b/projects/BWM/nuplan_extent/planning/training/preprocessing/utils/route_utils.py new file mode 100644 index 0000000..edceb8e --- /dev/null +++ b/projects/BWM/nuplan_extent/planning/training/preprocessing/utils/route_utils.py @@ -0,0 +1,565 @@ +from collections import deque +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +from nuplan.common.actor_state.ego_state import EgoState +from nuplan.common.actor_state.state_representation import StateSE2 +from nuplan.common.actor_state.vehicle_parameters import ( + VehicleParameters, get_pacifica_parameters) +from nuplan.common.maps.abstract_map import AbstractMap +from nuplan.common.maps.abstract_map_objects import RoadBlockGraphEdgeMapObject +from nuplan.common.maps.maps_datatypes import SemanticMapLayer +from nuplan.planning.simulation.occupancy_map.strtree_occupancy_map import \ + STRTreeOccupancyMapFactory + +from nuplan_extent.planning.training.preprocessing.utils.other_utils import \ + normalize_angle + + +class BreadthFirstSearchRoadBlock: + """ + A class that performs iterative breadth first search. The class operates on the roadblock graph. + """ + + def __init__( + self, + start_roadblock_id: int, + map_api: Optional[AbstractMap], + forward_search: str = True, + ): + """ + Constructor of BreadthFirstSearchRoadBlock class + :param start_roadblock_id: roadblock id where graph starts + :param map_api: map class in nuPlan + :param forward_search: whether to search in driving direction, defaults to True + """ + self._map_api: Optional[AbstractMap] = map_api + self._queue = deque([self.id_to_roadblock(start_roadblock_id), None]) + self._parent: Dict[str, Optional[RoadBlockGraphEdgeMapObject]] = dict() + self._forward_search = forward_search + + # lazy loaded + self._target_roadblock_ids: List[str] = None + + def search( + self, target_roadblock_id: Union[str, List[str]], max_depth: int + ) -> Tuple[List[RoadBlockGraphEdgeMapObject], bool]: + """ + Apply BFS to find route to target roadblock. + :param target_roadblock_id: id of target roadblock + :param max_depth: maximum search depth + :return: tuple of route and whether a path was found + """ + + if isinstance(target_roadblock_id, str): + target_roadblock_id = [target_roadblock_id] + self._target_roadblock_ids = target_roadblock_id + + start_edge = self._queue[0] + + # Initial search states + path_found: bool = False + end_edge: RoadBlockGraphEdgeMapObject = start_edge + end_depth: int = 1 + depth: int = 1 + + self._parent[start_edge.id + f"_{depth}"] = None + + while self._queue: + current_edge = self._queue.popleft() + + # Early exit condition + if self._check_end_condition(depth, max_depth): + break + + # Depth tracking + if current_edge is None: + depth += 1 + self._queue.append(None) + if self._queue[0] is None: + break + continue + + # Goal condition + if self._check_goal_condition(current_edge, depth, max_depth): + end_edge = current_edge + end_depth = depth + path_found = True + break + + neighbors = ( + current_edge.outgoing_edges + if self._forward_search + else current_edge.incoming_edges + ) + + # Populate queue + for next_edge in neighbors: + # if next_edge.id in self._candidate_lane_edge_ids_old: + self._queue.append(next_edge) + self._parent[next_edge.id + f"_{depth + 1}"] = current_edge + end_edge = next_edge + end_depth = depth + 1 + + return self._construct_path(end_edge, end_depth), path_found + + def id_to_roadblock(self, id: str) -> RoadBlockGraphEdgeMapObject: + """ + Retrieves roadblock from map-api based on id + :param id: id of roadblock + :return: roadblock class + """ + block = self._map_api._get_roadblock(id) + block = block or self._map_api._get_roadblock_connector(id) + return block + + @staticmethod + def _check_end_condition(depth: int, max_depth: int) -> bool: + """ + Check if the search should end regardless if the goal condition is met. + :param depth: The current depth to check. + :param target_depth: The target depth to check against. + :return: whether depth exceeds the target depth. + """ + return depth > max_depth + + def _check_goal_condition( + self, + current_edge: RoadBlockGraphEdgeMapObject, + depth: int, + max_depth: int, + ) -> bool: + """ + Check if the current edge is at the target roadblock at the given depth. + :param current_edge: edge to check. + :param depth: current depth to check. + :param max_depth: maximum depth the edge should be at. + :return: True if the lane edge is contain the in the target roadblock. False, otherwise. + """ + return ( + current_edge.id in self._target_roadblock_ids + and depth <= max_depth + ) + + def _construct_path( + self, end_edge: RoadBlockGraphEdgeMapObject, depth: int + ) -> List[RoadBlockGraphEdgeMapObject]: + """ + Constructs a path when goal was found. + :param end_edge: The end edge to start back propagating back to the start edge. + :param depth: The depth of the target edge. + :return: The constructed path as a list of RoadBlockGraphEdgeMapObject + """ + path = [end_edge] + path_id = [end_edge.id] + + while self._parent[end_edge.id + f"_{depth}"] is not None: + path.append(self._parent[end_edge.id + f"_{depth}"]) + path_id.append(path[-1].id) + end_edge = self._parent[end_edge.id + f"_{depth}"] + depth -= 1 + + if self._forward_search: + path.reverse() + path_id.reverse() + + return (path, path_id) + + +def get_current_roadblock_candidates( + ego_state: EgoState, + map_api: AbstractMap, + route_roadblocks_dict: Dict[str, RoadBlockGraphEdgeMapObject], + heading_error_thresh: float = np.pi / 4, + displacement_error_thresh: float = 3, +) -> Tuple[RoadBlockGraphEdgeMapObject, List[RoadBlockGraphEdgeMapObject]]: + """ + Determines a set of roadblock candidate where ego is located + :param ego_state: class containing ego state + :param map_api: map object + :param route_roadblocks_dict: dictionary of on-route roadblocks + :param heading_error_thresh: maximum heading error, defaults to np.pi/4 + :param displacement_error_thresh: maximum displacement, defaults to 3 + :return: tuple of most promising roadblock and other candidates + """ + ego_pose: StateSE2 = ego_state.rear_axle + roadblock_candidates = [] + + layers = [SemanticMapLayer.ROADBLOCK, SemanticMapLayer.ROADBLOCK_CONNECTOR] + roadblock_dict = map_api.get_proximal_map_objects( + point=ego_pose.point, radius=1.0, layers=layers + ) + roadblock_candidates = ( + roadblock_dict[SemanticMapLayer.ROADBLOCK] + + roadblock_dict[SemanticMapLayer.ROADBLOCK_CONNECTOR] + ) + + if not roadblock_candidates: + for layer in layers: + ( + roadblock_id_, + distance, + ) = map_api.get_distance_to_nearest_map_object( + point=ego_pose.point, layer=layer + ) + roadblock = map_api.get_map_object(roadblock_id_, layer) + + if roadblock: + roadblock_candidates.append(roadblock) + + on_route_candidates, on_route_candidate_displacement_errors = [], [] + candidates, candidate_displacement_errors = [], [] + + roadblock_displacement_errors = [] + roadblock_heading_errors = [] + + for idx, roadblock in enumerate(roadblock_candidates): + lane_displacement_error, lane_heading_error = np.inf, np.inf + + for lane in roadblock.interior_edges: + lane_discrete_path: List[ + StateSE2 + ] = lane.baseline_path.discrete_path + lane_discrete_points = np.array( + [state.point.array for state in lane_discrete_path], + dtype=np.float64, + ) + lane_state_distances = ( + (lane_discrete_points - ego_pose.point.array[None, ...]) ** 2.0 + ).sum(axis=-1) ** 0.5 + argmin = np.argmin(lane_state_distances) + + heading_error = np.abs( + normalize_angle( + lane_discrete_path[argmin].heading - ego_pose.heading + ) + ) + displacement_error = lane_state_distances[argmin] + + if displacement_error < lane_displacement_error: + lane_heading_error, lane_displacement_error = ( + heading_error, + displacement_error, + ) + + if ( + heading_error < heading_error_thresh + and displacement_error < displacement_error_thresh + ): + if roadblock.id in route_roadblocks_dict.keys(): + on_route_candidates.append(roadblock) + on_route_candidate_displacement_errors.append( + displacement_error + ) + else: + candidates.append(roadblock) + candidate_displacement_errors.append(displacement_error) + + roadblock_displacement_errors.append(lane_displacement_error) + roadblock_heading_errors.append(lane_heading_error) + + if on_route_candidates: # prefer on-route roadblocks + return ( + on_route_candidates[ + np.argmin(on_route_candidate_displacement_errors) + ], + on_route_candidates, + ) + elif candidates: # fallback to most promising candidate + return candidates[np.argmin(candidate_displacement_errors)], candidates + + # otherwise, just find any close roadblock + return ( + roadblock_candidates[np.argmin(roadblock_displacement_errors)], + roadblock_candidates, + ) + + +def route_roadblock_correction( + ego_state: EgoState, + map_api: AbstractMap, + route_roadblock_ids: List[str], + search_depth_backward: int = 15, + search_depth_forward: int = 30, +) -> List[str]: + """ + Applies several methods to correct route roadblocks. + :param ego_state: class containing ego state + :param map_api: map object + :param route_roadblocks_dict: dictionary of on-route roadblocks + :param search_depth_backward: depth of forward BFS search, defaults to 15 + :param search_depth_forward: depth of backward BFS search, defaults to 30 + :return: list of roadblock id's of corrected route + """ + + route_roadblock_dict = {} + for id_ in route_roadblock_ids: + block = map_api.get_map_object(id_, SemanticMapLayer.ROADBLOCK) + block = block or map_api.get_map_object( + id_, SemanticMapLayer.ROADBLOCK_CONNECTOR + ) + route_roadblock_dict[id_] = block + + ( + starting_block, + starting_block_candidates, + ) = get_current_roadblock_candidates( + ego_state, map_api, route_roadblock_dict + ) + starting_block_ids = [ + roadblock.id for roadblock in starting_block_candidates + ] + + route_roadblocks = list(route_roadblock_dict.values()) + route_roadblock_ids = list(route_roadblock_dict.keys()) + + # Fix 1: when agent starts off-route + if starting_block.id not in route_roadblock_ids: + # Backward search if current roadblock not in route + graph_search = BreadthFirstSearchRoadBlock( + route_roadblock_ids[0], map_api, forward_search=False + ) + (path, path_id), path_found = graph_search.search( + starting_block_ids, max_depth=search_depth_backward + ) + + if path_found: + route_roadblocks[:0] = path[:-1] + route_roadblock_ids[:0] = path_id[:-1] + + else: + # Forward search to any route roadblock + graph_search = BreadthFirstSearchRoadBlock( + starting_block.id, map_api, forward_search=True + ) + (path, path_id), path_found = graph_search.search( + route_roadblock_ids[:3], max_depth=search_depth_forward + ) + + if path_found: + end_roadblock_idx = np.argmax( + np.array(route_roadblock_ids) == path_id[-1] + ) + + route_roadblocks = route_roadblocks[end_roadblock_idx + 1 :] + route_roadblock_ids = route_roadblock_ids[ + end_roadblock_idx + 1 : + ] + + route_roadblocks[:0] = path + route_roadblock_ids[:0] = path_id + + # Fix 2: check if roadblocks are linked, search for links if not + roadblocks_to_append = {} + for i in range(len(route_roadblocks) - 1): + next_incoming_block_ids = [ + _roadblock.id + for _roadblock in route_roadblocks[i + 1].incoming_edges + ] + is_incoming = route_roadblock_ids[i] in next_incoming_block_ids + + if is_incoming: + continue + + graph_search = BreadthFirstSearchRoadBlock( + route_roadblock_ids[i], map_api, forward_search=True + ) + (path, path_id), path_found = graph_search.search( + route_roadblock_ids[i + 1], max_depth=search_depth_forward + ) + + if path_found and path and len(path) >= 3: + path, path_id = path[1:-1], path_id[1:-1] + roadblocks_to_append[i] = (path, path_id) + + # append missing intermediate roadblocks + offset = 1 + for i, (path, path_id) in roadblocks_to_append.items(): + route_roadblocks[i + offset : i + offset] = path + route_roadblock_ids[i + offset : i + offset] = path_id + offset += len(path) + + # Fix 3: cut route-loops + route_roadblocks, route_roadblock_ids = remove_route_loops( + route_roadblocks, route_roadblock_ids + ) + + return route_roadblock_ids + + +def remove_route_loops( + route_roadblocks: List[RoadBlockGraphEdgeMapObject], + route_roadblock_ids: List[str], +) -> Tuple[List[str], List[RoadBlockGraphEdgeMapObject]]: + """ + Remove ending of route, if the roadblock are intersecting the route (forming a loop). + :param route_roadblocks: input route roadblocks + :param route_roadblock_ids: input route roadblocks ids + :return: tuple of ids and roadblocks of route without loops + """ + + roadblock_occupancy_map = None + loop_idx = None + + for idx, roadblock in enumerate(route_roadblocks): + # loops only occur at intersection, thus searching for roadblock-connectors. + if str(roadblock.__class__.__name__) == "NuPlanRoadBlockConnector": + if not roadblock_occupancy_map: + roadblock_occupancy_map = ( + STRTreeOccupancyMapFactory.get_from_geometry( + [roadblock.polygon], [roadblock.id] + ) + ) + continue + + strtree, index_by_id = roadblock_occupancy_map._build_strtree() + indices = strtree.query(roadblock.polygon) + if len(indices) > 0: + for geom in strtree.geometries.take(indices): + area = geom.intersection(roadblock.polygon).area + if area > 1: + loop_idx = idx + break + if loop_idx: + break + + roadblock_occupancy_map.insert(roadblock.id, roadblock.polygon) + + if loop_idx: + route_roadblocks = route_roadblocks[:loop_idx] + route_roadblock_ids = route_roadblock_ids[:loop_idx] + + return route_roadblocks, route_roadblock_ids + + +class CollisionChecker: + def __init__( + self, + vehicle: VehicleParameters = get_pacifica_parameters(), + ) -> None: + self._vehicle = vehicle + self._sdc_half_length = vehicle.length / 2 + self._sdc_half_width = vehicle.width / 2 + + self._sdc_normalized_corners = torch.stack( + [ + torch.tensor([vehicle.length / 2, vehicle.width / 2]), + torch.tensor([vehicle.length / 2, -vehicle.width / 2]), + torch.tensor([-vehicle.length / 2, -vehicle.width / 2]), + torch.tensor([-vehicle.length / 2, vehicle.width / 2]), + ], + dim=0, + ) + + def to_device(self, device): + self._sdc_normalized_corners = self._sdc_normalized_corners.to(device) + + def build_bbox_from_center(self, center, heading, width, length): + """ + params: + center: [bs, N, (x, y)] + heading: [bs, N] + width: [bs, N] + length: [bs, N] + return: + corners: [bs, 4, (x, y)] + heading_vec, tanh_vec: [bs, 2] + """ + cos = torch.cos(heading) + sin = torch.sin(heading) + + heading_vec = ( + torch.stack([cos, sin], dim=-1) * length.unsqueeze(-1) / 2 + ) + tanh_vec = torch.stack([-sin, cos], dim=-1) * width.unsqueeze(-1) / 2 + + corners = torch.stack( + [ + center + heading_vec + tanh_vec, + center - heading_vec + tanh_vec, + center - heading_vec - tanh_vec, + center + heading_vec - tanh_vec, + ], + dim=-2, + ) + + return corners, heading_vec, tanh_vec + + def collision_check( + self, ego_state, objects, objects_width, objects_length + ): + """performing batch-wise collision check using Separating Axis Theorem + params: + ego_states: [bs, (x, y, theta)], center of the ego + objects: [bs, N, (x, y, theta)], center of the objects + returns: + is_collided: [bs, N] + """ + + bs, N = objects.shape[:2] + + # rotate object to ego's local frame + cos, sin = torch.cos(ego_state[:, 2]), torch.sin(ego_state[:, 2]) + rotate_mat = torch.stack([cos, -sin, sin, cos], dim=-1).reshape( + bs, 2, 2 + ) + + rotated_objects = objects.clone() + rotated_objects[..., :2] = torch.matmul( + rotated_objects[..., :2] - ego_state[:, :2].unsqueeze(1), + rotate_mat, + ) + rotated_objects[..., 2] -= ego_state[..., 2].unsqueeze(1) + + # [bs, N, 4, 2], [bs, N, 2], [bs, N, 2] + object_corners, axis1, axis2 = self.build_bbox_from_center( + rotated_objects[..., :2], + rotated_objects[..., 2], + objects_width, + objects_length, + ) + + ego_corners = self._sdc_normalized_corners.reshape(1, 1, 4, 2).repeat( + bs, N, 1, 1 + ) # [bs, N, 4, 2] + + all_corners = torch.concat( + [object_corners, ego_corners], dim=-2 + ) # [bs, N, 8, 2] + + x_projection = object_corners[..., 0] + y_projection = object_corners[..., 1] + axis1_projection = torch.matmul( + all_corners, axis1.unsqueeze(-1) + ).squeeze(-1) + axis2_projection = torch.matmul( + all_corners, axis2.unsqueeze(-1) + ).squeeze(-1) + + x_separated = (x_projection.max(-1)[0] < -self._sdc_half_length) | ( + x_projection.min(-1)[0] > self._sdc_half_length + ) + y_separated = (y_projection.max(-1)[0] < -self._sdc_half_width) | ( + y_projection.min(-1)[0] > self._sdc_half_width + ) + axis1_separated = ( + axis1_projection[..., :4].max(-1)[0] + < axis1_projection[..., 4:].min(-1)[0] + ) | ( + axis1_projection[..., :4].min(-1)[0] + > axis1_projection[..., 4:].max(-1)[0] + ) + axis2_separated = ( + axis2_projection[..., :4].max(-1)[0] + < axis2_projection[..., 4:].min(-1)[0] + ) | ( + axis2_projection[..., :4].min(-1)[0] + > axis2_projection[..., 4:].max(-1)[0] + ) + + collision = ~( + x_separated | y_separated | axis1_separated | axis2_separated + ) + + return collision diff --git a/projects/BWM/requirements-dev.txt b/projects/BWM/requirements-dev.txt new file mode 100644 index 0000000..a9e0ee4 --- /dev/null +++ b/projects/BWM/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt + +pytest==8.4.2 diff --git a/projects/BWM/requirements.txt b/projects/BWM/requirements.txt new file mode 100644 index 0000000..8f9926d --- /dev/null +++ b/projects/BWM/requirements.txt @@ -0,0 +1,36 @@ +# BWM inference runtime for Python 3.9 / PyTorch 2.3 / CUDA 12.1. +# Binary Torch packages are owned by environment.yml. + +nuplan-devkit @ git+https://github.com/motional/nuplan-devkit.git@e9241677997dd86bfc0bcd44817ab04fe631405b + +aiofiles==25.1.0 +aioboto3==11.0.1 +boto3==1.24.59 +cachetools==6.2.6 +casadi==3.7.2 +einops==0.8.2 +fiona==1.10.1 +geopandas==1.0.1 +hydra-core==1.3.2 +imageio==2.37.2 +matplotlib==3.9.4 +numba==0.60.0 +numpy==1.23.4 +omegaconf==2.3.1 +opencv-python-headless==4.11.0.86 +pandas==2.3.3 +pillow==11.3.0 +psutil==7.2.2 +pyarrow==21.0.0 +pyogrio==0.11.1 +pyquaternion==0.9.9 +pytorch-lightning==2.2.5 +rasterio==1.3.11 +retry==0.9.2 +scipy==1.13.1 +setuptools==59.5.0 +shapely==2.0.7 +sqlalchemy==1.4.27 +torchmetrics==1.8.2 +tqdm==4.68.3 +urllib3==1.26.20 diff --git a/projects/BWM/scripts/__init__.py b/projects/BWM/scripts/__init__.py new file mode 100644 index 0000000..cb758e8 --- /dev/null +++ b/projects/BWM/scripts/__init__.py @@ -0,0 +1 @@ +# Empty __init__.py file to make this directory a Python package \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/__init__.py b/projects/BWM/scripts/generation_general/__init__.py new file mode 100644 index 0000000..cb758e8 --- /dev/null +++ b/projects/BWM/scripts/generation_general/__init__.py @@ -0,0 +1 @@ +# Empty __init__.py file to make this directory a Python package \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/data_loaders/__init__.py b/projects/BWM/scripts/generation_general/data_loaders/__init__.py new file mode 100644 index 0000000..1c66bcb --- /dev/null +++ b/projects/BWM/scripts/generation_general/data_loaders/__init__.py @@ -0,0 +1 @@ +"""Data loading helpers used by the BWM generation pipeline.""" diff --git a/projects/BWM/scripts/generation_general/data_loaders/database_loader.py b/projects/BWM/scripts/generation_general/data_loaders/database_loader.py new file mode 100644 index 0000000..5f1f525 --- /dev/null +++ b/projects/BWM/scripts/generation_general/data_loaders/database_loader.py @@ -0,0 +1,418 @@ +""" +Direct database access data loading functionality. +""" +import sys +import os +import numpy as np +from typing import List +from nuplan.planning.training.preprocessing.feature_builders.abstract_feature_builder import AbstractFeatureBuilder +from nuplan.database.nuplan_db_orm.nuplandb import NuPlanDB +from nuplan.database.maps_db.gpkg_mapsdb import GPKGMapsDB +from nuplan.common.maps.nuplan_map.map_factory import get_maps_api +from nuplan.common.actor_state.state_representation import Point2D +from nuplan.common.maps.abstract_map import AbstractMap +from nuplan.common.maps.maps_datatypes import SemanticMapLayer +from utils.utils_core import NpEgoState +from nuplan_extent.planning.training.preprocessing.feature_builders.horizon_vector_feature_builder_v2 import HorizonVectorV2 + +from processors.feature_processor import compute_features +from processors.data_converter import SceneTensorWrapper + + +class MapObjectWrapper: + """Simple wrapper to convert NuPlan map objects to expected format.""" + def __init__(self, map_object, object_type_name, offset=None, rotation_matrix=None): + self.map_object = map_object + + # Match MapVectorBuilder's training inputs: lane centerlines and area polygons. + if object_type_name in ("LANE", "LANE_CONNECTOR"): + source_coords = map_object.baseline_path.linestring.coords + else: + source_coords = map_object.polygon.exterior.coords + coords_list = [] + for coord in source_coords: + x, y = coord[0], coord[1] + # Convert to relative coordinates by subtracting offset (like scenario approach) + if offset is not None: + x = x - offset[0] + y = y - offset[1] + + # Apply rotation if rotation matrix is provided + if rotation_matrix is not None: + cos_ref, sin_ref = rotation_matrix + x_rotated = x * cos_ref + y * sin_ref + y_rotated = -x * sin_ref + y * cos_ref + x, y = x_rotated, y_rotated + + coords_list.append([x, y]) # Only x, y for 2D coords + self.coords = np.array(coords_list) + + self.object_type = object_type_name + + # Extract speed limit + if hasattr(map_object, 'speed_limit_mps') and map_object.speed_limit_mps is not None: + self.speed_limit = map_object.speed_limit_mps + elif hasattr(map_object, 'speed_limit') and map_object.speed_limit is not None: + self.speed_limit = map_object.speed_limit + else: + self.speed_limit = None + + def __getattr__(self, name): + # Delegate other attributes to the original map object + return getattr(self.map_object, name) + +def get_openscenes_lidarpc_tokens(openscene_dataroot: str, log_name: str) -> List[str]: + """ + Get all lidarpc tokens from openscene data. + """ + import pickle + openscene_data_infos = os.path.join(openscene_dataroot, 'meta_datas', 'trainval', f"{log_name}.pkl") + if not os.path.exists(openscene_data_infos): + openscene_data_infos = os.path.join(openscene_dataroot, 'meta_datas', 'test', f"{log_name}.pkl") + if not os.path.exists(openscene_data_infos): + assert False, f"OpenScene data not found: {openscene_data_infos}" + try: + openscene_data = pickle.load(open(openscene_data_infos, 'rb')) + lidar_pc_tokens = [] + for os_data in openscene_data: + lidar_path = os_data['lidar_path'] + lidar_pc_tokens.append(lidar_path.split('/')[-1].split('.')[0]) + return lidar_pc_tokens + except Exception as e: + assert False, f"Failed to load OpenScene data: {e}" + + + +def get_features_from_db( + builder: AbstractFeatureBuilder, + log_name: str, + lidarpc_token: str, + data_root: str, + map_root: str, + openscene_data_root: str, + past_timesteps: int, + future_timesteps: int, + world_engine_compatible: bool = False, +) -> SceneTensorWrapper: + """ + Extract features directly from nuplan database without using scenario. + All coordinates are converted to local coordinate system relative to the first frame ego pose, + matching the coordinate system expected by the downstream processing pipeline. + + Args: + builder: Feature builder + log_name: Name of the nuplan log + lidarpc_token: Token of the lidar point cloud + data_root: Path to nuplan data + map_root: Path to nuplan maps + openscene_data_root: Path to OpenScene metadata + past_timesteps: Number of past timesteps to extract + future_timesteps: Number of future timesteps to extract + world_engine_compatible: Whether keep bicycle and pedestrian type since worldengine does not support bicycle and pedestrian type + Returns: + SceneTensorWrapper containing the extracted features in local coordinates + """ + # Load the database + db_file = os.path.join(data_root, f"{log_name}.db") + if not os.path.exists(db_file): + raise FileNotFoundError(f"Database file not found: {db_file}") + + db = NuPlanDB(data_root=data_root, load_path=log_name) + maps_db = GPKGMapsDB(map_root=map_root, map_version="nuplan-maps-v1.0") + + openscene_lidarpc_tokens = get_openscenes_lidarpc_tokens( + openscene_data_root, + log_name, + ) + + # Get lidarpc from token + lidarpc = db.lidar_pc.get(token=lidarpc_token) + if lidarpc is None: + raise ValueError(f"LidarPC with token {lidarpc_token} not found in database {log_name}") + + # Get map name + map_name = db.map_name + + # Get past and future lidarpc tokens based on OpenScene token list + # Find current token index in OpenScene lidar token list + try: + current_idx = openscene_lidarpc_tokens.index(lidarpc_token) + except ValueError: + assert False, f"LidarPC token {lidarpc_token} not found in OpenScene data for log {log_name}" + + # Calculate start and end indices for the sequence + start_idx = max(0, current_idx - past_timesteps) + end_idx = min(len(openscene_lidarpc_tokens), current_idx + future_timesteps + 1) + + if current_idx - past_timesteps < 0: + actual_past_timesteps = current_idx + else: + actual_past_timesteps = past_timesteps + + # Extract tokens based on OpenScene sequence + all_tokens = openscene_lidarpc_tokens[start_idx:end_idx] + n_timesteps = len(all_tokens) + + # Extract ego and agent data for each frame + ego_states = [] + agent_data = { + 'VEHICLE': [], + 'PEDESTRIAN': [], + 'BICYCLE': [] + } + + # Track token to ID mapping + track_token_id_mapping = { + 'VEHICLE': {}, + 'PEDESTRIAN': {}, + 'BICYCLE': {} + } + + # Store bidirectional mapping from track_token to ID + token_to_id_mapping = { + 'VEHICLE': {}, + 'PEDESTRIAN': {}, + 'BICYCLE': {} + } + + # nuPlan ego_pose is already at the rear axle. Use the first frame's + # rear axle as the shared local origin for ego, other agents, and the map. + reference_ego_pose = db.lidar_pc.get(token=all_tokens[0]).ego_pose + reference_heading = reference_ego_pose.quaternion.yaw_pitch_roll[0] + reference_x = reference_ego_pose.x + reference_y = reference_ego_pose.y + + # Process each token + for token in all_tokens: + pc = db.lidar_pc.get(token=token) + ego_pose = pc.ego_pose + + # BWM ego features use rear-axle positions, as provided by nuPlan. + ego_heading = ego_pose.quaternion.yaw_pitch_roll[0] + + # Preserve global axes and translate all positions by the same origin. + ego_state = [ + ego_pose.x - reference_x, # rear-axle x relative to the origin + ego_pose.y - reference_y, # rear-axle y relative to the origin + ego_heading, # heading (keep global, like scenario approach) + ego_pose.vx, # vx (global velocity) + ego_pose.vy, # vy (global velocity) + ego_pose.acceleration_x, # ax (global acceleration) + ego_pose.acceleration_y # ay (global acceleration) + ] + + ego_states.append(ego_state) + + # Extract agents for this frame + agents = pc.lidar_boxes + + # Process each agent type + for agent_type in ['VEHICLE', 'PEDESTRIAN', 'BICYCLE']: + frame_agents = [] + + for agent in agents: + # Only process agents matching the current agent_type + agent_category = agent.category.name.upper() + if agent_category != agent_type: + continue + + # Assign ID to track token if not already assigned + track_token = agent.track_token + if track_token not in token_to_id_mapping[agent_type]: + track_id = len(token_to_id_mapping[agent_type]) + 1 # Start from 1 + token_to_id_mapping[agent_type][track_token] = track_id + + # Get assigned ID + track_id = token_to_id_mapping[agent_type][track_token] + + # Keep agent coordinates in global frame, only subtract offset (like scenario approach) + agent_x_relative = agent.x - reference_x + agent_y_relative = agent.y - reference_y + agent_yaw_global = agent.yaw # Keep global heading like scenario approach + + agent_state = [ + track_id, + agent_x_relative, # x (relative to reference position only) + agent_y_relative, # y (relative to reference position only) + agent_yaw_global, # yaw (keep global, like scenario approach) + agent.vx, # vx (global velocity) + agent.vy, # vy (global velocity) + agent.length, + agent.width, + agent.height, + ] + + frame_agents.append(agent_state) + + agent_data[agent_type].append(frame_agents) + + # Here "center" describes the feature-frame origin, not the vehicle center. + ego_state_array = np.zeros(18) + ego_state_array[0] = reference_ego_pose.timestamp / 1e6 # time in seconds + ego_state_array[1] = reference_x # x (global coordinates, rear axle position) + ego_state_array[2] = reference_y # y (global coordinates, rear axle position) + ego_state_array[3] = reference_heading # heading (global) + ego_state_array[4] = reference_ego_pose.vx # vel_lon (global) + ego_state_array[5] = reference_ego_pose.vy # vel_lat (global) + ego_state_array[6] = reference_ego_pose.acceleration_x # acc_lon (global) + ego_state_array[7] = reference_ego_pose.acceleration_y # acc_lat (global) + ego_state_array[11] = 2.297 # width + ego_state_array[12] = 4.049 + 1.127 # length + ego_state_array[13] = 4.049 # front_length + ego_state_array[14] = 1.127 # rear_length + ego_state_array[15] = 1.67 # cog_position_from_rear_axle + ego_state_array[16] = 3.089 # wheel_base + ego_state_array[17] = 1.777 # height + + # Store the shared origin at the first frame's rear axle. + center = ego_state_array.view(NpEgoState) + + # CRITICAL FIX: Use identity transformation to match the simplified coordinate system + # Since we're keeping data in "global" coordinates (only translated), + # we need identity transformation matrix and zero heading offset + # Identity transformation matrix (no rotation) + trans = np.array([ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0, 0, 1] + ]) + + # Offset is the reference position + offset = np.array([reference_x, reference_y]) + + # Override center.heading to 0 to avoid double angle transformation + center_array = center.view(np.ndarray) + center_array[3] = 0.0 + center = center_array.view(NpEgoState) + + # Extract map data + map_api = get_maps_api(map_root, "nuplan-maps-v1.0", map_name) + + # Get map features within radius + radius = builder._radius + center_point = Point2D(center.x, center.y) + + # Get all desired map layers + desired_layers = [] + if 'LANE' in builder._map_features: + desired_layers.append(SemanticMapLayer.LANE) + if 'LANE_CONNECTOR' in builder._map_features: + desired_layers.append(SemanticMapLayer.LANE_CONNECTOR) + if 'STOP_LINE' in builder._map_features: + desired_layers.append(SemanticMapLayer.STOP_LINE) + if 'CROSSWALK' in builder._map_features: + desired_layers.append(SemanticMapLayer.CROSSWALK) + + # Get all proximal map objects at once + proximal_objects = map_api.get_proximal_map_objects(center_point, radius, desired_layers) + + map_features = [] + + # Collect all map objects and wrap them to provide coords attribute + # Only subtract offset like scenario approach, no rotation + + # Extract lanes (only subtract offset, like scenario approach) + if SemanticMapLayer.LANE in proximal_objects: + for lane in proximal_objects[SemanticMapLayer.LANE]: + map_features.append(MapObjectWrapper(lane, 'LANE', offset, None)) + + # Extract lane connectors (only subtract offset, like scenario approach) + if SemanticMapLayer.LANE_CONNECTOR in proximal_objects: + for connector in proximal_objects[SemanticMapLayer.LANE_CONNECTOR]: + map_features.append(MapObjectWrapper(connector, 'LANE_CONNECTOR', offset, None)) + + # Extract stop lines (only subtract offset, like scenario approach) + if SemanticMapLayer.STOP_LINE in proximal_objects: + for stop_line in proximal_objects[SemanticMapLayer.STOP_LINE]: + map_features.append(MapObjectWrapper(stop_line, 'STOP_LINE', offset, None)) + + # Extract crosswalks (only subtract offset, like scenario approach) + if SemanticMapLayer.CROSSWALK in proximal_objects: + for crosswalk in proximal_objects[SemanticMapLayer.CROSSWALK]: + map_features.append(MapObjectWrapper(crosswalk, 'CROSSWALK', offset, None)) + + # Package data in the format expected by compute_features + ego_array = np.array(ego_states) + + # Convert agent data to proper format that feature_processor expects + # feature_processor expects: n_timesteps x n_agents x 9 + # Each unique agent should have a consistent position across all timesteps + + # First, collect all unique agent IDs for each type + all_vehicle_ids = set() + all_pedestrian_ids = set() + all_bicycle_ids = set() + + for t in range(n_timesteps): + for vehicle in agent_data['VEHICLE'][t]: + all_vehicle_ids.add(vehicle[0]) + for pedestrian in agent_data['PEDESTRIAN'][t]: + all_pedestrian_ids.add(pedestrian[0]) + for bicycle in agent_data['BICYCLE'][t]: + all_bicycle_ids.add(bicycle[0]) + + # Get max agent IDs to determine array dimensions + max_vehicle_id = max(all_vehicle_ids) if all_vehicle_ids else 0 + max_pedestrian_id = max(all_pedestrian_ids) if all_pedestrian_ids else 0 + max_bicycle_id = max(all_bicycle_ids) if all_bicycle_ids else 0 + + # Create arrays with proper dimensions (using max ID since agent_id starts from 1) + if max_vehicle_id > 0: + vehicles_array = np.zeros((n_timesteps, max_vehicle_id, 9)) + for t in range(n_timesteps): + for vehicle in agent_data['VEHICLE'][t]: + agent_id = vehicle[0] + idx = agent_id - 1 # Convert 1-based ID to 0-based index + vehicles_array[t, idx] = vehicle + else: + vehicles_array = np.zeros((n_timesteps, 0, 9)) + + if max_pedestrian_id > 0 and not world_engine_compatible: + pedestrians_array = np.zeros((n_timesteps, max_pedestrian_id, 9)) + for t in range(n_timesteps): + for pedestrian in agent_data['PEDESTRIAN'][t]: + agent_id = pedestrian[0] + idx = agent_id - 1 # Convert 1-based ID to 0-based index + pedestrians_array[t, idx] = pedestrian + else: + pedestrians_array = np.zeros((n_timesteps, 0, 9)) + + if max_bicycle_id > 0 and not world_engine_compatible: + bicycles_array = np.zeros((n_timesteps, max_bicycle_id, 9)) + for t in range(n_timesteps): + for bicycle in agent_data['BICYCLE'][t]: + agent_id = bicycle[0] + idx = agent_id - 1 # Convert 1-based ID to 0-based index + bicycles_array[t, idx] = bicycle + else: + bicycles_array = np.zeros((n_timesteps, 0, 9)) + + # Process track_token_id_mapping to ensure compatibility with scenario format + for agent_type in ['VEHICLE', 'PEDESTRIAN', 'BICYCLE']: + for track_token, track_id in token_to_id_mapping[agent_type].items(): + track_token_id_mapping[agent_type][str(track_id)] = track_token # String ID to token + track_token_id_mapping[agent_type][track_id] = track_token # Integer ID to token + + # Create vector data in the format expected by compute_features + vector_data = HorizonVectorV2( + data={ + 'agents': { + 'VEHICLE': vehicles_array, + 'PEDESTRIAN': pedestrians_array, + 'BICYCLE': bicycles_array + }, + 'ego': ego_array, + 'track_token_id_mapping': track_token_id_mapping, + 'map_name': map_name, + 'log_name': log_name, + 'lidarpc': all_tokens, + 'scenario_token': lidarpc_token, + 'actual_past_timesteps': actual_past_timesteps, + 'offset': offset, + 'center': center, + 'trans': trans, + 'map': map_features + } + ) + + return compute_features(builder, vector_data) diff --git a/projects/BWM/scripts/generation_general/pipeline_w_opt.py b/projects/BWM/scripts/generation_general/pipeline_w_opt.py new file mode 100644 index 0000000..a730f65 --- /dev/null +++ b/projects/BWM/scripts/generation_general/pipeline_w_opt.py @@ -0,0 +1,502 @@ +""" +Main pipeline entry point for BWM data processing and generation. +Supports three modes: scenario-based, database-based, and road block-based processing. +""" +import argparse +import sys +import os +import pickle +import copy +import logging +import datetime +from pathlib import Path + +# Make repository-local BWM packages importable regardless of the caller's cwd. +BWM_ROOT = Path(__file__).resolve().parents[2] +if str(BWM_ROOT) not in sys.path: + sys.path.insert(0, str(BWM_ROOT)) + +from omegaconf import OmegaConf +import torch +import numpy as np +from tqdm import tqdm +from nuplan.planning.script.builders.model_builder import build_torch_module_wrapper +from nuplan.common.maps.nuplan_map.map_factory import get_maps_api +from nuplan.database.nuplan_db_orm.nuplandb import NuPlanDB +from utils.checkpoint_loader import load_inference_state_dict +from utils.config_loader import ( + ConfigError, + GENERATION_TASKS, + RUNTIME_PATH_KEYS, + load_entrypoint_config, + resolve_motion_limits, + validate_generation_settings, + validate_runtime_paths, +) + +is_task_type_need_attach = { + 'scenario_copy': False, + 'scenario_copy_with_nearby_vehicle_filter': False, + 'bp': False, + 'scene_gen': False, + 'intent_attack': True, + 'intent_attack_we': True, + 'intent_attack_with_goal_selection': True, + 'goal_conditional_inpainting': True +} + +from data_loaders.database_loader import get_features_from_db +from processors.data_converter import ( + convert_scene_tensor_wrapper_to_scenario_description, + to_numpy, + to_tensor, +) +from processors.scene_generator_v2 import ( + generate_new_scene_tensor_wrapper_from_wrapper_v2, +) +from visualizers.scene_visualizer import ( + visualize_scenario_description, + visualize_scene_tensor_global, +) +import matplotlib.pyplot as plt + +from post_processor.eval_metric.example_usage import calculate_metrics_for_agent_from_sd + + +def metric_check(scenario_description, agent_token, output_dir=None, task=None, cnt=None): + """ + Efficiently process agents with LQR tracking and metric checking. + Stops early if any agent fails metric check. + """ + scenario_key = list(scenario_description.keys())[0] + + for token in agent_token: + object_track = scenario_description[scenario_key]['object_track'] + if token not in object_track: + print(f"⚠️ Agent {token} not found in object_track, skipping metric check") + continue + + results = calculate_metrics_for_agent_from_sd(scenario_description, token, use_segmented=True) + + metrics = results['results'] + nc_score, nc_details = metrics['NC'] + dac_score, dac_details = metrics['DAC'] + + agent_passed = nc_score > 0 and dac_score > 0 + + object_track[token]['metadata']['metric_check_passed'] = agent_passed + + if not agent_passed: + print(f"❌ Agent {token} failed metric check, stopping validation") + print(f" NC score: {nc_score}, DAC score: {dac_score}") + return None + + return scenario_description + + +def setup_logging(log_dir=None, log_filename=None): + """Setup logging to save terminal output to file while still displaying on console.""" + if log_dir is None: + log_dir = os.path.join(os.getcwd(), 'logs') + + os.makedirs(log_dir, exist_ok=True) + + if log_filename is None: + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + log_filename = f"pipeline_{timestamp}.log" + + log_filepath = os.path.join(log_dir, log_filename) + + # Configure logging + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_filepath, encoding='utf-8'), + logging.StreamHandler(sys.stdout) # Also display on console + ] + ) + + # Create a custom logger + logger = logging.getLogger(__name__) + + # Override print function to also log to file + original_print = print + def logged_print(*args, **kwargs): + # Convert all arguments to string and join them + message = ' '.join(str(arg) for arg in args) + logger.info(message) + # Still call original print for immediate console output + original_print(*args, **kwargs) + + # Replace built-in print with logged version + import builtins + builtins.print = logged_print + + print(f"Logging initialized. Log file: {log_filepath}") + return log_filepath + + +def setup_model_and_feature_builder(cfg): + """Initialize model and feature builder from configuration.""" + model = build_torch_module_wrapper(cfg.model) + if cfg.checkpoint: + state_dict = load_inference_state_dict( + cfg.checkpoint, + map_location="cpu", + ) + state_dict = { + key[6:]: value + for key, value in state_dict.items() + } + model.load_state_dict(state_dict, strict=True) + + # Move model to GPU if available + if torch.cuda.is_available(): + model = model.cuda() + + feature_builder = model.get_list_of_required_feature()[0] + return model, feature_builder + + +def process_scene_tensor(scene_tensor_wrapper, model, task="intent_attack", motion_limits=None): + """Common processing pipeline for scene tensor wrapper.""" + # Get the device where the model is located + device = next(model.parameters()).device + + # Convert to tensor with correct device, process, and convert back to numpy + scene_tensor_wrapper = to_tensor(scene_tensor_wrapper, device=device) + new_scene_tensor_wrapper, generator_infos_dict = generate_new_scene_tensor_wrapper_from_wrapper_v2( + scene_tensor_wrapper, model, task, motion_limits=motion_limits + ) + new_scene_tensor_wrapper = to_numpy(new_scene_tensor_wrapper) + + + return new_scene_tensor_wrapper, generator_infos_dict + + +def save_scenario_description(scenario_description, output_dir, filename_prefix): + """Save scenario description to file.""" + output_dir_full = os.path.join(output_dir, filename_prefix) + if scenario_description and output_dir: + os.makedirs(output_dir_full, exist_ok=True) + output_file = os.path.join(output_dir_full, f"{filename_prefix}.pkl") + with open(output_file, "wb") as f: + pickle.dump(scenario_description, f, protocol=pickle.HIGHEST_PROTOCOL) + print(f"Saved scenario description to {output_file}") + + +def select_base_scenes(cfg, digitaltwin_data_root): + """Select available (log, token) pairs using independent SceneFilter allowlists.""" + if cfg.get('scene_filter_path'): + scene_filter_cfg = OmegaConf.load(cfg.scene_filter_path) + else: + scene_filter_cfg = cfg + + config_logs = scene_filter_cfg.get('log_names') + config_tokens = scene_filter_cfg.get('tokens') + if config_logs is None and config_tokens is None: + raise ConfigError("SceneFilter must define log_names or tokens") + # None means unrestricted; an explicit empty list must select no scenes. + config_logs = set(config_logs) if config_logs is not None else None + config_tokens = set(config_tokens) if config_tokens is not None else None + + selected_scenes = [] + for folder_name in os.listdir(digitaltwin_data_root): + video_scene_dict_path = os.path.join(digitaltwin_data_root, folder_name, "video_scene_dict.pkl") + if not os.path.isfile(video_scene_dict_path): + continue + log_name, lidarpc_token = folder_name.rsplit('-', 1) + if config_logs is not None and log_name not in config_logs: + continue + if config_tokens is not None and lidarpc_token not in config_tokens: + continue + selected_scenes.append((log_name, lidarpc_token)) + return selected_scenes + + +def process_database_based_approach( + cfg, + model, + feature_builder, + digitaltwin_data_root, +): + """Process using direct database access approach.""" + print("Using direct database access for multi-task batched...") + + data_root = cfg.scenario_builder.data_root + map_root = cfg.scenario_builder.map_root + selected_scenes = select_base_scenes(cfg, digitaltwin_data_root) + print(f"Selected {len(selected_scenes)} base scenes with available assets") + + # Process each log and token pair + for log_name, lidarpc_token in selected_scenes: + + digitaltwin_data_folder = os.path.join(digitaltwin_data_root, f"{log_name}-{lidarpc_token}") + filename_prefix = f"{log_name}-{lidarpc_token}" + video_scene_dict_path = os.path.join(digitaltwin_data_folder, "video_scene_dict.pkl") + output_path = os.path.join(cfg.output_dir, filename_prefix, f"{filename_prefix}.pkl") + + if os.path.exists(output_path) or not os.path.exists(video_scene_dict_path): + continue + + print(f"Processing {filename_prefix}") + # Initialize database and map API + log_db = NuPlanDB(data_root=data_root, load_path=log_name) + map_api = get_maps_api(map_root, "nuplan-maps-v1.0", log_db.log.map_version) + + scene_tensor_wrapper = get_features_from_db( + feature_builder, + log_name, + lidarpc_token, + data_root, + map_root, + cfg.openscene_data_root, + past_timesteps=cfg.num_history_frames, + future_timesteps=cfg.num_future_frames, + world_engine_compatible=cfg.world_engine_compatible + ) + + # Generate valid scenarios + final_scenario_description = generate_valid_scenarios( + scene_tensor_wrapper, model, cfg.generation.tasks, map_api, data_root, + openscene_data_root=cfg.openscene_data_root, + digitaltwin_data_root=digitaltwin_data_root, + output_dir=os.path.join(cfg.output_dir, filename_prefix), + motion_limits=resolve_motion_limits(cfg.get("motion_validation", {})), + ) + + # Save results and update status + if final_scenario_description and len(final_scenario_description) > 0: + if cfg.save_scenario_description: + save_scenario_description(final_scenario_description, cfg.output_dir, filename_prefix) + else: + print(f"Accepted {len(final_scenario_description)} scenarios for {filename_prefix}; scene PKL saving is disabled") + else: + print(f"No valid scenario description found for {filename_prefix}") + + +def generate_valid_scenarios( + scene_tensor_wrapper, + model, + task_budgets, + map_api, + data_root, + openscene_data_root, + digitaltwin_data_root, + output_dir=None, + motion_limits=None, +): + """Generate valid scenarios through multiple iterations with validation.""" + motion_limits = resolve_motion_limits(motion_limits) + original_scene_tensor_wrapper = copy.deepcopy(scene_tensor_wrapper) + + visualize_scene_tensor_global( + scene_tensor=original_scene_tensor_wrapper.scene_tensor, + local_to_global=original_scene_tensor_wrapper.trans, + center=original_scene_tensor_wrapper.center, + global_offset=original_scene_tensor_wrapper.offset, + output_dir=output_dir + ) + + final_scenario_description = {} + + def process_single_task(task, budget, base_counter=0): + """Process a single task with the given configuration.""" + max_attempts = budget['max_attempts'] + max_success = budget['max_success'] + success_counter = 0 + + for i in range(max_attempts): + if success_counter >= max_success: + break + + try: + # Process scene tensor + scene_tensor_wrapper_copy = copy.deepcopy(original_scene_tensor_wrapper) + new_scene_tensor_wrapper, generator_infos_dict = process_scene_tensor( + scene_tensor_wrapper_copy, model, task, motion_limits=motion_limits + ) + + attack_agent_token = generator_infos_dict.get("attack_agent_token", None) + scenario_valid = generator_infos_dict.get("scenario_valid", False) + + if not scenario_valid: + continue + + # Convert to scenario description + scenario_description = convert_scene_tensor_wrapper_to_scenario_description( + new_scene_tensor_wrapper, + map_api, + data_root, + openscene_data_root, + digitaltwin_data_root + ) + + # Determine agent tokens + agent_tokens = ['ego'] + if attack_agent_token is not None: + if isinstance(attack_agent_token, str): + agent_tokens.append(attack_agent_token) + elif isinstance(attack_agent_token, list): + agent_tokens.extend(attack_agent_token) + else: + print(f"Warning: Invalid attack_agent_token type: {type(attack_agent_token)}") + continue + + # LQR tracking and metric check + scenario_description = metric_check( + scenario_description, agent_tokens, output_dir, task, success_counter + ) + + if scenario_description is not None: + # Visualize successful scenario + visualize_scenario_description( + scenario_description, + output_dir=output_dir, + output_filename=f"scenario_description-{task}-{success_counter}.gif" + ) + + # Update scenario metadata + scenario_keys = list(scenario_description.keys()) + + ori_token = scenario_keys[0] + current_total = base_counter + success_counter + new_key_token = f"{ori_token}-{current_total:03d}" + new_sd_token = f"{scenario_description[ori_token]['token']}-{task}" + + scenario_description[ori_token].update({ + 'id': new_key_token, + 'name': new_key_token, + 'token': new_sd_token + }) + + final_scenario_description[new_key_token] = scenario_description[ori_token] + success_counter += 1 + + except torch.cuda.OutOfMemoryError: + print(f"CUDA OOM in task {task}, iteration {i} — stopping task early") + torch.cuda.empty_cache() + break + except Exception as e: + print(f"Error processing task {task}, iteration {i}: {e}") + continue + + return success_counter + + # Process each task + total_success = 0 + for task in GENERATION_TASKS: + budget = task_budgets[task] + successes = process_single_task(task, budget, total_success) + total_success += successes + print(f"Task {task}: {successes}/{budget['max_success']} successful scenarios") + + print(f"Total successful scenarios generated: {total_success}") + return final_scenario_description + + + +def parse_args(argv=None): + """Parse the small public CLI for the BWM generation pipeline.""" + parser = argparse.ArgumentParser(description="Run the BWM generation pipeline.") + parser.add_argument( + "--config", + required=True, + help="Repository-relative path to a layered BWM scenario YAML.", + ) + parser.add_argument( + "--validate-config", + action="store_true", + help="Load and summarize configuration without starting generation.", + ) + return parser.parse_args(argv) + + +def _display_value(value): + return "" if value is None else value + + +def print_config_summary(loaded): + """Print a deterministic, side-effect-free summary of a loaded config.""" + cfg = loaded.config + missing_runtime = [ + key for key in RUNTIME_PATH_KEYS + if OmegaConf.select(cfg, key) is None + ] + print("=== BWM Configuration ===") + print(f"mode: {loaded.mode}") + print(f"source: {loaded.source}") + print(f"scenario_name: {_display_value(cfg.get('scenario_name'))}") + print(f"data_type: {_display_value(cfg.get('data_type'))}") + print(f"scene_filter_path: {_display_value(cfg.get('scene_filter_path'))}") + print(f"log_names_count: {len(cfg.get('log_names') or [])}") + print(f"tokens_count: {len(cfg.get('tokens') or [])}") + print("generation_execution: sequential") + for task in GENERATION_TASKS: + budget = cfg.generation.tasks[task] + print(f"generation.tasks.{task}: max_attempts={budget.max_attempts}, max_success={budget.max_success}") + print(f"save_scenario_description: {str(cfg.save_scenario_description).lower()}") + for key, value in resolve_motion_limits(cfg.get("motion_validation", {})).items(): + print(f"motion_validation.{key}: {value}") + print( + "num_history_frames: " + f"{_display_value(cfg.get('num_history_frames'))}" + ) + print( + "num_future_frames: " + f"{_display_value(cfg.get('num_future_frames'))}" + ) + for key in RUNTIME_PATH_KEYS: + print(f"{key}: {_display_value(OmegaConf.select(cfg, key))}") + + print( + "runtime_unset: " + + (", ".join(missing_runtime) if missing_runtime else "none") + ) + + +def main(argv=None): + args = parse_args(argv) + try: + loaded = load_entrypoint_config(args.config) + validate_generation_settings(loaded.config) + validate_runtime_paths(loaded.config) + except ConfigError as error: + print(f"Configuration error: {error}", file=sys.stderr) + return 2 + + if args.validate_config: + print_config_summary(loaded) + return 0 + + cfg = loaded.config + cfg_path = loaded.source + + # Setup logging + log_dir = cfg.get('log_dir', './logs') + log_filename = f"{cfg.get('task_type', None)}-{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.log" + log_filepath = setup_logging(log_dir, log_filename) + + print("=== Pipeline Started ===") + print(f"Configuration loaded from: {cfg_path}") + print(f"Logs will be saved to: {log_filepath}") + print_config_summary(loaded) + + # Setup model and feature builder + model, feature_builder = setup_model_and_feature_builder(cfg) + + process_database_based_approach( + cfg, + model, + feature_builder, + cfg.digitaltwin_data_root, + ) + + print("=== Pipeline Completed Successfully ===") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/projects/BWM/scripts/generation_general/post_processor/__init__.py b/projects/BWM/scripts/generation_general/post_processor/__init__.py new file mode 100644 index 0000000..dbdd837 --- /dev/null +++ b/projects/BWM/scripts/generation_general/post_processor/__init__.py @@ -0,0 +1 @@ +# post_processor package \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/post_processor/eval_metric/__init__.py b/projects/BWM/scripts/generation_general/post_processor/eval_metric/__init__.py new file mode 100644 index 0000000..db9cccf --- /dev/null +++ b/projects/BWM/scripts/generation_general/post_processor/eval_metric/__init__.py @@ -0,0 +1 @@ +# eval_metric package \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/post_processor/eval_metric/description_converter.py b/projects/BWM/scripts/generation_general/post_processor/eval_metric/description_converter.py new file mode 100644 index 0000000..b958d2b --- /dev/null +++ b/projects/BWM/scripts/generation_general/post_processor/eval_metric/description_converter.py @@ -0,0 +1,492 @@ +#!/usr/bin/env python3 +""" +Data conversion utilities. + +Convert scenario descriptions to the data structures used by NC/DAC metrics. +Supports the custom scenario description format. +""" + +import numpy as np +from typing import Dict, List, Any, Union, Optional +from shapely.geometry import Polygon, LineString, shape +from shapely.affinity import translate +from nuplan.common.actor_state.vehicle_parameters import get_pacifica_parameters +try: + from post_processor.eval_metric.standalone_metrics import EgoTrajectory, ObjectTrack, MapInfo, AgentTrajectory +except ImportError: + from standalone_metrics import EgoTrajectory, ObjectTrack, MapInfo, AgentTrajectory + +class ScenarioDataConverter: + """Converter for the custom scenario description format.""" + + @staticmethod + def from_scenario_description(scenario_description: Dict[str, Any]) -> tuple: + """ + Convert data from a scenario description. + + Args: + scenario_description: Scenario description containing: + - object_track: Object trajectory data. + - map_features: Map feature data. + - metadata: Coordinate transformation information. + + Returns: + tuple: (ego_trajectory, object_tracks, map_info) + """ + # Extract the data. + object_tracks_data = scenario_description['object_track'] + map_features_data = scenario_description.get('map_features', {}) + metadata = scenario_description.get('metadata', {}) + + # data_converter.py subtracts original_center from both track and map coordinates. + # Both already share the local origin, so no additional transformation is needed. + # (ego_position = global - original_center, map = normalize_to_ego_center = global - original_center) + ego_trajectory = ScenarioDataConverter._convert_ego_trajectory( + object_tracks_data['ego'], coord_offset=None) + + object_tracks = ScenarioDataConverter._convert_object_tracks( + object_tracks_data, coord_offset=None) + + map_info = ScenarioDataConverter._convert_map_features(map_features_data, coord_offset=None) + if "drivable_area" in metadata: + # Native drivable geometry is authoritative. Unioning it with legacy + # lane outlines could fill holes or reintroduce approximate road edges. + map_info.drivable_areas = ScenarioDataConverter._convert_drivable_area(metadata) + + # Log coordinate diagnostics. + if len(ego_trajectory.positions) > 0: + pos = ego_trajectory.positions + valid = ego_trajectory.valid_mask + valid_pos = pos[valid] if valid.any() else pos + ep0 = pos[0] + print(f"[DEBUG] ego pos[0]: ({ep0[0]:.2f}, {ep0[1]:.2f})") + print(f"[DEBUG] ego traj range: x=[{valid_pos[:,0].min():.1f}, {valid_pos[:,0].max():.1f}] y=[{valid_pos[:,1].min():.1f}, {valid_pos[:,1].max():.1f}]") + print(f"[DEBUG] ego valid frames: {valid.sum()}/{len(valid)}") + if map_info.drivable_areas: + from shapely.ops import unary_union + all_bounds = [p.bounds for p in map_info.drivable_areas if not p.is_empty] + if all_bounds: + all_bounds = np.array(all_bounds) + print(f"[DEBUG] drivable union bounds: x=[{all_bounds[:,0].min():.1f}, {all_bounds[:,2].max():.1f}] y=[{all_bounds[:,1].min():.1f}, {all_bounds[:,3].max():.1f}]") + print(f"[DEBUG] drivable areas count: {len(map_info.drivable_areas)}") + + return ego_trajectory, object_tracks, map_info + + @staticmethod + def _convert_ego_trajectory(ego_data: Dict[str, Any], coord_offset: np.ndarray = None) -> EgoTrajectory: + """ + Convert the ego trajectory. + + Args: + ego_data: Ego vehicle data containing state and metadata. + + Returns: + EgoTrajectory: Ego trajectory in the format required by NC/DAC metrics. + """ + state = ego_data['state'] + + # Extract positions, retaining the first two dimensions for 2D coordinates. + positions = np.array(state['position'].copy()) + if positions.shape[1] == 3: + positions = positions[:, :2] # Keep only x and y coordinates. + + # SimEngine tracks already contain vehicle centers. Only convert tracks + # explicitly marked as rear-axle coordinates (the older BWM convention). + if ego_data.get('metadata', {}).get('coordinate_system') == 'rear_axle': + headings = np.asarray(state['heading']).reshape(-1) + rear_axle_to_center_dist = get_pacifica_parameters().rear_axle_to_center + positions[:, 0] += rear_axle_to_center_dist * np.cos(headings) + positions[:, 1] += rear_axle_to_center_dist * np.sin(headings) + + original_pos_sample = positions[0] if len(positions) > 0 else None + + # Apply the optional offset to align positions with the map frame. + if coord_offset is not None and coord_offset.size >= 2: + positions[:, 0] += coord_offset[0] + positions[:, 1] += coord_offset[1] + + # Extract the remaining state information. + headings = np.array(state['heading']) + velocities = np.array(state['velocity']) + valid_mask = np.array(state['valid'], dtype=bool) + + # Extract vehicle dimensions from the first valid frame. + valid_indices = np.where(valid_mask)[0] + if len(valid_indices) > 0: + first_valid_idx = valid_indices[0] + length = float(state['length'][first_valid_idx]) + width = float(state['width'][first_valid_idx]) + dimensions = (length, width) + else: + # Use default dimensions when no valid frame is available. + dimensions = (4.5, 2.0) + + ego_trajectory = EgoTrajectory( + positions=positions, + headings=headings, + velocities=velocities, + dimensions=dimensions, + valid_mask=valid_mask + ) + + return ego_trajectory + + @staticmethod + def _convert_object_tracks(object_tracks_data: Dict[str, Dict[str, Any]], coord_offset: np.ndarray = None) -> List[ObjectTrack]: + """ + Convert object trajectories. + + Args: + object_tracks_data: Dictionary containing all object trajectories. + + Returns: + List[ObjectTrack]: Object trajectories in the format required by NC/DAC metrics. + """ + object_tracks = [] + + for track_id, track_data in object_tracks_data.items(): + # Skip the ego vehicle. + if track_id == 'ego': + continue + + state = track_data['state'] + metadata = track_data['metadata'] + + # Extract positions, retaining the first two dimensions for 2D coordinates. + positions = np.array(state['position']) + if positions.shape[1] == 3: + positions = positions[:, :2] # Keep only x and y coordinates. + + # Apply the optional offset to align positions with the map features. + if coord_offset is not None and coord_offset.size >= 2: + positions[:, 0] += coord_offset[0] + positions[:, 1] += coord_offset[1] + + # Extract the remaining state information. + headings = np.array(state['heading']) + velocities = np.array(state['velocity']) + valid_mask = np.array(state['valid'], dtype=bool) + + # Extract vehicle dimensions from the first valid frame. + valid_indices = np.where(valid_mask)[0] + if len(valid_indices) > 0: + first_valid_idx = valid_indices[0] + length = float(state['length'][first_valid_idx]) + width = float(state['width'][first_valid_idx]) + dimensions = (length, width) + else: + # Use default dimensions when no valid frame is available. + object_type = track_data['type'].upper() + dimensions = ScenarioDataConverter._get_default_dimensions(object_type) + + # Create an ObjectTrack. + object_track = ObjectTrack( + object_id=metadata['object_id'], + object_type=track_data['type'].lower(), + positions=positions, + headings=headings, + velocities=velocities, + dimensions=dimensions, + valid_mask=valid_mask + ) + object_tracks.append(object_track) + + return object_tracks + + @staticmethod + def _convert_drivable_area(metadata: Dict[str, Any]) -> List[Polygon]: + """Align serialized global nuPlan polygons with the scenario's local tracks.""" + payload = metadata["drivable_area"] + if payload.get("coordinate_system") != "global": + raise ValueError("Expected global coordinates for drivable-area geometry") + geometry = shape(payload["geometry"]) + if geometry.is_empty or geometry.geom_type not in ("Polygon", "MultiPolygon") or not geometry.is_valid: + raise ValueError("Expected non-empty valid drivable-area polygons") + offset = np.asarray(metadata["old_origin_in_current_coordinate"]) + geometry = translate(geometry, xoff=offset[0], yoff=offset[1]) + return [geometry] if geometry.geom_type == "Polygon" else list(geometry.geoms) + + @staticmethod + def _convert_map_features(map_features: Dict[str, Any], coord_offset: np.ndarray = None) -> MapInfo: + """ + Convert the flat map feature dictionary returned by extract_map_features. + + Args: + map_features: Map features in the form {feature_id: feature_data}, + where feature_data contains 'type' and geometry ('polyline' or 'polygon'). + + Returns: + MapInfo: Map data in the format required by NC/DAC metrics. + """ + drivable_areas = [] + lane_boundaries = [] + centerlines = [] + + # Import WorldEngineObjectType for type checks. + try: + from ..utils.nuplan_utils import WorldEngineObjectType + except ImportError: + # Define basic type constants if the import fails. + class WorldEngineObjectType: + LANE_SURFACE_STREET = "LANE_SURFACE_STREET" + LANE_SURFACE_UNSTRUCTURE = "LANE_SURFACE_UNSTRUCTURE" + LINE_BROKEN_SINGLE_WHITE = "LINE_BROKEN_SINGLE_WHITE" + LINE_SOLID_SINGLE_WHITE = "LINE_SOLID_SINGLE_WHITE" + BOUNDARY_SIDEWALK = "BOUNDARY_SIDEWALK" + CROSSWALK = "CROSSWALK" + ROADBLOCK = "ROADBLOCK" + ROADBLOCK_CONNECTOR = "ROADBLOCK_CONNECTOR" + INTERSECTION = "INTERSECTION" + CARPARK_AREA = "CARPARK_AREA" + GENERIC_DRIVABLE_AREA = "GENERIC_DRIVABLE_AREA" + + # Iterate over all map features. + feature_type_counts = {} + + for feature_id, feature_data in map_features.items(): + if not isinstance(feature_data, dict) or 'type' not in feature_data: + continue + + feature_type = feature_data['type'] + feature_type_counts[feature_type] = feature_type_counts.get(feature_type, 0) + 1 + + # Extract lane centerlines and drivable areas. + if feature_type in [WorldEngineObjectType.LANE_SURFACE_STREET, + WorldEngineObjectType.LANE_SURFACE_UNSTRUCTURE]: + # Centerline. + if 'polyline' in feature_data and len(feature_data['polyline']) >= 2: + try: + centerlines.append(LineString(feature_data['polyline'])) + except Exception: + continue + + # Use lane polygons as drivable areas. + if 'polygon' in feature_data and len(feature_data['polygon']) >= 3: + try: + pts = np.array(feature_data['polygon']) + if coord_offset is not None: + pts = pts + coord_offset + drivable_areas.append(Polygon(pts)) + except Exception: + continue + + # Process boundary lines. + elif feature_type in [WorldEngineObjectType.LINE_BROKEN_SINGLE_WHITE, + WorldEngineObjectType.LINE_SOLID_SINGLE_WHITE]: + if 'polyline' in feature_data and len(feature_data['polyline']) >= 2: + try: + lane_boundaries.append(LineString(feature_data['polyline'])) + except Exception: + continue + + # Process drivable areas such as intersections and road segments. + elif feature_type in [WorldEngineObjectType.INTERSECTION, + WorldEngineObjectType.CARPARK_AREA, + WorldEngineObjectType.GENERIC_DRIVABLE_AREA]: + if 'polygon' in feature_data and len(feature_data['polygon']) >= 3: + try: + pts = np.array(feature_data['polygon']) + if coord_offset is not None: + pts = pts + coord_offset + drivable_areas.append(Polygon(pts)) + except Exception: + continue + + # Skip sidewalks and crosswalks, which are not drivable areas for vehicles. + elif feature_type in [WorldEngineObjectType.BOUNDARY_SIDEWALK, + WorldEngineObjectType.CROSSWALK]: + # Exclude sidewalks and crosswalks from vehicle drivable areas. + continue + + # Treat other linear features as boundaries. + elif 'polyline' in feature_data and len(feature_data['polyline']) >= 2: + try: + lane_boundaries.append(LineString(feature_data['polyline'])) + except Exception: + continue + + + + return MapInfo( + drivable_areas=drivable_areas, + lane_boundaries=lane_boundaries, + centerlines=centerlines + ) + + @staticmethod + def _get_default_dimensions(object_type: str) -> tuple: + """ + Get default dimensions for an object type. + + Args: + object_type: Object type. + + Returns: + tuple: (length, width) + """ + default_dimensions = { + 'VEHICLE': (4.5, 2.0), + 'PEDESTRIAN': (0.5, 0.5), + 'BICYCLE': (1.8, 0.6), + 'CYCLIST': (1.8, 0.6), + 'MOTORCYCLE': (2.0, 0.8), + 'TRUCK': (8.0, 2.5), + 'BUS': (12.0, 2.5), + } + + return default_dimensions.get(object_type.upper(), (4.0, 1.8)) + + +def convert_scenario_data(scenario_description: Dict[str, Any]) -> tuple: + """ + Convert a scenario description to the format required by NC/DAC metrics. + + Args: + scenario_description: Data in scenario description format. + + Returns: + tuple: (ego_trajectory, object_tracks, map_info) + """ + converter = ScenarioDataConverter() + return converter.from_scenario_description(scenario_description) + + +def convert_multi_scenario_data(scenario_dict: Dict[str, Dict[str, Any]]) -> Dict[str, tuple]: + """ + Convert multiple scenarios in a batch. + + Args: + scenario_dict: Dictionary mapping scenario_id to scenario_description. + + Returns: + Dict[str, tuple]: Dictionary mapping scenario_id to (ego_trajectory, object_tracks, map_info). + """ + converted_data = {} + converter = ScenarioDataConverter() + + for scenario_id, scenario_description in scenario_dict.items(): + try: + converted_data[scenario_id] = converter.from_scenario_description(scenario_description) + except Exception as e: + print(f"Warning: Failed to convert scenario {scenario_id}: {e}") + continue + + return converted_data + + +def convert_scenario_data_with_agent_token(scenario_description: Dict[str, Any], + agent_token: Union[int, str] = None) -> tuple: + """ + Convert a scenario description and select the target agent by token. + + Args: + scenario_description: Data in scenario description format. + agent_token: Target agent ID or token. None or 'ego' selects the ego vehicle. + + Returns: + tuple: (target_agent, other_tracks, map_info) + - target_agent: AgentTrajectory for the target agent. + - other_tracks: List[ObjectTrack] excluding the target agent. + - map_info: MapInfo containing map data. + """ + # Start with the standard conversion. + ego_trajectory, object_tracks, map_info = convert_scenario_data(scenario_description) + + # Return the ego vehicle as the target when agent_token is missing or 'ego'. + if agent_token is None or agent_token == 'ego': + target_agent = AgentTrajectory( + agent_id='ego', + agent_type='ego', + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + return target_agent, object_tracks, map_info + + # Find the requested agent. + target_track = None + other_tracks = [] + + for track in object_tracks: + # Match object_id directly or by its string representation. + if (track.object_id == agent_token or + str(track.object_id) == str(agent_token)): + target_track = track + else: + other_tracks.append(track) + + # Fall back to the ego vehicle and print a warning if the requested agent is missing. + if target_track is None: + print(f"Warning: Agent token '{agent_token}' not found in scenario, using ego as default") + available_ids = [track.object_id for track in object_tracks] + print(f"Available agent IDs: {available_ids}") + + target_agent = AgentTrajectory( + agent_id='ego', + agent_type='ego', + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + # In this fallback, other_tracks is the original object_tracks list. + return target_agent, object_tracks, map_info + + # When a non-ego agent is the target, include the ego vehicle in other_tracks. + ego_as_track = ObjectTrack( + object_id='ego', + object_type='vehicle', # Treat the ego agent as a vehicle. + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + other_tracks.append(ego_as_track) + + # Convert the matching track to an AgentTrajectory. + target_agent = AgentTrajectory( + agent_id=target_track.object_id, + agent_type=target_track.object_type, + positions=target_track.positions, + headings=target_track.headings, + velocities=target_track.velocities, + dimensions=target_track.dimensions, + valid_mask=target_track.valid_mask + ) + + return target_agent, other_tracks, map_info + + +def get_available_agents(scenario_description: Dict[str, Any]) -> Dict[str, str]: + """ + Get information about all available agents in the scenario. + + Args: + scenario_description: Data in scenario description format. + + Returns: + Dict[str, str]: Mapping from agent_id to agent_type, including the ego vehicle. + """ + agents = {'ego': 'ego'} # Ego vehicle. + + try: + object_tracks_data = scenario_description['object_track'] + + for track_id, track_data in object_tracks_data.items(): + if track_id == 'ego': + continue + + metadata = track_data.get('metadata', {}) + object_id = metadata.get('object_id', track_id) + object_type = track_data.get('type', 'unknown').lower() + + agents[str(object_id)] = object_type + + except Exception as e: + print(f"Warning: Failed to extract agent information: {e}") + + return agents diff --git a/projects/BWM/scripts/generation_general/post_processor/eval_metric/example_usage.py b/projects/BWM/scripts/generation_general/post_processor/eval_metric/example_usage.py new file mode 100644 index 0000000..045696a --- /dev/null +++ b/projects/BWM/scripts/generation_general/post_processor/eval_metric/example_usage.py @@ -0,0 +1,501 @@ +import os +import pickle +import numpy as np +from typing import Dict, Any, Optional, Union +from shapely.geometry import Polygon, LineString +try: + from post_processor.eval_metric.standalone_metrics import ( + EgoTrajectory, + ObjectTrack, + MapInfo, + AgentTrajectory, + calculate_metrics_from_scenario, + calculate_metrics_for_agent, + find_agent_by_token, + StandaloneMetricsCalculator + ) + from post_processor.eval_metric.description_converter import ( + convert_scenario_data, + convert_multi_scenario_data, + convert_scenario_data_with_agent_token, + get_available_agents + ) +except ImportError: + from standalone_metrics import ( + EgoTrajectory, + ObjectTrack, + MapInfo, + AgentTrajectory, + calculate_metrics_from_scenario, + calculate_metrics_for_agent, + find_agent_by_token, + StandaloneMetricsCalculator + ) + from description_converter import ( + convert_scenario_data, + convert_multi_scenario_data, + convert_scenario_data_with_agent_token, + get_available_agents + ) + +def calculate_metrics_from_scenario_description(scenario_dict: dict, + scenario_id: Optional[str] = None, + custom_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + # Select the scenario to evaluate. + if scenario_id is None: + scenario_id = list(scenario_dict.keys())[0] + elif scenario_id not in scenario_dict: + available_ids = list(scenario_dict.keys()) + raise ValueError(f"Scenario {scenario_id} not found. Available scenarios: {available_ids}") + + scenario_description = scenario_dict[scenario_id] + + try: + ego_trajectory, object_tracks, map_info = convert_scenario_data(scenario_description) + except Exception as e: + raise ValueError(f"Failed to convert scenario data: {e}") + + # Compute metrics. + if custom_params: + calculator = StandaloneMetricsCalculator(**custom_params) + nc_score, nc_details = calculator.calculate_nc_metric(ego_trajectory, object_tracks) + dac_score, dac_details = calculator.calculate_dac_metric(ego_trajectory, map_info) + results = { + 'NC': (nc_score, nc_details), + 'DAC': (dac_score, dac_details) + } + else: + results = calculate_metrics_from_scenario( + ego_trajectory=ego_trajectory, + object_tracks=object_tracks, + map_info=map_info + ) + + return { + 'scenario_id': scenario_id, + 'results': results, + 'scenario_info': { + 'ego_timesteps': len(ego_trajectory.positions), + 'num_objects': len(object_tracks), + 'num_drivable_areas': len(map_info.drivable_areas), + 'num_centerlines': len(map_info.centerlines) + } + } + +def load_scenario_description(pkl_file_path: str) -> Dict[str, Any]: + if not os.path.exists(pkl_file_path): + raise FileNotFoundError(f"Pickle file not found: {pkl_file_path}") + + with open(pkl_file_path, 'rb') as f: + data = pickle.load(f) + + print(f"Successfully loaded scenario data from: {pkl_file_path}") + + return data + +def calculate_metrics_for_agent_from_pkl(pkl_file_path: str, + agent_token: Union[int, str] = None, + scenario_id: Optional[str] = None, + custom_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """ + Load a scenario from a pickle file and compute metrics for the requested agent. + + Args: + pkl_file_path: Path to the pickle file. + agent_token: Target agent ID or token. None or 'ego' selects the ego vehicle. + scenario_id: ID of the scenario to evaluate. None selects the first scenario. + custom_params: Custom metric parameters. + + Returns: + Dict: Dictionary containing metric results. + """ + # Load scenario description data. + scenario_dict = load_scenario_description(pkl_file_path) + + # Select the scenario to evaluate. + if scenario_id is None: + scenario_id = list(scenario_dict.keys())[0] + # print(f"No scenario_id specified, using first scenario: {scenario_id}") + elif scenario_id not in scenario_dict: + available_ids = list(scenario_dict.keys()) + raise ValueError(f"Scenario {scenario_id} not found. Available scenarios: {available_ids}") + + scenario_description = scenario_dict[scenario_id] + + # Get all available agents. + available_agents = get_available_agents(scenario_description) + print(f"Available agents in scenario: {available_agents}") + + # Convert the data and select the target agent using agent_token. + print(f"Converting scenario data for agent: {agent_token}") + try: + target_agent, other_tracks, map_info = convert_scenario_data_with_agent_token( + scenario_description, agent_token) + print(f"Successfully converted scenario data:") + print(f" - Target agent ({target_agent.agent_id}): {len(target_agent.positions)} timesteps") + print(f" - Other tracks: {len(other_tracks)} objects") + print(f" - Map info: {len(map_info.drivable_areas)} drivable areas, {len(map_info.centerlines)} centerlines") + except Exception as e: + raise ValueError(f"Failed to convert scenario data: {e}") + + # Compute metrics. + print(f"Calculating metrics for agent {target_agent.agent_id}...") + if custom_params: + calculator = StandaloneMetricsCalculator(**custom_params) + nc_score, nc_details = calculator.calculate_nc_metric_for_agent(target_agent, other_tracks) + dac_score, dac_details = calculator.calculate_dac_metric_for_agent(target_agent, map_info) + results = { + 'NC': (nc_score, nc_details), + 'DAC': (dac_score, dac_details) + } + else: + results = calculate_metrics_for_agent( + target_agent=target_agent, + other_tracks=other_tracks, + map_info=map_info + ) + + return { + 'scenario_id': scenario_id, + 'target_agent_id': target_agent.agent_id, + 'target_agent_type': target_agent.agent_type, + 'results': results, + 'scenario_info': { + 'agent_timesteps': len(target_agent.positions), + 'num_other_objects': len(other_tracks), + 'num_drivable_areas': len(map_info.drivable_areas), + 'num_centerlines': len(map_info.centerlines), + 'available_agents': available_agents + } + } + + +def calculate_metrics_from_pkl(pkl_file_path: str, + scenario_id: Optional[str] = None, + custom_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """ + Load a scenario from a pickle file and compute metrics. + + Args: + pkl_file_path: Path to the pickle file. + scenario_id: ID of the scenario to evaluate. None selects the first scenario. + custom_params: Custom metric parameters. + + Returns: + Dict: Dictionary containing metric results. + """ + # Load scenario description data. + scenario_dict = load_scenario_description(pkl_file_path) + + + # Select the scenario to evaluate. + if scenario_id is None: + scenario_id = list(scenario_dict.keys())[0] + # print(f"No scenario_id specified, using first scenario: {scenario_id}") + elif scenario_id not in scenario_dict: + available_ids = list(scenario_dict.keys()) + raise ValueError(f"Scenario {scenario_id} not found. Available scenarios: {available_ids}") + + scenario_description = scenario_dict[scenario_id] + + # Convert the data format. + print(f"Converting scenario data for: {scenario_id}") + try: + ego_trajectory, object_tracks, map_info = convert_scenario_data(scenario_description) + print(f"Successfully converted scenario data:") + print(f" - Ego trajectory: {len(ego_trajectory.positions)} timesteps") + print(f" - Object tracks: {len(object_tracks)} objects") + print(f" - Map info: {len(map_info.drivable_areas)} drivable areas, {len(map_info.centerlines)} centerlines") + except Exception as e: + raise ValueError(f"Failed to convert scenario data: {e}") + + # Compute metrics. + print("Calculating metrics...") + if custom_params: + calculator = StandaloneMetricsCalculator(**custom_params) + nc_score, nc_details = calculator.calculate_nc_metric(ego_trajectory, object_tracks) + dac_score, dac_details = calculator.calculate_dac_metric(ego_trajectory, map_info) + results = { + 'NC': (nc_score, nc_details), + 'DAC': (dac_score, dac_details) + } + else: + results = calculate_metrics_from_scenario( + ego_trajectory=ego_trajectory, + object_tracks=object_tracks, + map_info=map_info + ) + + return { + 'scenario_id': scenario_id, + 'results': results, + 'scenario_info': { + 'ego_timesteps': len(ego_trajectory.positions), + 'num_objects': len(object_tracks), + 'num_drivable_areas': len(map_info.drivable_areas), + 'num_centerlines': len(map_info.centerlines) + } + } + + +def calculate_metrics_for_agent_from_sd(scenario_dict: dict, + agent_token: Union[int, str] = None, + scenario_id: Optional[str] = None, + use_segmented: bool = True, + custom_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + # Select the scenario to evaluate. + if scenario_id is None: + scenario_id = list(scenario_dict.keys())[0] + # print(f"No scenario_id specified, using first scenario: {scenario_id}") + elif scenario_id not in scenario_dict: + available_ids = list(scenario_dict.keys()) + raise ValueError(f"Scenario {scenario_id} not found. Available scenarios: {available_ids}") + + scenario_description = scenario_dict[scenario_id] + + available_agents = get_available_agents(scenario_description) + + try: + target_agent, other_tracks, map_info = convert_scenario_data_with_agent_token( + scenario_description, agent_token) + + except Exception as e: + print(f"❌ Trajectory conversion failed: {e}") + raise ValueError(f"Failed to convert scenario data: {e}") + + # Check for an agent trajectory with no valid timesteps. + valid_points_count = np.sum(target_agent.valid_mask) + total_points = len(target_agent.valid_mask) + + if valid_points_count == 0: + print(f"❌ Warning: Agent {agent_token} has no valid trajectory points") + # Return the default failure result. + results = { + 'NC': (0.0, { + 'has_collision': False, + 'collision_time': None, + 'collision_type': 'no_collision', + 'collided_object_id': None, + 'collision_info': [], + 'target_agent_id': target_agent.agent_id, + 'error': 'no_valid_trajectory_points' + }), + 'DAC': (0.0, { + 'is_compliant': False, + 'violation_times': [], + 'violation_positions': [], + 'total_violation_time': 0.0, + 'target_agent_id': target_agent.agent_id, + 'error': 'no_valid_trajectory_points' + }) + } + elif valid_points_count < 3: + print(f"⚠️ Warning: Agent {agent_token} has only {valid_points_count} valid points (less than 3)") + # Also return a low score when there are too few trajectory points. + results = { + 'NC': (0.1, { + 'has_collision': False, + 'collision_time': None, + 'collision_type': 'no_collision', + 'collided_object_id': None, + 'collision_info': [], + 'target_agent_id': target_agent.agent_id, + 'warning': 'insufficient_valid_trajectory_points' + }), + 'DAC': (0.1, { + 'is_compliant': False, + 'violation_times': [], + 'violation_positions': [], + 'total_violation_time': 0.0, + 'target_agent_id': target_agent.agent_id, + 'warning': 'insufficient_valid_trajectory_points' + }) + } + else: + # Compute metrics for the valid trajectory. + results = calculate_metrics_for_agent( + target_agent=target_agent, + other_tracks=other_tracks, + map_info=map_info, + use_segmented=use_segmented + ) + + return { + 'scenario_id': scenario_id, + 'target_agent_id': target_agent.agent_id, + 'target_agent_type': target_agent.agent_type, + 'results': results, + 'use_segmented': use_segmented, + 'scenario_info': { + 'agent_timesteps': len(target_agent.positions), + 'valid_timesteps': valid_points_count, + 'valid_ratio': valid_points_count / total_points if total_points > 0 else 0.0, + 'num_other_objects': len(other_tracks), + 'num_drivable_areas': len(map_info.drivable_areas), + 'num_centerlines': len(map_info.centerlines), + 'available_agents': available_agents + } + } + +def batch_calculate_metrics(pkl_file_path: str, + custom_params: Optional[Dict[str, Any]] = None) -> Dict[str, Dict[str, Any]]: + """ + Compute metrics for multiple scenarios in a batch. + + Args: + pkl_file_path: Path to the pickle file. + custom_params: Custom metric parameters. + + Returns: + Dict: Metric results for all scenarios. + """ + # Load all scenarios. + scenario_dict = load_scenario_description(pkl_file_path) + + print(f"Batch processing {len(scenario_dict)} scenarios...") + + # Convert the data in a batch. + converted_data = convert_multi_scenario_data(scenario_dict) + print(f"Successfully converted {len(converted_data)} scenarios") + + # Compute metrics in a batch. + all_results = {} + + for scenario_id, (ego_trajectory, object_tracks, map_info) in converted_data.items(): + print(f"Calculating metrics for scenario: {scenario_id}") + + try: + if custom_params: + calculator = StandaloneMetricsCalculator(**custom_params) + nc_score, nc_details = calculator.calculate_nc_metric(ego_trajectory, object_tracks) + dac_score, dac_details = calculator.calculate_dac_metric(ego_trajectory, map_info) + results = { + 'NC': (nc_score, nc_details), + 'DAC': (dac_score, dac_details) + } + else: + results = calculate_metrics_from_scenario( + ego_trajectory=ego_trajectory, + object_tracks=object_tracks, + map_info=map_info + ) + + all_results[scenario_id] = { + 'results': results, + 'scenario_info': { + 'ego_timesteps': len(ego_trajectory.positions), + 'num_objects': len(object_tracks), + 'num_drivable_areas': len(map_info.drivable_areas), + 'num_centerlines': len(map_info.centerlines) + } + } + + except Exception as e: + print(f"Failed to calculate metrics for scenario {scenario_id}: {e}") + continue + + return all_results + + +def print_metrics_results(results: Dict[str, Any]): + """Print metric results (backward-compatible interface).""" + scenario_id = results['scenario_id'] + metrics = results['results'] + info = results['scenario_info'] + + print(f"\n=== Scenario metric results: {scenario_id} ===") + print(f"Scenario information:") + print(f" - Ego trajectory timesteps: {info.get('ego_timesteps', info.get('agent_timesteps', 'N/A'))}") + print(f" - Other objects: {info.get('num_objects', info.get('num_other_objects', 'N/A'))}") + print(f" - Drivable areas: {info['num_drivable_areas']}") + print(f" - Centerlines: {info['num_centerlines']}") + + nc_score, nc_details = metrics['NC'] + dac_score, dac_details = metrics['DAC'] + + print(f"\nNC metric results:") + print(f" - NC score: {nc_score:.4f}") + print(f" - Has collision: {nc_details['has_collision']}") + if nc_details['has_collision']: + print(f" - Collision time: {nc_details['collision_time']}") + print(f" - Collided object ID: {nc_details['collided_object_id']}") + print(f" - Collision type: {nc_details['collision_type']}") + print(f" - Total collisions: {len(nc_details['collision_info'])}") + + print(f"\nDAC metric results:") + print(f" - DAC score: {dac_score:.4f}") + print(f" - Is compliant: {dac_details['is_compliant']}") + print(f" - Violation count: {dac_details['total_violation_time']}") + if not dac_details['is_compliant']: + print(f" - Violation timesteps: {dac_details.get('violation_times', 'N/A')}") + + +def print_agent_metrics_results(results: Dict[str, Any]): + """Print metric results for the requested agent.""" + scenario_id = results['scenario_id'] + agent_id = results['target_agent_id'] + agent_type = results['target_agent_type'] + metrics = results['results'] + info = results['scenario_info'] + use_segmented = results.get('use_segmented', False) + + print(f"\n=== Agent metric results: {scenario_id} ===") + print(f"Target agent information:") + print(f" - Agent ID: {agent_id}") + print(f" - Agent type: {agent_type}") + print(f" - Trajectory timesteps: {info['agent_timesteps']}") + print(f" - Valid timesteps: {info['valid_timesteps']}") + print(f" - Validity ratio: {info['valid_ratio']:.3f}") + print(f" - Other objects: {info['num_other_objects']}") + print(f" - Drivable areas: {info['num_drivable_areas']}") + print(f" - Centerlines: {info['num_centerlines']}") + print(f" - Available agents: {info['available_agents']}") + print(f" - Calculation method: {'segmented' if use_segmented else 'global'}") + + nc_score, nc_details = metrics['NC'] + dac_score, dac_details = metrics['DAC'] + + print(f"\nNC metric results (Agent {agent_id}):") + print(f" - NC score: {nc_score:.4f}") + print(f" - Has collision: {nc_details['has_collision']}") + + # Display segment information when available. + if use_segmented and 'segments_info' in nc_details: + segments_info = nc_details['segments_info'] + total_segments = nc_details.get('total_segments', len(segments_info)) + print(f" - Contiguous valid segments: {total_segments}") + for segment in segments_info: + print(f" Segment {segment['segment_idx']}: timesteps {segment['start_idx']}-{segment['end_idx']} " + f"(length {segment['length']}, NC={segment['nc_score']:.3f}, " + f"collision: {'yes' if segment['has_collision'] else 'no'})") + + if nc_details['has_collision']: + print(f" - Collision time: {nc_details['collision_time']}") + print(f" - Collided object ID: {nc_details['collided_object_id']}") + print(f" - Collision type: {nc_details['collision_type']}") + print(f" - Total collisions: {len(nc_details['collision_info'])}") + # Display details of all collisions. + for i, collision in enumerate(nc_details['collision_info']): + segment_info = f" (segment {collision['segment_idx']})" if 'segment_idx' in collision else "" + print(f" Collision {i+1}: time {collision['time']}{segment_info}, " + f"with object {collision['object_id']} ({collision['object_type']})") + + print(f"\nDAC metric results (Agent {agent_id}):") + print(f" - DAC score: {dac_score:.4f}") + print(f" - Is compliant: {dac_details['is_compliant']}") + print(f" - Violation count: {dac_details['total_violation_time']}") + + # Display segment information when available. + if use_segmented and 'segments_info' in dac_details: + segments_info = dac_details['segments_info'] + total_segments = dac_details.get('total_segments', len(segments_info)) + print(f" - Contiguous valid segments: {total_segments}") + for segment in segments_info: + print(f" Segment {segment['segment_idx']}: timesteps {segment['start_idx']}-{segment['end_idx']} " + f"(length {segment['length']}, DAC={segment['dac_score']:.3f}, " + f"compliant: {'yes' if segment['is_compliant'] else 'no'})") + + if not dac_details['is_compliant']: + print(f" - Violation timesteps: {dac_details.get('violation_times', 'N/A')}") + if len(dac_details.get('violation_times', [])) > 0: + print(f" - First violation timesteps: {dac_details['violation_times'][:5]}") # Show only the first five. diff --git a/projects/BWM/scripts/generation_general/post_processor/eval_metric/standalone_metrics.py b/projects/BWM/scripts/generation_general/post_processor/eval_metric/standalone_metrics.py new file mode 100644 index 0000000..591520d --- /dev/null +++ b/projects/BWM/scripts/generation_general/post_processor/eval_metric/standalone_metrics.py @@ -0,0 +1,788 @@ +import numpy as np +import numpy.typing as npt +from typing import Dict, List, Optional, Tuple, Union +from dataclasses import dataclass +from shapely.geometry import Point, Polygon, LineString +from shapely import creation +import copy + +@dataclass +class ObjectTrack: + """Trajectory data for a single object.""" + object_id: int + object_type: str # 'vehicle', 'pedestrian', 'cyclist', etc. + positions: npt.NDArray[np.float64] # shape: (num_timesteps, 2) [x, y] + headings: npt.NDArray[np.float64] # shape: (num_timesteps,) [rad] + velocities: npt.NDArray[np.float64] # shape: (num_timesteps, 2) [vx, vy] + dimensions: Tuple[float, float] # (length, width) + valid_mask: npt.NDArray[np.bool_] # shape: (num_timesteps,) + +@dataclass +class EgoTrajectory: + """Trajectory data for the ego vehicle.""" + positions: npt.NDArray[np.float64] # shape: (num_timesteps, 2) [x, y] + headings: npt.NDArray[np.float64] # shape: (num_timesteps,) [rad] + velocities: npt.NDArray[np.float64] # shape: (num_timesteps, 2) [vx, vy] + dimensions: Tuple[float, float] # (length, width) + valid_mask: npt.NDArray[np.bool_] # shape: (num_timesteps,) + +@dataclass +class AgentTrajectory: + """Generic trajectory data for any agent.""" + agent_id: Union[int, str] # Agent ID or token. + agent_type: str # 'ego', 'vehicle', 'pedestrian', 'cyclist', etc. + positions: npt.NDArray[np.float64] # shape: (num_timesteps, 2) [x, y] + headings: npt.NDArray[np.float64] # shape: (num_timesteps,) [rad] + velocities: npt.NDArray[np.float64] # shape: (num_timesteps, 2) [vx, vy] + dimensions: Tuple[float, float] # (length, width) + valid_mask: npt.NDArray[np.bool_] # shape: (num_timesteps,) + +@dataclass +class MapInfo: + """Map information.""" + drivable_areas: List[Polygon] # List of drivable area polygons. + lane_boundaries: List[LineString] # List of lane boundary lines. + centerlines: List[LineString] # List of centerlines. + +class CollisionType: + """Collision type enumeration.""" + NO_COLLISION = "no_collision" + ACTIVE_FRONT_COLLISION = "active_front_collision" + ACTIVE_LATERAL_COLLISION = "active_lateral_collision" + STOPPED_TRACK_COLLISION = "stopped_track_collision" + +class StandaloneMetricsCalculator: + """Standalone metric calculator.""" + + def __init__(self, + stopped_speed_threshold: float = 0.005, # m/s + agent_types: List[str] = None): + """ + Initialize the metric calculator. + + Args: + stopped_speed_threshold: Speed threshold for classifying a vehicle as stopped. + agent_types: Object types treated as agents. + """ + self.stopped_speed_threshold = stopped_speed_threshold + self.agent_types = agent_types or ['vehicle', 'cyclist', 'motorcyclist'] + + def find_continuous_valid_segments(self, valid_mask: np.ndarray, min_length: int = 3) -> List[Tuple[int, int]]: + """ + Find contiguous valid segments with at least min_length points each. + + Args: + valid_mask: (N,) boolean array indicating validity + min_length: Minimum number of points in a contiguous segment. + + Returns: + List[Tuple[int, int]]: Start and end indices of contiguous segments, [(start, end), ...]. + """ + segments = [] + start = None + + for i, is_valid in enumerate(valid_mask): + if is_valid and start is None: + start = i + elif not is_valid and start is not None: + if i - start >= min_length: + segments.append((start, i)) + start = None + + # Handle the final segment. + if start is not None and len(valid_mask) - start >= min_length: + segments.append((start, len(valid_mask))) + + return segments + + def calculate_nc_metric_for_agent_segmented(self, + target_agent: AgentTrajectory, + other_tracks: List[ObjectTrack], + **kwargs) -> Tuple[float, Dict]: + """ + Compute NC for the target agent over contiguous valid segments. + + Args: + target_agent: Trajectory of the target agent. + other_tracks: Trajectories of other objects. + + Returns: + Tuple[float, Dict]: (NC score, details). + """ + # Find contiguous valid segments of the target agent. + valid_segments = self.find_continuous_valid_segments(target_agent.valid_mask) + + if not valid_segments: + return 0.0, { + 'has_collision': False, + 'collision_time': None, + 'collision_type': CollisionType.NO_COLLISION, + 'collided_object_id': None, + 'collision_info': [], + 'target_agent_id': target_agent.agent_id, + 'error': 'no_valid_segments', + 'segments_info': [] + } + + # Compute NC separately for each segment. + segment_results = [] + overall_collision_info = [] + overall_has_collision = False + overall_nc_score = 1.0 + first_collision_time = None + first_collision_type = CollisionType.NO_COLLISION + first_collided_object_id = None + + for segment_idx, (start_idx, end_idx) in enumerate(valid_segments): + segment_length = end_idx - start_idx + + # Extract segment data. + segment_positions = target_agent.positions[start_idx:end_idx] + segment_headings = target_agent.headings[start_idx:end_idx] + segment_velocities = target_agent.velocities[start_idx:end_idx] + segment_valid = target_agent.valid_mask[start_idx:end_idx] + + # Create an AgentTrajectory for the segment. + segment_agent = AgentTrajectory( + agent_id=target_agent.agent_id, + agent_type=target_agent.agent_type, + positions=segment_positions, + headings=segment_headings, + velocities=segment_velocities, + dimensions=target_agent.dimensions, + valid_mask=segment_valid + ) + + # Create the corresponding other_tracks for this segment. + segment_other_tracks = [] + for obj_track in other_tracks: + if end_idx <= len(obj_track.positions): + segment_obj_positions = obj_track.positions[start_idx:end_idx] + segment_obj_headings = obj_track.headings[start_idx:end_idx] + segment_obj_velocities = obj_track.velocities[start_idx:end_idx] + segment_obj_valid = obj_track.valid_mask[start_idx:end_idx] + + segment_obj_track = ObjectTrack( + object_id=obj_track.object_id, + object_type=obj_track.object_type, + positions=segment_obj_positions, + headings=segment_obj_headings, + velocities=segment_obj_velocities, + dimensions=obj_track.dimensions, + valid_mask=segment_obj_valid + ) + segment_other_tracks.append(segment_obj_track) + + # Compute NC for this segment. + segment_nc_score, segment_collision_details = self.calculate_nc_metric_for_agent_basic( + segment_agent, segment_other_tracks + ) + + # Convert collision timestep indices to full-trajectory indices. + if segment_collision_details['collision_info']: + for collision in segment_collision_details['collision_info']: + collision['time'] += start_idx + collision['segment_idx'] = segment_idx + + overall_collision_info.extend(segment_collision_details['collision_info']) + + if segment_collision_details['has_collision']: + overall_has_collision = True + if first_collision_time is None: + first_collision_time = segment_collision_details['collision_time'] + start_idx + first_collision_type = segment_collision_details['collision_type'] + first_collided_object_id = segment_collision_details['collided_object_id'] + + # Update the overall NC score using the lowest segment score. + overall_nc_score = min(overall_nc_score, segment_nc_score) + + # Record segment details. + segment_info = { + 'segment_idx': segment_idx, + 'start_idx': start_idx, + 'end_idx': end_idx, + 'length': segment_length, + 'nc_score': segment_nc_score, + 'has_collision': segment_collision_details['has_collision'], + 'collision_count': len(segment_collision_details['collision_info']) + } + segment_results.append(segment_info) + + return overall_nc_score, { + 'has_collision': overall_has_collision, + 'collision_time': first_collision_time, + 'collision_type': first_collision_type, + 'collided_object_id': first_collided_object_id, + 'collision_info': overall_collision_info, + 'target_agent_id': target_agent.agent_id, + 'segments_info': segment_results, + 'total_segments': len(valid_segments), + 'method': 'segmented' + } + + def calculate_dac_metric_for_agent_segmented(self, + target_agent: AgentTrajectory, + map_info: MapInfo, + **kwargs) -> Tuple[float, Dict]: + """ + Compute DAC for the target agent over contiguous valid segments. + + Args: + target_agent: Trajectory of the target agent. + map_info: Map information. + + Returns: + Tuple[float, Dict]: (DAC score, details). + """ + # Find contiguous valid segments of the target agent. + valid_segments = self.find_continuous_valid_segments(target_agent.valid_mask) + + if not valid_segments: + return 0.0, { + 'is_compliant': False, + 'violation_times': [], + 'violation_positions': [], + 'total_violation_time': 0.0, + 'target_agent_id': target_agent.agent_id, + 'error': 'no_valid_segments', + 'segments_info': [] + } + + if not map_info.drivable_areas: + # Assume full compliance when drivable area information is unavailable. + return 1.0, { + 'is_compliant': True, + 'violation_times': [], + 'violation_positions': [], + 'total_violation_time': 0.0, + 'target_agent_id': target_agent.agent_id, + 'segments_info': [] + } + + # Compute DAC separately for each segment. + segment_results = [] + overall_violation_times = [] + overall_violation_positions = [] + overall_is_compliant = True + overall_dac_score = 1.0 + + for segment_idx, (start_idx, end_idx) in enumerate(valid_segments): + segment_length = end_idx - start_idx + + # Extract segment data. + segment_positions = target_agent.positions[start_idx:end_idx] + segment_headings = target_agent.headings[start_idx:end_idx] + segment_velocities = target_agent.velocities[start_idx:end_idx] + segment_valid = target_agent.valid_mask[start_idx:end_idx] + + # Create an AgentTrajectory for the segment. + segment_agent = AgentTrajectory( + agent_id=target_agent.agent_id, + agent_type=target_agent.agent_type, + positions=segment_positions, + headings=segment_headings, + velocities=segment_velocities, + dimensions=target_agent.dimensions, + valid_mask=segment_valid + ) + + # Compute DAC for this segment. + segment_dac_score, segment_compliance_details = self.calculate_dac_metric_for_agent_basic( + segment_agent, map_info + ) + + # Convert violation timestep indices to full-trajectory indices. + if segment_compliance_details['violation_times']: + adjusted_violation_times = [t + start_idx for t in segment_compliance_details['violation_times']] + overall_violation_times.extend(adjusted_violation_times) + overall_violation_positions.extend(segment_compliance_details['violation_positions']) + + if not segment_compliance_details['is_compliant']: + overall_is_compliant = False + + # Update the overall DAC score using the lowest segment score. + overall_dac_score = min(overall_dac_score, segment_dac_score) + + # Record segment details. + segment_info = { + 'segment_idx': segment_idx, + 'start_idx': start_idx, + 'end_idx': end_idx, + 'length': segment_length, + 'dac_score': segment_dac_score, + 'is_compliant': segment_compliance_details['is_compliant'], + 'violation_count': len(segment_compliance_details['violation_times']) + } + segment_results.append(segment_info) + + return overall_dac_score, { + 'is_compliant': overall_is_compliant, + 'violation_times': overall_violation_times, + 'violation_positions': overall_violation_positions, + 'total_violation_time': len(overall_violation_times), + 'target_agent_id': target_agent.agent_id, + 'segments_info': segment_results, + 'total_segments': len(valid_segments), + 'method': 'segmented' + } + + def calculate_nc_metric_for_agent_basic(self, + target_agent: AgentTrajectory, + other_tracks: List[ObjectTrack], + **kwargs) -> Tuple[float, Dict]: + """ + Compute NC for the target agent without segmentation. + Original implementation of calculate_nc_metric_for_agent. + """ + num_timesteps = len(target_agent.positions) + nc_score = 1.0 + collision_details = { + 'has_collision': False, + 'collision_time': None, + 'collision_type': CollisionType.NO_COLLISION, + 'collided_object_id': None, + 'collision_info': [], + 'target_agent_id': target_agent.agent_id + } + + # Create the target agent's polygon at each timestep. + agent_polygons = self._create_vehicle_polygons( + target_agent.positions, + target_agent.headings, + target_agent.dimensions + ) + + # Check for collisions at each timestep. + collision_count = 0 + for t in range(num_timesteps): + if not target_agent.valid_mask[t]: + continue + + agent_polygon = agent_polygons[t] + agent_speed = np.linalg.norm(target_agent.velocities[t]) + + # Check for collisions with each object. + for obj_track in other_tracks: + if t >= len(obj_track.positions) or not obj_track.valid_mask[t]: + continue + + # Create the object's polygon. + obj_polygon = self._create_vehicle_polygon( + obj_track.positions[t], + obj_track.headings[t], + obj_track.dimensions + ) + + # Check for intersection. + if agent_polygon.intersects(obj_polygon): + collision_count += 1 + # Classify the collision type. + collision_type = self._classify_collision_type( + target_agent.positions[t], + target_agent.headings[t], + target_agent.velocities[t], + obj_track.positions[t], + obj_track.headings[t], + obj_track.velocities[t], + obj_track.object_type + ) + + # Determine whether the collision is at fault. + is_at_fault = self._is_at_fault_collision(collision_type, obj_track.object_type) + + # Record collision details. + collision_info = { + 'time': t, + 'object_id': obj_track.object_id, + 'object_type': obj_track.object_type, + 'collision_type': collision_type, + 'agent_speed': agent_speed, + 'object_speed': np.linalg.norm(obj_track.velocities[t]), + 'is_at_fault': is_at_fault + } + collision_details['collision_info'].append(collision_info) + + # Record only at-fault collisions. + if is_at_fault: + collision_details['has_collision'] = True + if collision_details['collision_time'] is None: + collision_details['collision_time'] = t + collision_details['collision_type'] = collision_type + collision_details['collided_object_id'] = obj_track.object_id + + # Update the NC score; only at-fault collisions affect it. + if obj_track.object_type in self.agent_types: + nc_score = 0.0 + else: + nc_score = min(nc_score, 0.5) + + return nc_score, collision_details + + def calculate_dac_metric_for_agent_basic(self, + target_agent: AgentTrajectory, + map_info: MapInfo, + **kwargs) -> Tuple[float, Dict]: + """ + Compute DAC for the target agent without segmentation. + Original implementation of calculate_dac_metric_for_agent. + """ + num_timesteps = len(target_agent.positions) + dac_score = 1.0 + compliance_details = { + 'is_compliant': True, + 'violation_times': [], + 'violation_positions': [], + 'total_violation_time': 0.0, + 'target_agent_id': target_agent.agent_id + } + + # Create the union of all drivable area polygons. + if not map_info.drivable_areas: + # Assume full compliance when drivable area information is unavailable. + return dac_score, compliance_details + + # Merge all drivable areas. + from shapely.ops import unary_union + drivable_union = unary_union(map_info.drivable_areas) + + # Check each timestep. + violation_count = 0 + + for t in range(num_timesteps): + if not target_agent.valid_mask[t]: + continue + + # Create the target agent's polygon at the current timestep. + agent_polygon = self._create_vehicle_polygon( + target_agent.positions[t], + target_agent.headings[t], + target_agent.dimensions + ) + + # Check whether the polygon is within the drivable area. + is_contained = drivable_union.contains(agent_polygon) + is_intersecting = drivable_union.intersects(agent_polygon) + + if not is_contained: + if not is_intersecting: + # Completely outside the drivable area. + violation_count += 1 + compliance_details['is_compliant'] = False + compliance_details['violation_times'].append(t) + compliance_details['violation_positions'].append( + target_agent.positions[t].copy() + ) + dac_score = 0.0 + else: + # For partial overlap, evaluate compliance using the overlap ratio. + overlap_ratio = agent_polygon.intersection(drivable_union).area / agent_polygon.area + if overlap_ratio < 0.8: # Treat overlap below 80% as a violation. + violation_count += 1 + compliance_details['is_compliant'] = False + compliance_details['violation_times'].append(t) + compliance_details['violation_positions'].append( + target_agent.positions[t].copy() + ) + dac_score = max(0.0, min(dac_score, overlap_ratio)) + + # Count timesteps with violations. + compliance_details['total_violation_time'] = len(compliance_details['violation_times']) + + return dac_score, compliance_details + + def calculate_nc_metric_for_agent(self, + target_agent: AgentTrajectory, + other_tracks: List[ObjectTrack], + use_segmented: bool = True, + **kwargs) -> Tuple[float, Dict]: + """ + Compute the No Collision (NC) metric for the target agent. + + Args: + target_agent: Trajectory of the target agent. + other_tracks: Trajectories of other objects. + use_segmented: Whether to compute metrics by segment. + + Returns: + Tuple[float, Dict]: (NC score, details). + """ + if use_segmented: + return self.calculate_nc_metric_for_agent_segmented(target_agent, other_tracks, **kwargs) + else: + return self.calculate_nc_metric_for_agent_basic(target_agent, other_tracks, **kwargs) + + def calculate_dac_metric_for_agent(self, + target_agent: AgentTrajectory, + map_info: MapInfo, + use_segmented: bool = True, + **kwargs) -> Tuple[float, Dict]: + """ + Compute the Drivable Area Compliance (DAC) metric for the target agent. + + Args: + target_agent: Trajectory of the target agent. + map_info: Map information. + use_segmented: Whether to compute metrics by segment. + + Returns: + Tuple[float, Dict]: (DAC score, details). + """ + if use_segmented: + return self.calculate_dac_metric_for_agent_segmented(target_agent, map_info, **kwargs) + else: + return self.calculate_dac_metric_for_agent_basic(target_agent, map_info, **kwargs) + + def calculate_nc_metric(self, + ego_trajectory: EgoTrajectory, + object_tracks: List[ObjectTrack], + **kwargs) -> Tuple[float, Dict]: + """ + Compute the No Collision (NC) metric (backward-compatible interface). + + Args: + ego_trajectory: Ego vehicle trajectory. + object_tracks: Trajectories of other objects. + + Returns: + Tuple[float, Dict]: (NC score, details). + """ + # Convert to AgentTrajectory format. + target_agent = AgentTrajectory( + agent_id='ego', + agent_type='ego', + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + + return self.calculate_nc_metric_for_agent(target_agent, object_tracks, **kwargs) + + def calculate_dac_metric(self, + ego_trajectory: EgoTrajectory, + map_info: MapInfo, + **kwargs) -> Tuple[float, Dict]: + """ + Compute the Drivable Area Compliance (DAC) metric (backward-compatible interface). + + Args: + ego_trajectory: Ego vehicle trajectory. + map_info: Map information. + + Returns: + Tuple[float, Dict]: (DAC score, details). + """ + # Convert to AgentTrajectory format. + target_agent = AgentTrajectory( + agent_id='ego', + agent_type='ego', + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + + return self.calculate_dac_metric_for_agent(target_agent, map_info, **kwargs) + + def _create_vehicle_polygons(self, + positions: npt.NDArray[np.float64], + headings: npt.NDArray[np.float64], + dimensions: Tuple[float, float]) -> List[Polygon]: + """Create vehicle polygons for all timesteps.""" + polygons = [] + for i in range(len(positions)): + polygon = self._create_vehicle_polygon(positions[i], headings[i], dimensions) + polygons.append(polygon) + return polygons + + def _create_vehicle_polygon(self, + position: npt.NDArray[np.float64], + heading: float, + dimensions: Tuple[float, float]) -> Polygon: + """Create a polygon representation of a single vehicle.""" + length, width = dimensions + + # Vehicle corners relative to the vehicle center. + corners = np.array([ + [length/2, width/2], # Front corner (+x, +y). + [-length/2, width/2], # Rear corner (-x, +y). + [-length/2, -width/2], # Rear corner (-x, -y). + [length/2, -width/2] # Front corner (+x, -y). + ]) + + # Rotation matrix. + cos_h, sin_h = np.cos(heading), np.sin(heading) + rotation_matrix = np.array([ + [cos_h, -sin_h], + [sin_h, cos_h] + ]) + + # Rotate and translate. + rotated_corners = corners @ rotation_matrix.T + world_corners = rotated_corners + position + + return Polygon(world_corners) + + def _classify_collision_type(self, + ego_pos: npt.NDArray[np.float64], + ego_heading: float, + ego_vel: npt.NDArray[np.float64], + obj_pos: npt.NDArray[np.float64], + obj_heading: float, + obj_vel: npt.NDArray[np.float64], + obj_type: str) -> str: + """Classify the collision type.""" + + # Compute the relative position. + relative_pos = obj_pos - ego_pos + + # Transform into the ego vehicle's coordinate frame. + cos_h, sin_h = np.cos(ego_heading), np.sin(ego_heading) + local_x = relative_pos[0] * cos_h + relative_pos[1] * sin_h + local_y = -relative_pos[0] * sin_h + relative_pos[1] * cos_h + + # Compute speeds. + ego_speed = np.linalg.norm(ego_vel) + obj_speed = np.linalg.norm(obj_vel) + + # Check whether the object is stopped. + if obj_speed < self.stopped_speed_threshold: + return CollisionType.STOPPED_TRACK_COLLISION + + # Check whether the collision is frontal. + if local_x > 0: # The object is in front of the ego vehicle. + return CollisionType.ACTIVE_FRONT_COLLISION + else: # Side collision. + return CollisionType.ACTIVE_LATERAL_COLLISION + + def _is_at_fault_collision(self, collision_type: str, obj_type: str) -> bool: + """Determine whether the collision is at fault.""" + if collision_type in [CollisionType.ACTIVE_FRONT_COLLISION, + CollisionType.STOPPED_TRACK_COLLISION]: + return True + return False + +# Convenience functions. +def calculate_metrics_from_scenario(ego_trajectory: EgoTrajectory, + object_tracks: List[ObjectTrack], + map_info: MapInfo, + **kwargs) -> Dict[str, Tuple[float, Dict]]: + """ + Compute NC and DAC from scenario data (backward-compatible interface). + + Args: + ego_trajectory: Ego vehicle trajectory. + object_tracks: Trajectories of other objects. + map_info: Map information. + + Returns: + Dict: {'NC': (score, details), 'DAC': (score, details)} + """ + calculator = StandaloneMetricsCalculator(**kwargs) + + nc_score, nc_details = calculator.calculate_nc_metric(ego_trajectory, object_tracks) + dac_score, dac_details = calculator.calculate_dac_metric(ego_trajectory, map_info) + + return { + 'NC': (nc_score, nc_details), + 'DAC': (dac_score, dac_details) + } + + +def calculate_metrics_for_agent(target_agent: AgentTrajectory, + other_tracks: List[ObjectTrack], + map_info: MapInfo, + use_segmented: bool = True, + **kwargs) -> Dict[str, Tuple[float, Dict]]: + """ + Compute NC and DAC for the target agent. + + Args: + target_agent: Trajectory of the target agent. + other_tracks: Trajectories of other objects. + map_info: Map information. + use_segmented: Whether to compute metrics by segment (recommended). + + Returns: + Dict[str, Tuple[float, Dict]]: Dictionary containing NC and DAC metric results. + """ + calculator = StandaloneMetricsCalculator() + + nc_score, nc_details = calculator.calculate_nc_metric_for_agent( + target_agent, other_tracks, use_segmented=use_segmented, **kwargs) + dac_score, dac_details = calculator.calculate_dac_metric_for_agent( + target_agent, map_info, use_segmented=use_segmented, **kwargs) + + return { + 'NC': (nc_score, nc_details), + 'DAC': (dac_score, dac_details) + } + + +def find_agent_by_token(all_tracks: List[ObjectTrack], + ego_trajectory: EgoTrajectory, + agent_token: Union[int, str]) -> Tuple[Optional[AgentTrajectory], List[ObjectTrack]]: + """ + Find the agent by token and return its trajectory and the remaining tracks. + + Args: + all_tracks: Trajectories of all objects. + ego_trajectory: Ego vehicle trajectory. + agent_token: Agent ID or token. 'ego' selects the ego vehicle. + + Returns: + Tuple[Optional[AgentTrajectory], List[ObjectTrack]]: (Target agent trajectory, other tracks). + """ + # Return the ego vehicle as the target for 'ego' or when no matching track is found. + if agent_token == 'ego': + target_agent = AgentTrajectory( + agent_id='ego', + agent_type='ego', + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + return target_agent, all_tracks + + # Find the requested agent. + target_track = None + other_tracks = [] + + for track in all_tracks: + # Match object_id directly or by its string representation. + if (track.object_id == agent_token or + str(track.object_id) == str(agent_token)): + target_track = track + else: + other_tracks.append(track) + + if target_track is None: + # Fall back to the ego vehicle if the requested agent is missing. + print(f"Warning: Agent token '{agent_token}' not found, using ego as default") + target_agent = AgentTrajectory( + agent_id='ego', + agent_type='ego', + positions=ego_trajectory.positions, + headings=ego_trajectory.headings, + velocities=ego_trajectory.velocities, + dimensions=ego_trajectory.dimensions, + valid_mask=ego_trajectory.valid_mask + ) + return target_agent, all_tracks + + # Convert the matching track to an AgentTrajectory. + target_agent = AgentTrajectory( + agent_id=target_track.object_id, + agent_type=target_track.object_type, + positions=target_track.positions, + headings=target_track.headings, + velocities=target_track.velocities, + dimensions=target_track.dimensions, + valid_mask=target_track.valid_mask + ) + + return target_agent, other_tracks diff --git a/projects/BWM/scripts/generation_general/processors/__init__.py b/projects/BWM/scripts/generation_general/processors/__init__.py new file mode 100644 index 0000000..9c11ff7 --- /dev/null +++ b/projects/BWM/scripts/generation_general/processors/__init__.py @@ -0,0 +1 @@ +"""Scene processing helpers used by the BWM generation pipeline.""" diff --git a/projects/BWM/scripts/generation_general/processors/data_converter.py b/projects/BWM/scripts/generation_general/processors/data_converter.py new file mode 100644 index 0000000..5bc5761 --- /dev/null +++ b/projects/BWM/scripts/generation_general/processors/data_converter.py @@ -0,0 +1,816 @@ +""" +Data conversion functionality for scene tensor and scene template formats. +""" +import sys +import os +import numpy as np +import torch +import pickle +from typing import List, Dict +from dataclasses import dataclass +import os +from pyquaternion import Quaternion +from nuplan.database.nuplan_db_orm.nuplandb import NuPlanDB +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import SceneTensor +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import ( + decode_scene_tensor, + VEH_PARAMS, + EGO_WIDTH, + EGO_LENGTH +) +from nuplan.common.actor_state.vehicle_parameters import get_pacifica_parameters +from nuplan.common.actor_state.state_representation import StateSE2 +from utils.nuplan_utils import ( + EGO, extract_traffic, extract_traffic_light, extract_map_features, NUPLAN_REAL_LIDAR2EGO_ROTATION, NUPLAN_REAL_LIDAR2EGO_TRANSLATION, + compute_angular_velocity, CanBus, is_vehicle_moving, extract_drivable_area +) + + +@dataclass +class SceneTensorWrapper: + scene_tensor: SceneTensor + trans: np.ndarray + center: np.ndarray + offset: np.ndarray + idx2token: List[str] + log_name: str + scenario_token: str + map_name: str + lidar_pc: List[str] + agent_type: List[str] + actual_past_timesteps: int + + +def read_openscene_data_infos(openscene_dataroot, log_name, lidar_pc_tokens): + """Read OpenScene data infos for given lidar pc tokens.""" + import pickle + openscene_data_infos = os.path.join(openscene_dataroot, 'meta_datas', 'trainval', f"{log_name}.pkl") + if not os.path.exists(openscene_data_infos): + openscene_data_infos = os.path.join(openscene_dataroot, 'meta_datas', 'test', f"{log_name}.pkl") + + if not os.path.exists(openscene_data_infos): + return {} # Return empty dict if openscene data not found + + try: + openscene_data_infos = pickle.load(open(openscene_data_infos, 'rb')) + openscene_data_dict = {frame['token']: frame for frame in openscene_data_infos} + openscene_data_dict = {token: openscene_data_dict[token] for token in lidar_pc_tokens if token in openscene_data_dict} + return openscene_data_dict + except Exception as e: + print(f"Warning: Failed to load OpenScene data: {e}") + return {} + +def get_agent_default_height(agent_type): + agent_type = agent_type.upper() + + if agent_type == "VEHICLE": + return 1.5 + elif agent_type == "PEDESTRIAN": + return 1.7 + elif agent_type == "BICYCLE": + return 1.2 + else: + return 1.5 + +def calculate_ego_in_agent_frames(info_dict): + """Calculate ego states in each agent's coordinate frame for angle statistics + + Returns: + dict: { + agent_id: { + 'position': [[x,y], ...], # relative position in agent frame + 'heading': [h, ...], # relative heading + 'velocity': [[vx,vy], ...], # relative velocity in agent frame + 'valid': [0/1, ...], # validity flag + 'angle': [a, ...], # angle between agent's heading and vector to ego [0, 2π] + 'angle_bin': [n0,n1,...,n11] # count of angles in each bin for valid frames + # bin 0: [0, π/6), bin 1: [π/6, π/3), ..., bin 11: [11π/6, 2π) + } + } + """ + ego_track = info_dict['object_track'][EGO] + ego_in_agent_frames = {} + + for agent_id, agent_track in info_dict['object_track'].items(): + if agent_id == EGO: + continue + + if agent_track['type'] != 'VEHICLE': + continue + + ego_in_agent_frames[agent_id] = { + 'position': [], # [x, y] in agent frame + 'heading': [], # relative heading + 'velocity': [], # relative velocity in agent frame + 'valid': [], # validity flag + 'angle': [], # continuous angle + 'angle_bin': [0] * 12 # initialize bin counts to zero + } + + for frame_idx in range(len(ego_track['state']['position'])): + if not (ego_track['state']['valid'][frame_idx] and agent_track['state']['valid'][frame_idx]): + ego_in_agent_frames[agent_id]['valid'].append(0) + ego_in_agent_frames[agent_id]['position'].append([0, 0]) + ego_in_agent_frames[agent_id]['heading'].append(0) + ego_in_agent_frames[agent_id]['velocity'].append([0, 0]) + ego_in_agent_frames[agent_id]['angle'].append(0) + continue + + # Get ego and agent states + ego_pos = np.array(ego_track['state']['position'][frame_idx][:2]) + ego_heading = ego_track['state']['heading'][frame_idx] + ego_vel = np.array(ego_track['state']['velocity'][frame_idx]) + + agent_pos = np.array(agent_track['state']['position'][frame_idx][:2]) + agent_heading = agent_track['state']['heading'][frame_idx] + agent_vel = np.array(agent_track['state']['velocity'][frame_idx]) + + # Calculate relative position and transform to agent frame + rel_pos = ego_pos - agent_pos + cos_h = np.cos(-agent_heading) + sin_h = np.sin(-agent_heading) + rot_matrix = np.array([[cos_h, -sin_h], + [sin_h, cos_h]]) + pos_in_agent = rot_matrix @ rel_pos + + # Calculate angle in agent's frame + angle = np.arctan2(pos_in_agent[1], pos_in_agent[0]) + angle = angle % (2 * np.pi) + + # Calculate angle bin and increment count + angle_bin = int(angle / (np.pi / 6.)) + angle_bin = min(11, max(0, angle_bin)) # Ensure bin index is within [0, 11] + ego_in_agent_frames[agent_id]['angle_bin'][angle_bin] += 1 + + # Calculate other relative states + rel_heading = ego_heading - agent_heading + rel_vel = ego_vel - agent_vel + vel_in_agent = rot_matrix @ rel_vel + + # Store results + ego_in_agent_frames[agent_id]['valid'].append(1) + ego_in_agent_frames[agent_id]['position'].append(pos_in_agent.tolist()) + ego_in_agent_frames[agent_id]['heading'].append(rel_heading) + ego_in_agent_frames[agent_id]['velocity'].append(vel_in_agent.tolist()) + ego_in_agent_frames[agent_id]['angle'].append(angle) + + return ego_in_agent_frames + +def convert_scene_tensor_wrapper_to_scene_template(scene_tensor_wrapper): + """ + Convert scene_tensor from local coordinate system to global coordinate system, + and construct a scene_template format dictionary with all position information in global coordinates. + + Notes: + - Ego vehicle is the agent at idx==0 in scene_tensor, using transformed global information. + - idx2token records all valid agents (including ego) tokens, in the same order as valid agents in scene_tensor. + - annotations only include non-ego agents (i>=1) that have token mappings. + + Args: + scene_tensor_wrapper: SceneTensorWrapper containing: + - scene_tensor: SceneTensor object with: + - tensor: np.ndarray, shape (NA, 21, 8), vehicle states across 21 frames, + dimensions: [x, y, cos(yaw), sin(yaw), vx, vy, length, width] + - validity: np.ndarray, shape (NA, 21), indicates if each vehicle is valid at each frame + - trans: 3x3 np.ndarray, homogeneous transformation matrix from local to global + - center: Center object with heading attribute (in radians) for angle transformation + (Note: ego global info comes from idx==0 in scene_tensor, not from center.x,y,heading) + - offset: np.ndarray, shape (2,), xy offset in global coordinate system + - idx2token: List[str], tokens for all valid agents (including ego) + - log_name: str + - scenario_token: str + - map_name: str + - lidar_pc: List[str], length 21, corresponding to 21 frame lidar_pc tokens + + Returns: + scene_template dictionary with format: + { + scene_metadata: { + log_name: ..., + map_name: ..., + initial_token: ..., + }, + frames: [ + { + token: , + ego_status: { + ego_pose: np.array([x, y, heading]), # Global coordinates (ego is idx==0 agent) + ego_velocity: np.array([vx, vy]), # Global coordinates + ego_acceleration: np.array([ax, ay]), # Global coordinates (set to 0) + }, + annotations: { + boxes: np.array([ + [x, y, z, l, w, h, heading], # Global coordinates, z, h set to 0 + ... + ]), + velocity_3d: np.array([ + [vx, vy, vz], # Global coordinates, vz set to 0 + ... + ]), + names: [ "vehicle", ... ], + track_tokens: [ token, ... ] + } + }, + ... + ] + } + """ + # Unpack fields from scene_tensor_wrapper + st = scene_tensor_wrapper.scene_tensor # SceneTensor object + trans = scene_tensor_wrapper.trans # 3x3 local -> global + # Only use heading from center for angle transformation + center = scene_tensor_wrapper.center # Assumed to have center.heading + offset = scene_tensor_wrapper.offset # xy offset in global coordinates, shape (2,) + idx2token = scene_tensor_wrapper.idx2token # List[str], tokens for all valid agents (including ego) + log_name = scene_tensor_wrapper.log_name + scenario_token = scene_tensor_wrapper.scenario_token + map_name = scene_tensor_wrapper.map_name + lidar_pc = scene_tensor_wrapper.lidar_pc # List[str], 21 frames + agent_type = scene_tensor_wrapper.agent_type + + # Get scene_tensor data: tensor and validity in local coordinates + # The tensor here is normalized data, need to denormalize to get real local coordinates + tensor = decode_scene_tensor(st.tensor) # shape: (NA, 21, 8) - denormalized local coordinates + validity = st.validity # shape: (NA, 21) + num_vehicles, num_timesteps, _ = tensor.shape + + # Construct valid agent token mapping + # Record all agent indices that are valid in any frame, in same order as idx2token + valid_indices = [i for i in range(num_vehicles) if np.any(validity[i, :] >= 0.5)] + + # Safety check: if valid_indices length exceeds idx2token length, create default tokens + if len(valid_indices) > len(idx2token): + print(f"Warning: Valid agent count ({len(valid_indices)}) exceeds token list length ({len(idx2token)})") + print("Creating default values for missing tokens") + # Create default tokens for each missing agent + missing_count = len(valid_indices) - len(idx2token) + for i in range(missing_count): + idx2token.append(f"default_token_{i}") + + # Ensure agent_type list is also extended to match the number of valid_indices + while len(agent_type) < len(valid_indices): + agent_type.append("vehicle") # Default type is vehicle + + # Build agent index to token mapping + agent_token_mapping = {i: idx2token[k] for k, i in enumerate(valid_indices) if k < len(idx2token)} + + # Local to global coordinate transformation + # Note: our tensor is now denormalized local coordinates + + # Position transformation: apply homogeneous coordinate transformation to (x, y) and add offset + xy_local = tensor[:, :, 0:2] # (NA, 21, 2) - local coordinates + ones = np.ones((num_vehicles, num_timesteps, 1)) + xy_local_h = np.concatenate([xy_local, ones], axis=-1) # (NA, 21, 3) + xy_global_h = np.einsum('ij,ntj->nti', trans, xy_local_h) + xy_global = xy_global_h[:, :, :2] + offset + # Update global_tensor (x, y) + global_tensor = tensor.copy() + global_tensor[:, :, 0:2] = xy_global + + # Angle transformation: local yaw = arctan2(sin, cos) + center.heading + local_yaw = np.arctan2(tensor[:, :, 3], tensor[:, :, 2]) + global_yaw = local_yaw + center.heading + global_tensor[:, :, 2] = np.cos(global_yaw) + global_tensor[:, :, 3] = np.sin(global_yaw) + + # Velocity transformation: rotate local velocity to global coordinates + local_vel = tensor[:, :, 4:6] # (NA, 21, 2) + ch = center.heading + rot = np.array([[np.cos(ch), -np.sin(ch)], + [np.sin(ch), np.cos(ch)]]) + global_vel = np.einsum('ij,ntj->nti', rot, local_vel) + global_tensor[:, :, 4:6] = global_vel + + # Construct scene_template + frames_list = [] + for t in range(num_timesteps): + # Ego information: directly use idx==0 data from scene_tensor (assume ego is always valid) + ego_x = global_tensor[0, t, 0] + ego_y = global_tensor[0, t, 1] + ego_yaw = np.arctan2(global_tensor[0, t, 3], global_tensor[0, t, 2]) + ego_pose = np.array([ego_x, ego_y, ego_yaw]) + ego_velocity = global_tensor[0, t, 4:6] + ego_acceleration = np.array([0.0, 0.0]) # Set to 0 for now + + boxes = [] + velocities = [] + names = [] + track_tokens = [] + # annotations only include non-ego agents (i>=1) that have token mappings + for i in range(1, num_vehicles): + if validity[i, t] < 0.5: + continue + if i not in agent_token_mapping: + continue + x = global_tensor[i, t, 0] + y = global_tensor[i, t, 1] + length = global_tensor[i, t, 6] + width = global_tensor[i, t, 7] + yaw = np.arctan2(global_tensor[i, t, 3], global_tensor[i, t, 2]) + # Construct box: [x, y, z, l, w, h, heading], z, h set to 0 for now + box = [x, y, 0.0, length, width, 0.0, yaw] + boxes.append(box) + vx = global_tensor[i, t, 4] + vy = global_tensor[i, t, 5] + velocities.append([vx, vy, 0.0]) + names.append(agent_type[i]) + token = agent_token_mapping[i] + track_tokens.append(token) + + frame_dict = dict( + token=lidar_pc[t], + ego_status=dict( + ego_pose=ego_pose, # From idx==0 global information + ego_velocity=ego_velocity, + ego_acceleration=ego_acceleration, + ), + annotations=dict( + boxes = np.array(boxes) if boxes else np.empty((0, 7)), + velocity_3d = np.array(velocities) if velocities else np.empty((0, 3)), + names = names, + track_tokens = track_tokens, + ) + ) + frames_list.append(frame_dict) + + scene_template = dict( + scene_metadata=dict( + log_name=log_name, + map_name=map_name, + initial_token=scenario_token, + ), + frames=frames_list + ) + + return scene_template + + +def to_tensor(scene_tensor_wrapper, device=None): + """ + Convert a SceneTensorWrapper to a torch.Tensor. + """ + scene_tensor = scene_tensor_wrapper.scene_tensor + tensor = scene_tensor.tensor + validity = scene_tensor.validity + road_graph = scene_tensor.road_graph + road_graph_validity = scene_tensor.road_graph_validity + + # Convert to tensors and move to device if specified + scene_tensor.tensor = torch.tensor(tensor, dtype=torch.float32) + scene_tensor.validity = torch.tensor(validity, dtype=torch.float32) # Changed from bool to float32 + scene_tensor.road_graph = torch.tensor(road_graph, dtype=torch.float32) + scene_tensor.road_graph_validity = torch.tensor(road_graph_validity, dtype=torch.float32) # Changed from bool to float32 + + # Move to device if specified + if device is not None: + scene_tensor.tensor = scene_tensor.tensor.to(device) + scene_tensor.validity = scene_tensor.validity.to(device) + scene_tensor.road_graph = scene_tensor.road_graph.to(device) + scene_tensor.road_graph_validity = scene_tensor.road_graph_validity.to(device) + + scene_tensor_wrapper.scene_tensor = scene_tensor + return scene_tensor_wrapper + + +def to_numpy(scene_tensor_wrapper): + """ + Convert a SceneTensorWrapper to a NumPy array. + """ + scene_tensor = scene_tensor_wrapper.scene_tensor + + # Move tensors to CPU first if they are on GPU, then convert to numpy + if isinstance(scene_tensor.tensor, torch.Tensor): + tensor = scene_tensor.tensor.detach().cpu().numpy() + else: + tensor = scene_tensor.tensor + + if isinstance(scene_tensor.validity, torch.Tensor): + validity = scene_tensor.validity.detach().cpu().numpy() + else: + validity = scene_tensor.validity + + if isinstance(scene_tensor.road_graph, torch.Tensor): + road_graph = scene_tensor.road_graph.detach().cpu().numpy() + else: + road_graph = scene_tensor.road_graph + + if isinstance(scene_tensor.road_graph_validity, torch.Tensor): + road_graph_validity = scene_tensor.road_graph_validity.detach().cpu().numpy() + else: + road_graph_validity = scene_tensor.road_graph_validity + + scene_tensor.tensor = tensor + scene_tensor.validity = validity + scene_tensor.road_graph = road_graph + scene_tensor.road_graph_validity = road_graph_validity + + scene_tensor_wrapper.scene_tensor = scene_tensor + return scene_tensor_wrapper + + +def dynamic_vehicle_filter(scene_tensor_wrapper: 'SceneTensorWrapper', movement_threshold: float = 3.0) -> 'SceneTensorWrapper': + """ + Filter scene_tensor_wrapper to keep only dynamic vehicles (vehicles that move more than the threshold). + + Args: + scene_tensor_wrapper: Input SceneTensorWrapper with all vehicles + movement_threshold: Minimum cumulative displacement in meters to be considered dynamic + + Returns: + SceneTensorWrapper: Filtered wrapper containing only dynamic vehicles + """ + # Get scene tensor and validity data + scene_tensor = scene_tensor_wrapper.scene_tensor + validity = scene_tensor.validity + tensor_data = scene_tensor.tensor + + # Index 0 is always ego vehicle - always keep it + dynamic_indices = [0] + + num_agents = tensor_data.shape[0] + + for i in range(1, len(scene_tensor_wrapper.agent_type)): + if i >= len(scene_tensor.tensor): + break + + agent_type = scene_tensor_wrapper.agent_type[i].upper() + if agent_type != 'VEHICLE': + continue + + # Then check if this vehicle is dynamic + if is_vehicle_moving(tensor_data, i, validity, movement_threshold): + dynamic_indices.append(i) + + # If no filtering needed (all vehicles are dynamic), return original + if len(dynamic_indices) == num_agents: + return scene_tensor_wrapper + + # Directly modify the original SceneTensor + filtered_tensor = tensor_data[dynamic_indices] + filtered_validity = validity[dynamic_indices] + + # Update the original SceneTensor's data + scene_tensor.tensor = filtered_tensor + scene_tensor.validity = filtered_validity + + # Filter other arrays that correspond to agents + filtered_idx2token = [] + filtered_agent_type = [] + + for i, orig_idx in enumerate(dynamic_indices): + # Handle idx2token array + if orig_idx < len(scene_tensor_wrapper.idx2token): + filtered_idx2token.append(scene_tensor_wrapper.idx2token[orig_idx]) + else: + filtered_idx2token.append(f"dynamic_agent_{i}") + + # Handle agent_type array + if orig_idx < len(scene_tensor_wrapper.agent_type): + filtered_agent_type.append(scene_tensor_wrapper.agent_type[orig_idx]) + else: + filtered_agent_type.append("VEHICLE") + + scene_tensor_wrapper.idx2token = filtered_idx2token + scene_tensor_wrapper.agent_type = filtered_agent_type + + return scene_tensor_wrapper + +def convert_scene_tensor_wrapper_to_scenario_description( + scene_tensor_wrapper, + map_api, + data_root, + openscene_data_root, + digitaltwin_data_root, + keep_dynamic_vehicle_only=False +): + """ + Convert a SceneTensorWrapper to scenario description. + This generates ONE scenario that contains all frames, which is what WorldEngine expects. + + Args: + scene_tensor_wrapper: The SceneTensorWrapper object containing original nuPlan data references + map_api: NuPlan map API instance for extracting map features + data_root: Path to nuPlan data root directory + openscene_data_root: Path to OpenScene metadata + digitaltwin_data_root: Path to WorldEngine DigitalTwin assets + keep_dynamic_vehicle_only: Whether to keep only dynamic vehicles in the scenario + + Returns: + Dictionary containing a single complete scenario description with all frames: + { + "{scenario_id}": { + "id": str, # Scenario identifier + "name": str, # Same as id + "dataset": "bwm.nuplan", # Dataset identifier + "map": str, # Map name + "token": str, # Scenario token + "log_length": int, # Total number of frames (13) + "sample_rate": int, # Stride at nuPlan's 20 Hz (10 for 2 Hz) + "base_timestamp": int, # Base timestamp + "sdc_id": "ego", # Self-driving car identifier + + "metadata": { + "old_origin_in_current_coordinate": np.array([x, y]), + "nuplan_lidar_pc_tokens": [str, ...], # ALL lidar tokens for all frames + "log_name": str, + "total_frames": int, + "openscene_data_infos_dict": dict, # ALL frames' openscene data + "scenario_token": str, + "original_log_length": int, + "ego_agent_angle_stats": dict, + "digitaltwin_ego2globals": list, # All ego2global matrices + }, + + "cameras": dict, # Camera calibration info + "lidar": dict, # LiDAR calibration info + + "object_track": { # MULTI-FRAME object tracks + "ego": { + "type": "VEHICLE", + "state": { + "position": np.array([[x,y,z], ...]), # Shape: (total_frames, 3) + "heading": np.array([h, ...]), # Shape: (total_frames,) + "velocity": np.array([[vx,vy], ...]), # Shape: (total_frames, 2) + "valid": np.array([1.0, ...]), # Shape: (total_frames,) + "length": np.array([l, ...]), # Shape: (total_frames,) + "width": np.array([w, ...]), # Shape: (total_frames,) + "height": np.array([h, ...]), # Shape: (total_frames,) + }, + "metadata": { + "type": "VEHICLE", + "track_length": total_frames, + "object_id": "ego", + "nuplan_type": "ego" + } + }, + # ... other agents with same multi-frame structure + }, + + "map_features": dict, # Map features + "dynamic_map_states": dict, # Traffic light states + } + } + """ + ######################################################### + # 1. Load necessary information + ######################################################### + if keep_dynamic_vehicle_only: + scene_tensor_wrapper = dynamic_vehicle_filter(scene_tensor_wrapper) + + scene_tensor = scene_tensor_wrapper.scene_tensor + trans = scene_tensor_wrapper.trans + offset = scene_tensor_wrapper.offset + agent_type = scene_tensor_wrapper.agent_type + lidar_pc_tokens = scene_tensor_wrapper.lidar_pc + map_name = scene_tensor_wrapper.map_name + scenario_token = scene_tensor_wrapper.scenario_token + idx2token = scene_tensor_wrapper.idx2token + agent_type = scene_tensor_wrapper.agent_type + log_name = scene_tensor_wrapper.log_name + center = scene_tensor_wrapper.center + actual_past_timesteps = scene_tensor_wrapper.actual_past_timesteps + original_center = [center.x, center.y] + + scenario_description = {} + + ######################################################### + # 2. Get basic information + ######################################################### + scenario_id = f"{log_name}-{scenario_token}" + scenario_description["id"] = scenario_id + scenario_description["name"] = scenario_id + scenario_description["dataset"] = "bwm.nuplan" + scenario_description["map"] = map_name + scenario_description["token"] = scenario_id + scenario_description["log_length"] = len(lidar_pc_tokens) + # SimEngine stores the stride relative to nuPlan's 20 Hz, not frequency. + # BWM uses the 2 Hz OpenScene sequence: 10 * 0.05 s = 0.5 s per frame. + scenario_description["sample_rate"] = 10 + + db = NuPlanDB(data_root=data_root, load_path=log_name) + log_file_path = os.path.join(data_root, f"{log_name}.db") + lidar_pc = db.lidar_pc.get(token=lidar_pc_tokens[0]) + scenario_description["base_timestamp"] = lidar_pc.timestamp + scenario_description["sdc_id"] = EGO + + + ######################################################### + # 3. Get metadata + ######################################################### + metadata = {} + + metadata["old_origin_in_current_coordinate"] = -np.asarray(original_center) + metadata["nuplan_lidar_pc_tokens"] = lidar_pc_tokens + metadata["log_name"] = log_name + metadata["total_frames"] = len(lidar_pc_tokens) + metadata["openscene_data_infos_dict"] = read_openscene_data_infos( + openscene_data_root, + log_name, + lidar_pc_tokens, + ) + metadata["scenario_token"] = scenario_token + metadata["original_log_length"] = len(lidar_pc_tokens) + metadata["actual_past_timesteps"] = actual_past_timesteps + metadata["ego_agent_angle_stats"] = {} # Will be calculated below + + if not digitaltwin_data_root: + raise ValueError("digitaltwin_data_root is required") + digitaltwin_data_folder = os.path.join(digitaltwin_data_root, f"{log_name}-{scenario_token}") + + with open(os.path.join(digitaltwin_data_folder, "video_scene_dict.pkl"), "rb") as f: + digitaltwin_video_scene_dict = pickle.load(f) + video_info = list(digitaltwin_video_scene_dict.values())[0] + metadata["digitaltwin_ego2globals"] = [info['ego2global'] for info in video_info['frame_infos']] + + scenario_description["metadata"] = metadata + + ######################################################### + # 4. Get camera and lidar information + ######################################################### + cams = {} + log_cam_infos = {camera.token : camera for camera in db.log.cameras} + for cam_info in log_cam_infos.values(): + cam_name = cam_info.channel + + # obtain calibrated camera info in digitaltwin + digitaltwin_cam_info = video_info['frame_infos'][0]['cams'][cam_name] + if 'colmap_param' in digitaltwin_cam_info: + intrinsic = digitaltwin_cam_info['colmap_param']['cam_intrinsic'] + distortion = digitaltwin_cam_info['colmap_param']['distortion'] + else: + intrinsic = digitaltwin_cam_info['cam_intrinsic'] + distortion = digitaltwin_cam_info['distortion'] + + cams[cam_name] = {} + cams[cam_name]['channel'] = cam_info.channel + cams[cam_name]['sensor2ego_rotation'] = cam_info.quaternion.elements + cams[cam_name]['sensor2ego_translation'] = cam_info.translation_np + cams[cam_name]['intrinsic'] = intrinsic + cams[cam_name]['distortion'] = distortion + cams[cam_name]['height'] = 1080 + cams[cam_name]['width'] = 1920 + + lidar_info = { + "channel": "LIDAR_TOP", + "sensor2ego_rotation": np.array(NUPLAN_REAL_LIDAR2EGO_ROTATION), + "sensor2ego_translation": np.array(NUPLAN_REAL_LIDAR2EGO_TRANSLATION), + } + + scenario_description["cameras"] = cams + scenario_description["lidar"] = lidar_info + + ######################################################### + # 5. Get object tracks + ######################################################### + object_tracks = {} + + # Transform object tensor to global coordinates + object_tensor = decode_scene_tensor(scene_tensor.tensor) + object_validity = scene_tensor.validity + num_vehicles, num_timesteps, _ = object_tensor.shape + valid_indices = [i for i in range(num_vehicles) if np.any(object_validity[i, :] >= 0.5)] + if len(valid_indices) > len(idx2token): + missing_count = len(valid_indices) - len(idx2token) + for i in range(missing_count): + idx2token.append(f"default_token_{i}") + while len(agent_type) < len(valid_indices): + agent_type.append("VEHICLE") + agent_token_mapping = {i: idx2token[k] for k, i in enumerate(valid_indices) if k < len(idx2token)} + + xy_local = object_tensor[:, :, 0:2] + ones = np.ones((num_vehicles, num_timesteps, 1)) + xy_local_h = np.concatenate([xy_local, ones], axis=-1) + xy_global_h = np.einsum('ij,ntj->nti', trans, xy_local_h) + xy_global = xy_global_h[:, :, :2] + offset + global_tensor = object_tensor.copy() + global_tensor[:, :, 0:2] = xy_global + local_yaw = np.arctan2(object_tensor[:, :, 3], object_tensor[:, :, 2]) + global_yaw = local_yaw + center.heading + global_tensor[:, :, 2] = np.cos(global_yaw) + global_tensor[:, :, 3] = np.sin(global_yaw) + local_vel = object_tensor[:, :, 4:6] + ch = center.heading + rot = np.array([[np.cos(ch), -np.sin(ch)], + [np.sin(ch), np.cos(ch)]]) + global_vel = np.einsum('ij,ntj->nti', rot, local_vel) + global_tensor[:, :, 4:6] = global_vel + + ego_vehicle_tensor = global_tensor[0] + ego_vehicle_validity = object_validity[0] + ego_position = ego_vehicle_tensor[:, 0:2] + ego_heading = np.arctan2(ego_vehicle_tensor[:, 3], ego_vehicle_tensor[:, 2]) + + # BWM represents ego at the rear axle; SimEngine object_track positions + # are vehicle centers. SimEngine converts back to the rear axle for rendering. + rear_axle_to_center_dist = get_pacifica_parameters().rear_axle_to_center + ego_center_position = ego_position + rear_axle_to_center_dist * np.column_stack( + (np.cos(ego_heading), np.sin(ego_heading)) + ) + + # Use the same local origin as other agents and map features, and add z=0. + ego_position = np.concatenate([ + ego_center_position - original_center, + np.zeros((ego_center_position.shape[0], 1)), + ], axis=1) + + ego_velocity = ego_vehicle_tensor[:, 4:6] + ego_valid = ego_vehicle_validity + ego_total_frames = np.sum(ego_valid > 0.5) + assert ego_total_frames == len(lidar_pc_tokens), "Ego vehicle must valid in all frames" + + # Store ego in the same vehicle-center convention as SimEngine's converter. + ego_track = {} + ego_track["type"] = "VEHICLE" + ego_track["state"] = { + "position": ego_position, + "heading": ego_heading, + "velocity": ego_velocity, + "valid": ego_valid, + "length": np.full((ego_total_frames, 1), get_pacifica_parameters().length), + 'width': np.full((ego_total_frames, 1), get_pacifica_parameters().width), + 'height': np.full((ego_total_frames, 1), get_pacifica_parameters().height) + } + ego_track["metadata"] = { + "type": "VEHICLE", + "track_length": ego_total_frames, + "object_id": "ego", + 'nuplan_type': 'ego', + 'coordinate_system': 'center' + } + object_tracks["ego"] = ego_track + + for k in range(1, len(valid_indices)): + i = valid_indices[k] + agent_track = {} + + agent_track['type'] = agent_type[i].upper() + + agent_position = global_tensor[i, :, 0:2] - original_center + agent_position = np.concatenate([agent_position, np.zeros((agent_position.shape[0], 1))], axis=1) + + agent_heading = np.arctan2(global_tensor[i, :, 3], global_tensor[i, :, 2]) + agent_velocity = global_tensor[i, :, 4:6] + agent_valid = object_validity[i] + agent_total_frames = np.sum(agent_valid > 0.5) + agent_length = global_tensor[i, :, 6:7] # Keep 2D shape (N, 1) + agent_width = global_tensor[i, :, 7:8] # Keep 2D shape (N, 1) + agent_height = get_agent_default_height(agent_type[i]) * np.ones((num_timesteps, 1)) + + + agent_track['state'] = { + 'position': agent_position, + 'heading': agent_heading, + 'velocity': agent_velocity, + 'valid': agent_valid, + 'length': agent_length, + 'width': agent_width, + 'height': agent_height + } + agent_track['metadata'] = { + 'type': agent_type[i].upper(), + 'track_length': agent_total_frames, + 'object_id': idx2token[i], + 'nuplan_id': idx2token[i], + 'nuplan_type': agent_type[i] + } + + object_tracks[idx2token[i]] = agent_track + + scenario_description["object_track"] = object_tracks + ######################################################### + # 6. Get map features + ######################################################### + map_features = extract_map_features( + map_api=map_api, + initial_ego_center=original_center + ) + + scenario_description["map_features"] = map_features + # Persist complete DAC geometry separately from SimEngine's lane topology. + metadata["drivable_area"] = extract_drivable_area(map_api, original_center) + + ######################################################### + # 7. Get dynamic map states + ######################################################### + all_lidar_pcs = [db.lidar_pc.get(token=token) for token in lidar_pc_tokens if db.lidar_pc.get(token=token)] + + dynamic_map_states = extract_traffic_light( + log_file=log_file_path, + lidar_pcs=all_lidar_pcs, + map_api=map_api, + initial_ego_center=original_center, + ) + scenario_description["dynamic_map_states"] = dynamic_map_states + + + ######################################################### + # 8. fill some missing information and return scenario description + ######################################################### + if len(object_tracks) > 1: + ego_in_agent_frames = calculate_ego_in_agent_frames(scenario_description) + scenario_description['metadata']['ego_agent_angle_stats'] = { + agent_id: frames_info['angle_bin'] + for agent_id, frames_info in ego_in_agent_frames.items() + } + + return {scenario_id: scenario_description} diff --git a/projects/BWM/scripts/generation_general/processors/feature_processor.py b/projects/BWM/scripts/generation_general/processors/feature_processor.py new file mode 100644 index 0000000..66e49af --- /dev/null +++ b/projects/BWM/scripts/generation_general/processors/feature_processor.py @@ -0,0 +1,271 @@ +""" +Feature processing functionality for scene tensor computation. +""" +import sys +import numpy as np +from typing import List +from collections import Counter + +from nuplan.planning.training.preprocessing.feature_builders.abstract_feature_builder import AbstractFeatureBuilder +from nuplan_extent.planning.training.preprocessing.feature_builders.horizon_vector_feature_builder_v2 import HorizonVectorV2 +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import ( + SceneTensor, + N_SCENE_TENSOR_FEATURES, + FEATURE_MEANS, + FEATURE_STD, + encode_agent, + encode_ego +) + +from processors.data_converter import SceneTensorWrapper + + +def compute_features(builder: AbstractFeatureBuilder, vector_data: HorizonVectorV2) -> SceneTensorWrapper: + """ + Compute scene tensor features from vector data. + + Args: + builder: Feature builder instance + vector_data: HorizonVectorV2 containing agent and map data + + Returns: + SceneTensorWrapper with computed features + """ + vehicles = vector_data.data["agents"]["VEHICLE"] # n_timesteps x n_agents x 9 + peds = vector_data.data["agents"]["PEDESTRIAN"] + bic = vector_data.data["agents"]["BICYCLE"] + ego = vector_data.data["ego"] # t x 7 tensor + track_token_id_mapping = vector_data.data['track_token_id_mapping'] + + map_name = vector_data.data['map_name'] + log_name = vector_data.data['log_name'] + lidar_pc = vector_data.data['lidarpc'] + scenario_token = vector_data.data['scenario_token'] + offset = vector_data.data['offset'] + center = vector_data.data['center'] + trans = vector_data.data['trans'] + actual_past_timesteps = vector_data.data['actual_past_timesteps'] + + n_timesteps = len(vehicles) + + # Get all unique track IDs + ids_veh = np.unique(vehicles[..., 0]) + ids_ped = np.unique(peds[..., 0]) + ids_bic = np.unique(bic[..., 0]) + + idx2token = ['ego'] + agent_type = ['vehicle'] + n_max_agents = 128 + + # Initialize scene tensor and validity arrays + scene_tensor = np.zeros((n_max_agents, n_timesteps, N_SCENE_TENSOR_FEATURES)) + scene_tensor_validity = np.zeros((n_max_agents, n_timesteps)) + + n_agents = 0 + valid_vehicle_count = 0 + for i, id_ in enumerate(ids_veh): + if i >= builder._num_max_agents[0]: + break + # only treat agent that appears in more than 5 frames as valid + mask = vehicles[..., 0] == id_ + time_validity_ = mask.sum(axis=1).astype(bool) + if time_validity_.sum() < 5: + continue + valid_vehicle_count += 1 + + # Special handling for database_loader data format + # vehicles data format: [id, x, y, yaw, vx, vy, length, width, height] + agent_data = vehicles[mask] # shape: (n_valid_timesteps, 9) + + # Rearrange data to match encode_agent expected format + # encode_agent expects: [x, y, heading, vx, vy, length, width] + encoded_agent = np.stack([ + agent_data[:, 1], # x + agent_data[:, 2], # y + np.cos(agent_data[:, 3]), # cos(yaw) + np.sin(agent_data[:, 3]), # sin(yaw) + agent_data[:, 4], # vx + agent_data[:, 5], # vy + agent_data[:, 6], # length + agent_data[:, 7], # width + ], axis=1) + + if encoded_agent.shape[0] != time_validity_.sum(): + print(f"[DEBUG] encoded_agent.shape[0] != time_validity_.sum(), truncate encoded_agent") + encoded_agent = encoded_agent[:time_validity_.sum()] + scene_tensor[n_agents, time_validity_] = encoded_agent + scene_tensor_validity[n_agents] = time_validity_ + + # Add all valid vehicles to idx2token + try: + # Try to find token + id_int = int(id_) + + # Try different key formats + keys_to_try = [id_int, str(id_int)] + found = False + + for key in keys_to_try: + if key in track_token_id_mapping['VEHICLE']: + idx2token.append(track_token_id_mapping['VEHICLE'][key]) + agent_type.append('vehicle') + n_agents += 1 + found = True + break + except Exception: + pass + + for i, id_ in enumerate(ids_ped): + if i >= builder._num_max_agents[1]: + break + # only treat agent that appears in more than 5 frames as valid + mask = peds[..., 0] == id_ + time_validity_ = mask.sum(axis=1).astype(bool) + if time_validity_.sum() < 5: + continue + + # Special handling for database_loader data format + # peds data format: [id, x, y, yaw, vx, vy, length, width, height] + agent_data = peds[mask] # shape: (n_valid_timesteps, 9) + + # Rearrange data to match encode_agent expected format + encoded_agent = np.stack([ + agent_data[:, 1], # x + agent_data[:, 2], # y + np.cos(agent_data[:, 3]), # cos(yaw) + np.sin(agent_data[:, 3]), # sin(yaw) + agent_data[:, 4], # vx + agent_data[:, 5], # vy + agent_data[:, 6], # length + agent_data[:, 7], # width + ], axis=1) + + if encoded_agent.shape[0] != time_validity_.sum(): + encoded_agent = encoded_agent[:time_validity_.sum()] + scene_tensor[n_agents, time_validity_] = encoded_agent + scene_tensor_validity[n_agents] = time_validity_ + + # Add all valid pedestrians to idx2token + try: + # Try to find token + id_int = int(id_) + + # Try different key formats + keys_to_try = [id_int, str(id_int)] + found = False + + for key in keys_to_try: + if key in track_token_id_mapping['PEDESTRIAN']: + idx2token.append(track_token_id_mapping['PEDESTRIAN'][key]) + agent_type.append('pedestrian') + n_agents += 1 + found = True + break + except Exception: + pass + + for i, id_ in enumerate(ids_bic): + if i >= builder._num_max_agents[2]: + break + # only treat agent that appears in more than 5 frames as valid + mask = bic[..., 0] == id_ + time_validity_ = mask.sum(axis=1).astype(bool) + if time_validity_.sum() < 5: + continue + + # Special handling for database_loader data format + # bic data format: [id, x, y, yaw, vx, vy, length, width, height] + agent_data = bic[mask] # shape: (n_valid_timesteps, 9) + + # Rearrange data to match encode_agent expected format + encoded_agent = np.stack([ + agent_data[:, 1], # x + agent_data[:, 2], # y + np.cos(agent_data[:, 3]), # cos(yaw) + np.sin(agent_data[:, 3]), # sin(yaw) + agent_data[:, 4], # vx + agent_data[:, 5], # vy + agent_data[:, 6], # length + agent_data[:, 7], # width + ], axis=1) + + if encoded_agent.shape[0] != time_validity_.sum(): + encoded_agent = encoded_agent[:time_validity_.sum()] + scene_tensor[n_agents, time_validity_] = encoded_agent + scene_tensor_validity[n_agents] = time_validity_ + + # Add all valid bicycles to idx2token + try: + # Try to find token + id_int = int(id_) + + # Try different key formats + keys_to_try = [id_int, str(id_int)] + found = False + + for key in keys_to_try: + if key in track_token_id_mapping['BICYCLE']: + idx2token.append(track_token_id_mapping['BICYCLE'][key]) + agent_type.append('bicycle') + n_agents += 1 + found = True + break + except Exception: + pass + + # Append the ego state + ego_state = encode_ego(ego) + + scene_tensor = np.concatenate( + [np.expand_dims(ego_state, 0), scene_tensor], axis=0 + ) + + # Normalize the scene tensor + scene_tensor = (scene_tensor - np.array(FEATURE_MEANS)) / ( + 2.0 * np.array(FEATURE_STD) + ) + scene_tensor_validity = np.concatenate( + [np.ones((1, n_timesteps)), scene_tensor_validity], axis=0 + ) + + # Encode road graph + road_graph = np.zeros( + shape=( + builder._map_num_max_polylines, + builder._map_num_points_polylines, + builder._map_dim_points_polyline, + ), + dtype=np.float32, + ) + road_graph_validity = np.zeros_like(road_graph) + map_data = vector_data.data["map"] + + for i in range(min(builder._map_num_max_polylines, len(map_data))): + road_graph[i], road_graph_validity[i] = builder._encode_map_object(map_data[i]) + + # Apply normalization for local coordinates - now map data is also in local coordinates + road_graph[..., :2] = (road_graph[..., :2] - np.array(FEATURE_MEANS)[:2]) / ( + 2 * np.array(FEATURE_STD)[:2] + ) + + scene_tensor = SceneTensor( + tensor=scene_tensor.astype(np.float32), + validity=scene_tensor_validity.astype(np.float32), + road_graph=road_graph.astype(np.float32), + road_graph_validity=road_graph_validity.astype(np.float32), + ) + + scene_tensor_wrapper = SceneTensorWrapper( + scene_tensor=scene_tensor, + trans=trans, + center=center, + offset=offset, + idx2token=idx2token, + log_name=log_name, + scenario_token=scenario_token, + map_name=map_name, + lidar_pc=lidar_pc, + agent_type=agent_type, + actual_past_timesteps=actual_past_timesteps + ) + return scene_tensor_wrapper \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/processors/scene_generator_v2.py b/projects/BWM/scripts/generation_general/processors/scene_generator_v2.py new file mode 100644 index 0000000..97d67be --- /dev/null +++ b/projects/BWM/scripts/generation_general/processors/scene_generator_v2.py @@ -0,0 +1,453 @@ +""" +Scene generation functionality including task masks and model inference. +""" +import sys +import copy +import torch +from torch.cuda.amp import autocast +from typing import Dict +from collections import Counter +import numpy as np + +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import SceneTensor, decode_scene_tensor, encode_scene_tensor, unnormalize_roadgraph +from processors.data_converter import SceneTensorWrapper +from utils.nuplan_utils import is_vehicle_moving +from utils.config_loader import resolve_motion_limits +from utils.motion_validation import validate_generated_motion + +def unsqueeze(features: Dict): + """ + Add batch dimension to tensors in features dictionary. + """ + scene_tensor = features['scene_tensor'] + task_mask = features['task_mask'] + + # Extract relevant tensors from scene_tensor + tensor = scene_tensor.tensor + validity = scene_tensor.validity + road_graph = scene_tensor.road_graph + road_graph_validity = scene_tensor.road_graph_validity + + # Use unsqueeze to add an extra dimension at position 0 + tensor = tensor.unsqueeze(0) # Correct method is unsqueeze + validity = validity.unsqueeze(0) + road_graph = road_graph.unsqueeze(0) + road_graph_validity = road_graph_validity.unsqueeze(0) + task_mask = task_mask.unsqueeze(0) + + return { + 'task_mask': task_mask, + 'scene_tensor': SceneTensor(tensor, validity, road_graph, road_graph_validity) + } + + +def squeeze(features: Dict): + """ + Remove batch dimension from tensors in features dictionary. + """ + scene_tensor = features['scene_tensor'] + task_mask = features['task_mask'] + + # Extract relevant tensors from scene_tensor + tensor = scene_tensor.tensor + validity = scene_tensor.validity + road_graph = scene_tensor.road_graph + road_graph_validity = scene_tensor.road_graph_validity + + # Use squeeze to remove dimensions of size 1 + tensor = tensor.squeeze(0) # Removes the dimension at position 0 if it's size 1 + validity = validity.squeeze(0) + road_graph = road_graph.squeeze(0) + road_graph_validity = road_graph_validity.squeeze(0) + task_mask = task_mask.squeeze(0) + + # Return the modified tensors in the same structure + return { + 'task_mask': task_mask, + 'scene_tensor': SceneTensor(tensor, validity, road_graph, road_graph_validity) + } + + +def filter_nearby_vehicles(scene_tensor_features, dynamic_vehicle_indices): + """Filter moving vehicles by distance and heading constraints.""" + ego_pos_norm = scene_tensor_features.tensor[0, 4, :2] + ego_heading_norm = scene_tensor_features.tensor[0, 4, 2:4] + + ego_pos = ego_pos_norm * 2.0 * 52.0 + 0.0 + ego_heading = torch.atan2(ego_heading_norm[1], ego_heading_norm[0]) + + nearby_vehicles = [] + lateral_threshold = 5.0 + longitudinal_threshold = 15.0 + + for vehicle_idx in dynamic_vehicle_indices: + if (vehicle_idx >= len(scene_tensor_features.tensor) or + scene_tensor_features.validity[vehicle_idx, 4] <= 0.5): + continue + + # Get the vehicle position. + vehicle_pos_norm = scene_tensor_features.tensor[vehicle_idx, 4, :2] + vehicle_pos = vehicle_pos_norm * 2.0 * 52.0 + 0.0 + + # Compute the relative position. + relative_pos = vehicle_pos - ego_pos + ego_forward = torch.stack([torch.cos(ego_heading), torch.sin(ego_heading)]) + ego_right = torch.stack([torch.sin(ego_heading), -torch.cos(ego_heading)]) + + # Compute longitudinal and lateral distances. + longitudinal_distance = torch.dot(relative_pos, ego_forward).item() + lateral_distance = abs(torch.dot(relative_pos, ego_right).item()) + + # Check distance and heading constraints. + if (lateral_distance <= lateral_threshold and abs(longitudinal_distance) <= longitudinal_threshold): + nearby_vehicles.append(vehicle_idx) + + return nearby_vehicles + +MAP_FEATURE_NAMES = ("LANE", "LANE_CONNECTOR", "STOP_LINE", "CROSSWALK") + + +def get_goal_point(example_traj, rg, validity, road_graph_validity, + map_feature_names=MAP_FEATURE_NAMES): + """Sample a forward, direction-compatible lane goal for the 2 Hz horizon. + + This is a geometric feasibility screen. The downstream dynamics optimizer + must still solve successfully; this screen does not prove route connectivity. + No suitable goal returns (None, 0), so callers can skip inference. + """ + trajectories = decode_scene_tensor(example_traj) + attack = trajectories[1] + if (attack.shape[0] <= 5 or not (validity[1, :5] > 0.5).all() + or not torch.isfinite(attack[:5]).all()): + return None, 0 + current = attack[4] + speed = torch.linalg.vector_norm(current[4:6]) + if speed <= 0.1 or (current[6:8] <= 0).any(): + return None, 0 + horizon = (attack.shape[0] - 5) * 0.5 + current_heading = torch.atan2(current[3], current[2]) + + def feasible(position, heading): + displacement = position - current[:2] + distance = torch.linalg.vector_norm(displacement, dim=-1) + bearing = torch.atan2(displacement[..., 1], displacement[..., 0]) + + def angle_difference(a, b): + return torch.atan2(torch.sin(a - b), torch.cos(a - b)).abs() + + return ( + torch.isfinite(position).all(dim=-1) & torch.isfinite(heading) + & (distance >= speed * max(horizon - 1.0, 0.0)) + & (distance <= speed * (horizon + 1.0)) + & (angle_difference(bearing, current_heading) <= np.deg2rad(15)) + & (angle_difference(heading, current_heading) <= np.deg2rad(60)) + & (angle_difference(heading, bearing) <= np.deg2rad(60)) + ) + + # Clone because unnormalize_roadgraph modifies coordinates in place. + road = unnormalize_roadgraph(rg.clone()) + if road.shape[1] < 2: + return None, 0 + point_valid = (road_graph_validity[..., :2] > 0.5).all(dim=-1) + point_valid &= torch.isfinite(road[..., :2]).all(dim=-1) + lane_point = torch.zeros_like(point_valid) + for name in ("LANE", "LANE_CONNECTOR"): + if name in map_feature_names: + channel = 2 + list(map_feature_names).index(name) + lane_point |= ((road[..., channel] > 0.5) + & (road_graph_validity[..., channel] > 0.5)) + point_valid &= lane_point + xy = road[..., :2] + segment = xy[:, 1:] - xy[:, :-1] + segment_valid = point_valid[:, 1:] & point_valid[:, :-1] + segment_valid &= torch.linalg.vector_norm(segment, dim=-1) > 1e-6 + # Use the next segment at each point and the previous one at the last point. + tangent = torch.cat((segment, segment[:, -1:]), dim=1) + tangent_valid = torch.cat((segment_valid, segment_valid[:, -1:]), dim=1) + heading = torch.atan2(tangent[..., 1], tangent[..., 0]) + eligible = point_valid & tangent_valid & feasible(xy, heading) + indices = torch.nonzero(eligible, as_tuple=False) + if len(indices) == 0: + return None, 0 + selected = indices[torch.randint(len(indices), (), device=indices.device)] + line, point = selected.tolist() + goal_position, goal_heading = xy[line, point], heading[line, point] + goal_kind = 1 + + # Preserve the optional ego-endpoint attack only when it passes the same + # screen and lies near an eligible lane point with compatible direction. + ego_goal = trajectories[0, -1] + ego_heading = torch.atan2(ego_goal[3], ego_goal[2]) + if (validity[0, -1] > 0.5 and torch.isfinite(ego_goal).all() + and feasible(ego_goal[:2], ego_heading)): + lane_distance = torch.linalg.vector_norm(xy - ego_goal[:2], dim=-1) + lane_angle = torch.atan2(torch.sin(heading - ego_heading), + torch.cos(heading - ego_heading)).abs() + if ((eligible & (lane_distance <= 5.0) & (lane_angle <= np.deg2rad(60))).any() + and torch.rand((), device=road.device) < 0.5): + goal_position, goal_heading, goal_kind = ego_goal[:2], ego_heading, 2 + + goal = current.clone() + goal[:2] = goal_position + goal[2:4] = torch.stack((torch.cos(goal_heading), torch.sin(goal_heading))) + goal[4:6] = speed * goal[2:4] + return encode_scene_tensor(goal), goal_kind + +def create_goal_conditional_copy_mask(scene_tensor_wrapper): + """ + Filter vehicles by motion and distance, then perturb their ground-truth goals with 1 m Gaussian noise for generation. + """ + scene_tensor_features = scene_tensor_wrapper.scene_tensor + task_mask = torch.zeros_like(scene_tensor_features.tensor) + scenario_valid = True + device = scene_tensor_features.tensor.device + decoded_tensor = decode_scene_tensor(scene_tensor_features.tensor) + + # 1. Find all moving vehicles. + dynamic_vehicle_indices = [] + for i in range(1, len(scene_tensor_wrapper.agent_type)): + if i >= len(scene_tensor_features.tensor): + break + + agent_type = scene_tensor_wrapper.agent_type[i].upper() + if agent_type != 'VEHICLE': + continue + + # Check for motion using decoded positions. + if is_vehicle_moving(scene_tensor_features.tensor, i, scene_tensor_features.validity): + dynamic_vehicle_indices.append(i) + + if not dynamic_vehicle_indices: + print("Warning: No dynamic vehicles in the scene; all agents remain in log replay") + task_mask[:, :5, :] = 1 + scenario_valid = False + infos = { + "task_mask": task_mask, + "attack_agent_token": None, + "scenario_valid": scenario_valid + } + return infos + + # Step 2: Select vehicles with a real final-frame goal. Incomplete tracks + # remain in log replay, preserving their original states and validity. + controlled_vehicles = [ + idx for idx in filter_nearby_vehicles(scene_tensor_features, dynamic_vehicle_indices) + if scene_tensor_features.validity[idx, -1] > 0.5 + ] + if not controlled_vehicles: + print("Warning: No controllable non-ego vehicles with a valid final frame; generation failed") + task_mask[:, :5, :] = 1 + scenario_valid = False + infos = { + "task_mask": task_mask, + "attack_agent_token": None, + "scenario_valid": scenario_valid + } + return infos + + # Step 3: Set the ego vehicle's goal after confirming there is a candidate. + ego_perturbation_real = torch.randn(2, device=device) * 1.0 # Gaussian perturbation with a 1 m standard deviation. + ego_perturbation_normalized = ego_perturbation_real / (2.0 * 52.0) + scene_tensor_features.tensor[0, -1, :2] += ego_perturbation_normalized + + # Step 4: Set goals for the controlled vehicles. + for vehicle_idx in controlled_vehicles: + if vehicle_idx >= task_mask.shape[0]: + continue + vehicle_perturbation_real = torch.randn(2, device=device) * 1.0 # Gaussian perturbation with a 1.0 m standard deviation. + vehicle_perturbation_normalized = vehicle_perturbation_real / (2.0 * 52.0) + scene_tensor_features.tensor[vehicle_idx, -1, :2] += vehicle_perturbation_normalized + + # Step 5: Set the task mask. + # Ego vehicle: condition on the first five history frames and final goal frame, and generate the frames in between. + task_mask[0, :5, :] = 1 # Use the first five timesteps as history. + task_mask[0, 5:-1, :] = 0 # Explicitly mark intermediate frames for generation. + task_mask[0, -1] = 1 # Condition on the final goal frame. + + # Controlled vehicles: condition on the first five history frames and final goal frame, and generate the frames in between. + for vehicle_idx in controlled_vehicles: + if vehicle_idx < task_mask.shape[0]: + task_mask[vehicle_idx, :5, :] = 1 # Use the first five timesteps as history. + task_mask[vehicle_idx, 5:-1, :] = 0 # Explicitly mark intermediate frames for generation. + task_mask[vehicle_idx, -1] = 1 # Condition on the final goal frame. + + # Replay all remaining vehicles from the log. + for i in range(1, task_mask.shape[0]): + if i not in controlled_vehicles: + task_mask[i, :, :] = 1 + + attack_agent_tokens = [scene_tensor_wrapper.idx2token[idx] for idx in controlled_vehicles + if idx < len(scene_tensor_wrapper.idx2token)] + if len(attack_agent_tokens) == 0: + assert False, "No controllable vehicles in the scene" + if len(attack_agent_tokens) == 1: + attack_agent_token = attack_agent_tokens[0] + else: + attack_agent_token = attack_agent_tokens + + return { + "task_mask": task_mask, + "attack_agent_token": attack_agent_token, + "scenario_valid": scenario_valid, + } + +def create_intent_attack_with_goal_selection_mask(scene_tensor_wrapper, map_feature_names=MAP_FEATURE_NAMES): + """ + Filter vehicles by motion and distance, then randomly select an attacker from the top-K candidates closest to the ego vehicle. + """ + scene_tensor_features = scene_tensor_wrapper.scene_tensor + task_mask = torch.zeros_like(scene_tensor_features.tensor) + scenario_valid = True + decoded_tensor = decode_scene_tensor(scene_tensor_features.tensor) + + # 1. Find all moving vehicles. + dynamic_vehicle_indices = [] + for i in range(1, len(scene_tensor_wrapper.agent_type)): + if i >= len(scene_tensor_features.tensor): + break + + agent_type = scene_tensor_wrapper.agent_type[i].upper() + if agent_type != 'VEHICLE': + continue + + # Check for motion using decoded positions. + if is_vehicle_moving(scene_tensor_features.tensor, i, scene_tensor_features.validity): + dynamic_vehicle_indices.append(i) + + if not dynamic_vehicle_indices: + print("Warning: No dynamic vehicles in the scene; all agents remain in log replay") + task_mask[:, :5, :] = 1 + scenario_valid = False + infos = { + "task_mask": task_mask, + "attack_agent_token": None, + "scenario_valid": scenario_valid + } + return infos + + # Selection and ranking must use the same current frame and candidate set. + controlled_vehicles = [ + idx for idx in filter_nearby_vehicles(scene_tensor_features, dynamic_vehicle_indices) + if (scene_tensor_features.validity[idx, :5] > 0.5).all() + and torch.isfinite(decoded_tensor[idx, :5]).all() + ] + if not controlled_vehicles: + print("Warning: No nearby controllable vehicles with complete history") + return {"task_mask": task_mask, "attack_agent_token": None, "scenario_valid": False} + + ego_pos = scene_tensor_features.tensor[0, 4, :2] + controlled_vehicles.sort(key=lambda idx: torch.linalg.vector_norm( + scene_tensor_features.tensor[idx, 4, :2] - ego_pos).item()) + candidates = controlled_vehicles[:4] + closest_index = candidates[torch.randint(len(candidates), ()).item()] + + # Validate the goal before swapping or extending the chosen track. + goal_point, goal_point_valid = get_goal_point( + scene_tensor_features.tensor[[0, closest_index]].clone().float(), + scene_tensor_features.road_graph, + scene_tensor_features.validity[[0, closest_index]], + scene_tensor_features.road_graph_validity, + map_feature_names, + ) + if goal_point_valid == 0: + print("Warning: No direction-compatible lane goal for the selected attack vehicle") + return {"task_mask": task_mask, "attack_agent_token": None, "scenario_valid": False} + + attack_agent_token = scene_tensor_wrapper.idx2token[closest_index] if len(scene_tensor_wrapper.idx2token) > closest_index else None + if closest_index != 1: + temp_tensor = scene_tensor_features.tensor[1].clone() + scene_tensor_features.tensor[1] = scene_tensor_features.tensor[closest_index].clone() + scene_tensor_features.tensor[closest_index] = temp_tensor + + temp_valid = scene_tensor_features.validity[1].clone() + scene_tensor_features.validity[1] = scene_tensor_features.validity[closest_index] + scene_tensor_features.validity[closest_index] = temp_valid + + if len(scene_tensor_wrapper.idx2token) > closest_index: + scene_tensor_wrapper.idx2token[1], scene_tensor_wrapper.idx2token[closest_index] = ( + scene_tensor_wrapper.idx2token[closest_index], + scene_tensor_wrapper.idx2token[1], + ) + if len(scene_tensor_wrapper.agent_type) > closest_index: + scene_tensor_wrapper.agent_type[1], scene_tensor_wrapper.agent_type[closest_index] = ( + scene_tensor_wrapper.agent_type[closest_index], + scene_tensor_wrapper.agent_type[1], + ) + + scene_tensor_features.tensor[1, -1, :] = goal_point + scene_tensor_features.validity[1, 5:] = 1 + + task_mask[:, :5, :] = 1 + task_mask[:2, -1] = 1 + + for i in range(2, task_mask.shape[0]): + task_mask[i, :, :] = 1 + + infos = { + "task_mask": task_mask, + "attack_agent_token": attack_agent_token, + "scenario_valid": scenario_valid, + } + + return infos + +def generate_new_scene_tensor_wrapper_from_wrapper_v2(scene_tensor_wrapper, model, task, motion_limits=None): + """ + Take an existing scene_tensor_wrapper and use the task ("bp", "scene_gen", "intent_attack") + to build the task_mask and generate a new scene_tensor_wrapper. + + Returns: + tuple: (new_scene_tensor_wrapper, attack_agent_token) + For goal_conditional_inpainting, return the new wrapper and the attacking vehicle's token. + For other tasks, attack_agent_token is None. + """ + motion_limits = resolve_motion_limits(motion_limits) + features = {"scene_tensor": scene_tensor_wrapper.scene_tensor} + attack_agent_token = None + + if task == "goal_conditional_copy_with_noise": + infos_dict = create_goal_conditional_copy_mask(scene_tensor_wrapper) + elif task == "intent_attack_with_goal_selection": + map_features = model.get_list_of_required_feature()[0]._map_features + infos_dict = create_intent_attack_with_goal_selection_mask(scene_tensor_wrapper, map_features) + else: + raise ValueError(f"Unknown task: {task}") + + if not infos_dict['scenario_valid']: + return scene_tensor_wrapper, {k: v for k, v in infos_dict.items() if k != "task_mask"} + + features["task_mask"] = infos_dict["task_mask"] + + batched_features = unsqueeze(features) + was_training = model.training + try: + with torch.no_grad(), autocast(enabled=False): + model.eval() + predictions = model.forward_inference(batched_features) + finally: + model.train(was_training) + + # Check native rear-axle ego / center agent states, avoiding export offsets. + reason = validate_generated_motion( + decode_scene_tensor(predictions["sampled_tensor"][0]).detach().cpu().numpy(), + features["scene_tensor"].validity.detach().cpu().numpy(), + features["task_mask"].detach().cpu().numpy(), + motion_limits, + ) + if reason is not None: + print(f"Rejected generated motion: {reason}") + return scene_tensor_wrapper, {"scenario_valid": False, + "attack_agent_token": infos_dict["attack_agent_token"], + "rejection_reason": reason} + + predictions['scene_tensor'] = batched_features['scene_tensor'] + predictions['scene_tensor'].tensor = predictions['sampled_tensor'] + predictions = squeeze(predictions) + + # Update scene_tensor.tensor while preserving the other fields. + new_scene_tensor_wrapper = scene_tensor_wrapper + new_scene_tensor_wrapper.scene_tensor = predictions['scene_tensor'] + + return_infos = {k: v for k, v in infos_dict.items() if k != "task_mask"} + + return new_scene_tensor_wrapper, return_infos diff --git a/projects/BWM/scripts/generation_general/publish_scenarios.py b/projects/BWM/scripts/generation_general/publish_scenarios.py new file mode 100644 index 0000000..cb34cb2 --- /dev/null +++ b/projects/BWM/scripts/generation_general/publish_scenarios.py @@ -0,0 +1,298 @@ +"""Publish BWM staging artifacts using the SimEngine scenario-file contract.""" +from __future__ import annotations + +import argparse +import importlib.util +import os +import pickle +import sys +import tempfile +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any, NamedTuple + +CONFIG_LOADER_PATH = ( + Path(__file__).resolve().parent + / "utils" + / "config_loader.py" +) +CONFIG_LOADER_SPEC = importlib.util.spec_from_file_location( + "bwm_publisher_config_loader", + CONFIG_LOADER_PATH, +) +if CONFIG_LOADER_SPEC is None or CONFIG_LOADER_SPEC.loader is None: + raise RuntimeError(f"Unable to load BWM config loader: {CONFIG_LOADER_PATH}") +CONFIG_LOADER = importlib.util.module_from_spec(CONFIG_LOADER_SPEC) +CONFIG_LOADER_SPEC.loader.exec_module(CONFIG_LOADER) +ConfigError = CONFIG_LOADER.ConfigError +load_entrypoint_config = CONFIG_LOADER.load_entrypoint_config + + +REQUIRED_SCENARIO_FIELDS = frozenset( + { + "id", + "name", + "token", + "dataset", + "map", + "log_length", + "sample_rate", + "base_timestamp", + "metadata", + "cameras", + "lidar", + "object_track", + "sdc_id", + "map_features", + "dynamic_map_states", + } +) + + +class PublicationError(ValueError): + """Raised when staging artifacts cannot be published safely.""" + + +class PublicationResult(NamedTuple): + """Summary of a completed publication.""" + + destination: Path + source_files: tuple[Path, ...] + source_count: int + scenario_count: int + replaced: bool + + +def discover_source_files(output_dir: Path) -> list[Path]: + """Return sorted immediate ``/.pkl`` artifacts.""" + staging_dir = Path(output_dir) + if not staging_dir.is_dir(): + return [] + + source_files = [] + for source_dir in staging_dir.iterdir(): + if not source_dir.is_dir(): + continue + source_file = source_dir / f"{source_dir.name}.pkl" + if source_file.is_file(): + source_files.append(source_file) + return sorted(source_files) + + +def _load_source(source_path: Path) -> Mapping[str, Any]: + try: + with source_path.open("rb") as stream: + payload = pickle.load(stream) + except Exception as error: + raise PublicationError( + f"Unable to load source pickle {source_path}: {error}" + ) from error + + if not isinstance(payload, Mapping): + raise PublicationError( + f"Source {source_path} must contain a mapping" + ) + if not payload: + raise PublicationError(f"Source {source_path} must not be empty") + return payload + + +def _validate_scenario( + scenario_id: object, + scenario: object, + source_path: Path, +) -> None: + if not isinstance(scenario_id, str) or not scenario_id.strip(): + raise PublicationError( + f"Source {source_path} contains a non-empty string scenario ID violation" + ) + if not isinstance(scenario, Mapping): + raise PublicationError( + f"Source {source_path} scenario '{scenario_id}' must be a mapping" + ) + + missing_fields = sorted(REQUIRED_SCENARIO_FIELDS.difference(scenario)) + if missing_fields: + raise PublicationError( + f"Source {source_path} scenario '{scenario_id}' is missing " + f"required fields: {', '.join(missing_fields)}" + ) + + for field in ("id", "name"): + if scenario[field] != scenario_id: + raise PublicationError( + f"Source {source_path} scenario '{scenario_id}' has {field}=" + f"{scenario[field]!r}, which does not match the top-level key" + ) + + token = scenario["token"] + if not isinstance(token, str) or not token.strip(): + raise PublicationError( + f"Source {source_path} scenario '{scenario_id}' token must be " + "a non-empty string" + ) + + +def merge_source_files( + source_files: Sequence[Path], +) -> dict[str, Mapping[str, Any]]: + """Validate and merge canonical source files without silent collisions.""" + if not source_files: + raise PublicationError("No canonical BWM staging source files found") + + merged: dict[str, Mapping[str, Any]] = {} + owners: dict[str, Path] = {} + for source_path in sorted(Path(path) for path in source_files): + payload = _load_source(source_path) + for scenario_id in payload: + if not isinstance(scenario_id, str) or not scenario_id.strip(): + _validate_scenario(scenario_id, payload[scenario_id], source_path) + + for scenario_id in sorted(payload): + scenario = payload[scenario_id] + _validate_scenario(scenario_id, scenario, source_path) + if scenario_id in merged: + raise PublicationError( + f"Duplicate scenario ID '{scenario_id}' in " + f"{owners[scenario_id]} and {source_path}" + ) + merged[scenario_id] = scenario + owners[scenario_id] = source_path + + return merged + + +def _validate_scenario_name(scenario_name: str) -> None: + if ( + not isinstance(scenario_name, str) + or not scenario_name.strip() + or scenario_name in {".", ".."} + or "/" in scenario_name + or "\\" in scenario_name + ): + raise PublicationError( + "scenario_name must be a non-empty safe path component" + ) + + +def publish_scenarios( + output_dir: Path, + publish_root: Path, + scenario_name: str, + overwrite: bool = False, +) -> PublicationResult: + """Validate staging artifacts and atomically publish one canonical pickle.""" + _validate_scenario_name(scenario_name) + source_files = tuple(discover_source_files(Path(output_dir))) + merged = merge_source_files(source_files) + + destination = ( + Path(publish_root) + / scenario_name + / "all_scenarios.pkl" + ) + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists() and not overwrite: + raise PublicationError( + f"Published scenario file already exists: {destination}; " + "pass --overwrite to replace it" + ) + + replaced = destination.exists() + temporary_path = None + try: + temporary_file = tempfile.NamedTemporaryFile( + mode="wb", + prefix=f".{destination.name}.", + suffix=".tmp", + dir=destination.parent, + delete=False, + ) + temporary_path = Path(temporary_file.name) + with temporary_file as stream: + pickle.dump(merged, stream, protocol=pickle.HIGHEST_PROTOCOL) + stream.flush() + os.fsync(stream.fileno()) + + if overwrite: + os.replace(temporary_path, destination) + else: + try: + os.link(temporary_path, destination) + except FileExistsError as error: + raise PublicationError( + f"Published scenario file already exists: {destination}; " + "pass --overwrite to replace it" + ) from error + temporary_path.unlink() + temporary_path = None + except PublicationError: + raise + except Exception as error: + raise PublicationError( + f"Unable to publish scenario file {destination}: {error}" + ) from error + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + + return PublicationResult( + destination=destination, + source_files=source_files, + source_count=len(source_files), + scenario_count=len(merged), + replaced=replaced, + ) + + +def parse_args(argv=None): + """Parse the public BWM publication CLI.""" + parser = argparse.ArgumentParser( + description="Publish BWM staging artifacts for SimEngine.", + ) + parser.add_argument( + "--config", + required=True, + help="Repository-relative path to a layered BWM scenario YAML.", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="Explicitly replace an existing all_scenarios.pkl.", + ) + return parser.parse_args(argv) + + +def main(argv=None): + args = parse_args(argv) + try: + loaded = load_entrypoint_config(args.config) + cfg = loaded.config + for key in ("output_dir", "publish_root", "scenario_name"): + if not cfg.get(key): + raise PublicationError( + f"Layered BWM config must define {key}" + ) + result = publish_scenarios( + Path(cfg.output_dir), + Path(cfg.publish_root), + str(cfg.scenario_name), + overwrite=args.overwrite, + ) + except ConfigError as error: + print(f"Configuration error: {error}", file=sys.stderr) + return 2 + except PublicationError as error: + print(f"Publication error: {error}", file=sys.stderr) + return 2 + + print(f"staging: {cfg.output_dir}") + print(f"destination: {result.destination}") + print(f"source_files: {result.source_count}") + print(f"scenarios: {result.scenario_count}") + print(f"replaced: {'yes' if result.replaced else 'no'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/projects/BWM/scripts/generation_general/utils/__init__.py b/projects/BWM/scripts/generation_general/utils/__init__.py new file mode 100644 index 0000000..ae1fc82 --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/__init__.py @@ -0,0 +1 @@ +"""Utility modules used by the BWM generation pipeline.""" diff --git a/projects/BWM/scripts/generation_general/utils/checkpoint_loader.py b/projects/BWM/scripts/generation_general/utils/checkpoint_loader.py new file mode 100644 index 0000000..e1f1cf8 --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/checkpoint_loader.py @@ -0,0 +1,76 @@ +"""Compatibility loading for trusted BWM inference checkpoints.""" + +import pickle +from collections.abc import Mapping + +import torch + + +_IGNORED_TRAINING_METADATA = { + ( + "nuplan_extent.planning.training.modeling.objectives.diffusion_objective", + "DiffusionObjective", + ), + ( + "nuplan_extent.planning.training.modeling.metrics.dummy_metric", + "DummyMetric", + ), + ( + "nuplan_extent.planning.training.modeling.aggregated_metrics.behavior_prediction", + "BehaviorPredictionMetric", + ), +} + + +class CheckpointFormatError(ValueError): + """Raised when an inference checkpoint has no usable state dictionary.""" + + +class _DiscardedTrainingMetadata: + """Stand-in for training-only metadata that inference never consumes.""" + + def __new__(cls, *args, **kwargs): + return super().__new__(cls) + + def __init__(self, *args, **kwargs): + pass + + def __setstate__(self, state): + pass + + +class _InferenceCheckpointUnpickler(pickle.Unpickler): + """Ignore only the known training metadata removed from public BWM.""" + + def find_class(self, module, name): + if (module, name) in _IGNORED_TRAINING_METADATA: + return _DiscardedTrainingMetadata + return super().find_class(module, name) + + +class _InferenceCheckpointPickleModule: + """Minimal pickle-module interface consumed by ``torch.load``.""" + + Unpickler = _InferenceCheckpointUnpickler + load = staticmethod(pickle.load) + + +def load_inference_state_dict(checkpoint_path, map_location="cpu"): + """Load and validate the state dictionary from a trusted BWM checkpoint.""" + checkpoint = torch.load( + checkpoint_path, + map_location=map_location, + pickle_module=_InferenceCheckpointPickleModule, + weights_only=False, + ) + if not isinstance(checkpoint, Mapping): + raise CheckpointFormatError( + "Inference checkpoint root must be a mapping" + ) + + state_dict = checkpoint.get("state_dict") + if not isinstance(state_dict, Mapping): + raise CheckpointFormatError( + "Inference checkpoint must contain a mapping-valued 'state_dict'" + ) + return state_dict diff --git a/projects/BWM/scripts/generation_general/utils/config_loader.py b/projects/BWM/scripts/generation_general/utils/config_loader.py new file mode 100644 index 0000000..64b7510 --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/config_loader.py @@ -0,0 +1,203 @@ +"""Compose BWM generation settings with an AlgEngine scene selection.""" +from __future__ import annotations + +from collections.abc import Mapping +import math +from pathlib import Path +from typing import Any, NamedTuple + +from omegaconf import DictConfig, OmegaConf + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[5] +BWM_ROOT = Path(__file__).resolve().parents[3] +DEFAULT_CONFIG_PATH = BWM_ROOT / "configs" / "default.yaml" + + +RUNTIME_PATH_KEYS = ( + "checkpoint", + "digitaltwin_data_root", + "openscene_data_root", + "scenario_builder.data_root", + "scenario_builder.map_root", + "scenario_builder.sensor_root", +) + + +OUTPUT_PATH_KEYS = ( + "output_dir", + "log_dir", + "publish_root", +) + +REPOSITORY_PATH_KEYS = RUNTIME_PATH_KEYS + OUTPUT_PATH_KEYS + +# Keep execution order independent of the order of keys in scenario overrides. +GENERATION_TASKS = ( + "goal_conditional_copy_with_noise", + "intent_attack_with_goal_selection", +) + +# Provisional rejection thresholds, not calibrated quality guarantees. +DEFAULT_MOTION_LIMITS = { + "max_speed_mps": 45.0, + "max_acceleration_mps2": 10.0, + "max_velocity_error_mps": 5.0, +} + +class ConfigError(ValueError): + """Raised when BWM configuration composition is invalid.""" + + +def resolve_motion_limits(settings=None): + """Merge and validate the optional motion-validation overrides.""" + if settings is None: + settings = {} + if not isinstance(settings, (dict, DictConfig)): + raise ConfigError("motion_validation must be a mapping") + unknown = set(settings) - set(DEFAULT_MOTION_LIMITS) + if unknown: + raise ConfigError("Unknown motion_validation settings: " + ", ".join(sorted(unknown))) + limits = {**DEFAULT_MOTION_LIMITS, **settings} + for key, value in limits.items(): + if type(value) not in (int, float) or not math.isfinite(value) or value <= 0: + raise ConfigError(f"motion_validation.{key} must be a finite positive number") + return limits + + +class LoadedGenerationConfig(NamedTuple): + """Configuration selected for a BWM pipeline invocation.""" + + config: DictConfig + mode: str + source: Path + + +def _resolve_path(path: str | Path, repo_root: Path) -> Path: + resolved = Path(path).expanduser() + if not resolved.is_absolute(): + resolved = repo_root / resolved + return resolved.resolve() + + +def _anchor_runtime_path(path: str | Path, repo_root: Path) -> Path: + """Anchor a runtime path without dereferencing repository symlinks.""" + anchored = Path(path).expanduser() + if not anchored.is_absolute(): + anchored = repo_root / anchored + return anchored.absolute() + + +def _resolve_runtime_paths(cfg: DictConfig, repo_root: Path) -> DictConfig: + """Resolve configured runtime inputs after all config layers are merged.""" + for key in REPOSITORY_PATH_KEYS: + value = OmegaConf.select(cfg, key) + if value: + OmegaConf.update( + cfg, + key, + str(_anchor_runtime_path(value, repo_root)), + merge=False, + ) + return cfg + + +def validate_runtime_paths(cfg: DictConfig) -> None: + """Fail when a required layered runtime input is unset or missing.""" + missing = [] + for key in RUNTIME_PATH_KEYS: + value = OmegaConf.select(cfg, key) + if not value: + missing.append(f"{key}=") + elif not Path(str(value)).exists(): + missing.append(f"{key}={value}") + if missing: + raise ConfigError( + "Missing layered runtime paths: " + ", ".join(missing) + ) + + +def validate_generation_settings(cfg: DictConfig) -> None: + """Check generation controls before loading the model or creating outputs.""" + resolve_motion_limits(cfg.get("motion_validation", {})) + if "max_iterations" in cfg: + raise ConfigError("Use generation.tasks..max_attempts for generation budgets") + if "worker" in cfg: + raise ConfigError("Unsupported BWM setting 'worker': generation runs sequentially") + generation = cfg.get("generation") + if not isinstance(generation, (dict, DictConfig)) or set(generation) != {"tasks"}: + raise ConfigError("generation must contain a tasks mapping") + tasks = generation.get("tasks") + if not isinstance(tasks, (dict, DictConfig)) or set(tasks) != set(GENERATION_TASKS): + raise ConfigError("generation.tasks must contain exactly: " + ", ".join(GENERATION_TASKS)) + for task in GENERATION_TASKS: + budget = tasks[task] + prefix = f"generation.tasks.{task}" + if not isinstance(budget, (dict, DictConfig)) or set(budget) != {"max_attempts", "max_success"}: + raise ConfigError(f"{prefix} must contain max_attempts and max_success") + for key in ("max_attempts", "max_success"): + if type(budget[key]) is not int or budget[key] < 0: + raise ConfigError(f"{prefix}.{key} must be a non-negative integer") + if type(cfg.get("save_scenario_description")) is not bool: + raise ConfigError("save_scenario_description must be true or false") + + +def _load_config_file(path: Path, label: str) -> DictConfig: + if not path.is_file(): + raise ConfigError(f"{label} config does not exist: {path}") + return OmegaConf.load(path) + + +def load_generation_config( + scenario_config_path: str | Path, + *, + default_config_path: str | Path | None = None, + overrides: Mapping[str, Any] | None = None, + repo_root: str | Path | None = None, +) -> DictConfig: + """Load default, scenario, and command-line layers for BWM generation.""" + root = Path(repo_root).resolve() if repo_root is not None else WORLDENGINE_ROOT + default_path = _resolve_path(default_config_path or DEFAULT_CONFIG_PATH, root) + scenario_path = _resolve_path(scenario_config_path, root) + + default_cfg = _load_config_file(default_path, "Default") + scenario_cfg = _load_config_file(scenario_path, "Scenario") + for selection_key in ("log_names", "tokens"): + if selection_key in scenario_cfg: + raise ConfigError( + f"{selection_key} must be provided through scene_filter_path" + ) + + override_cfg = OmegaConf.create(overrides or {}) + cfg = OmegaConf.merge(default_cfg, scenario_cfg, override_cfg) + + scene_filter_value = cfg.get("scene_filter_path") + if not scene_filter_value: + raise ConfigError("scenario config must define scene_filter_path") + scene_filter_path = _resolve_path(scene_filter_value, root) + scene_filter_cfg = _load_config_file(scene_filter_path, "SceneFilter") + selection = { + key: scene_filter_cfg.get(key) + for key in ("log_names", "tokens") + if scene_filter_cfg.get(key) is not None + } + if not selection: + raise ConfigError("SceneFilter must define log_names or tokens") + + cfg = OmegaConf.merge(cfg, selection, override_cfg) + cfg.scene_filter_path = str(scene_filter_path) + return _resolve_runtime_paths(cfg, root) + + +def load_entrypoint_config( + scenario_config_path: str | Path | None = None, +) -> LoadedGenerationConfig: + """Compose the explicit layered scenario selected by a public entrypoint.""" + if scenario_config_path is None: + raise ConfigError( + "A layered BWM scenario config is required; pass --config" + ) + + source = _resolve_path(scenario_config_path, WORLDENGINE_ROOT) + config = load_generation_config(scenario_config_path) + return LoadedGenerationConfig(config, "layered", source) diff --git a/projects/BWM/scripts/generation_general/utils/motion_validation.py b/projects/BWM/scripts/generation_general/utils/motion_validation.py new file mode 100644 index 0000000..643e04f --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/motion_validation.py @@ -0,0 +1,52 @@ +"""Validate generated motion in native BWM coordinates, before scene export.""" + +import numpy as np + + +def validate_generated_motion(trajectories, validity, keep_mask, limits, dt=0.5): + """Return the first rejection reason, or None for a passing candidate. + + Inputs have shape (agents, time, 8), (agents, time), and (agents, time, 8). + Check transitions touching generated states, including both fixed boundaries. + Fully replayed tracks and wholly historical transitions are not screened. + """ + trajectories = np.asarray(trajectories) + validity = np.asarray(validity) + generated = ~np.asarray(keep_mask, dtype=bool).all(axis=-1) + for agent in np.flatnonzero(generated.any(axis=-1)): + states = trajectories[agent] + if not np.isfinite(validity[agent]).all() or not (validity[agent] > 0.5).all(): + return f"agent {agent}: controlled trajectory has missing frames" + if not np.isfinite(states).all(): + return f"agent {agent}: non-finite trajectory state" + if (states[:, 6:8] <= 0).any(): + return f"agent {agent}: non-positive vehicle dimensions" + + changed = generated[agent] + edges = changed[:-1] | changed[1:] + edge_velocity = np.diff(states[:, :2], axis=0) / dt + endpoint_speed = np.linalg.norm(states[:, 4:6], axis=-1) + edge_speed = np.linalg.norm(edge_velocity, axis=-1) + touched = changed.copy() + touched[:-1] |= edges + touched[1:] |= edges + peak_speed = max(endpoint_speed[touched].max(), edge_speed[edges].max()) + if peak_speed > limits["max_speed_mps"]: + return f"agent {agent}: speed {peak_speed:.3f} m/s exceeds limit" + + # A position jump must not be hidden by a plausible stored velocity. + mean_velocity = (states[:-1, 4:6] + states[1:, 4:6]) / 2 + residual = np.linalg.norm(edge_velocity - mean_velocity, axis=-1) + if residual[edges].max() > limits["max_velocity_error_mps"]: + index = int(np.flatnonzero(edges & (residual > limits["max_velocity_error_mps"]))[0]) + return f"agent {agent}: velocity mismatch at frames {index}->{index + 1} ({residual[index]:.3f} m/s)" + + position_accel = np.linalg.norm(np.diff(edge_velocity, axis=0) / dt, axis=-1) + accel_windows = edges[:-1] | edges[1:] + velocity_accel = np.linalg.norm(np.diff(states[:, 4:6], axis=0) / dt, axis=-1) + peak_accel = velocity_accel[edges].max() + if accel_windows.any(): + peak_accel = max(peak_accel, position_accel[accel_windows].max()) + if peak_accel > limits["max_acceleration_mps2"]: + return f"agent {agent}: acceleration {peak_accel:.3f} m/s^2 exceeds limit" + return None diff --git a/projects/BWM/scripts/generation_general/utils/nuplan_type_mapping.py b/projects/BWM/scripts/generation_general/utils/nuplan_type_mapping.py new file mode 100644 index 0000000..0f3234e --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/nuplan_type_mapping.py @@ -0,0 +1,40 @@ +""" +Category mapping from nuplan track objects to world engine. +""" + + +import logging + +from utils.type import WorldEngineObjectType + +from nuplan.common.actor_state.tracked_objects_types import TrackedObjectType +from nuplan.common.maps.maps_datatypes import TrafficLightStatusType +NuPlanEgoType = TrackedObjectType.EGO + + +def get_traffic_obj_type(nuplan_type): + if nuplan_type == TrackedObjectType.VEHICLE: + return "VEHICLE" + elif nuplan_type == TrackedObjectType.TRAFFIC_CONE: + return "TRAFFIC_CONE" + elif nuplan_type == TrackedObjectType.PEDESTRIAN: + return "PEDESTRIAN" + elif nuplan_type == TrackedObjectType.BICYCLE: + return "CYCLIST" + elif nuplan_type == TrackedObjectType.BARRIER: + return "TRAFFIC_BARRIER" + elif nuplan_type == TrackedObjectType.EGO: + raise ValueError("Ego should not be in detected resukts") + else: + return None + + +def set_light_status(status): + if status == TrafficLightStatusType.GREEN: + return "TRAFFIC_LIGHT_GREEN" + elif status == TrafficLightStatusType.RED: + return "TRAFFIC_LIGHT_RED" + elif status == TrafficLightStatusType.YELLOW: + return "TRAFFIC_LIGHT_YELLOW" + elif status == TrafficLightStatusType.UNKNOWN: + return "TRAFFIC_LIGHT_UNKNOWN" \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/utils/nuplan_utils.py b/projects/BWM/scripts/generation_general/utils/nuplan_utils.py new file mode 100644 index 0000000..342ada7 --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/nuplan_utils.py @@ -0,0 +1,682 @@ +import math +import argparse +import shutil +from typing import Dict, List, cast, Generator +import torch +import numpy as np +from pyquaternion import Quaternion +import cv2 +from tqdm import tqdm +import os +from sqlalchemy import Column, inspect +import multiprocessing +import pickle +from shapely.geometry.linestring import LineString +from shapely.geometry.multilinestring import MultiLineString +from shapely.geometry import box, mapping +from shapely.ops import unary_union +import geopandas as gpd + +from nuplan.common.actor_state.state_representation import StateSE2, StateVector2D, TimePoint +from nuplan.common.maps.nuplan_map.map_factory import get_maps_api +from nuplan.database.nuplan_db_orm.nuplandb_wrapper import NuPlanDBWrapper +from nuplan.common.actor_state.agent import Agent +from nuplan.common.actor_state.state_representation import Point2D +from nuplan.common.actor_state.static_object import StaticObject +from nuplan.database.nuplan_db import nuplan_scenario_queries +from nuplan.common.actor_state.ego_state import EgoState +from nuplan.common.actor_state.vehicle_parameters import get_pacifica_parameters +from nuplan.common.maps.maps_datatypes import TrafficLightStatusData, TrafficLightStatuses, Transform +from nuplan.common.maps.maps_datatypes import SemanticMapLayer, StopLineType +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import decode_scene_tensor +from utils.type import WorldEngineObjectType +from utils.nuplan_type_mapping import ( + get_traffic_obj_type, NuPlanEgoType, set_light_status) + +EGO = 'ego' + +NUPLAN_REAL_LIDAR2EGO_ROTATION = [-0.0016505558783280307, -0.00023289146777086609, 0.003725490480134295, 0.9999916710390838] +NUPLAN_REAL_LIDAR2EGO_TRANSLATION = [1.5185133218765259, 0.0, 1.6308990716934204] + +def normalize_to_ego_center(vector, ego_center=(0, 0)): + "Normalize position-related vectors to the ego_center of the first frame." + vector = np.array(vector) + vector -= np.asarray(ego_center) + return vector + + +def parse_object_state(obj_state, ego_center): + ret = {} + ret["position"] = normalize_to_ego_center( + [obj_state.center.x, obj_state.center.y], ego_center) + ret["heading"] = obj_state.center.heading + ret["velocity"] = normalize_to_ego_center( + [obj_state.velocity.x, obj_state.velocity.y]) + ret["valid"] = 1 + ret["length"] = obj_state.box.length + ret["width"] = obj_state.box.width + ret["height"] = obj_state.box.height + return ret + + +def parse_ego_vehicle_state(state, ego_center): + ret = {} + ret["position"] = normalize_to_ego_center([state.waypoint.x, state.waypoint.y], ego_center) + ret["heading"] = state.waypoint.heading + ret["velocity"] = normalize_to_ego_center([state.agent.velocity.x, state.agent.velocity.y]) + ret["acceleration"] = normalize_to_ego_center([state.dynamic_car_state.rear_axle_acceleration_2d.x, state.dynamic_car_state.rear_axle_acceleration_2d.y]) + ret["angular_velocity"] = state.dynamic_car_state.angular_velocity + ret["valid"] = 1 + ret["length"] = state.agent.box.length + ret["width"] = state.agent.box.width + ret["height"] = state.agent.box.height + return ret + + +def compute_angular_velocity(initial_heading, final_heading, dt): + """ + Calculate the angular velocity between two headings given in radians. + + Parameters: + initial_heading (float): The initial heading in radians. + final_heading (float): The final heading in radians. + dt (float): The time interval between the two headings in seconds. + + Returns: + float: The angular velocity in radians per second. + """ + + # Calculate the difference in headings + delta_heading = final_heading - initial_heading + + # Adjust the delta_heading to be in the range (-π, π] + delta_heading = (delta_heading + math.pi) % (2 * math.pi) - math.pi + + # Compute the angular velocity + angular_vel = delta_heading / dt + + return angular_vel + + +def parse_ego_vehicle_state_trajectory(log_file, lidar_pcs, ego_center, sample_interval): + egos = [lidar_pc.ego_pose for lidar_pc in lidar_pcs] + + # Then convert ego_status to carfootprint. + ego_boxes = [] + for ego in egos: + q = Quaternion(ego.qw, ego.qx, ego.qy, ego.qz) + ego_boxes.append( + EgoState.build_from_rear_axle( + StateSE2(ego.x, ego.y, q.yaw_pitch_roll[0]), + tire_steering_angle=0.0, + vehicle_parameters=get_pacifica_parameters(), + time_point=TimePoint(ego.timestamp), + rear_axle_velocity_2d=StateVector2D(ego.vx, y=ego.vy), + rear_axle_acceleration_2d=StateVector2D( + x=ego.acceleration_x, y=ego.acceleration_y), + ) + ) + + data = [ + parse_ego_vehicle_state(ego_box, ego_center) + for ego_box in ego_boxes + ] + dt = sample_interval * 0.05 + for i in range(len(data) - 1): + data[i]["angular_velocity"] = compute_angular_velocity( + initial_heading=data[i]["heading"], + final_heading=data[i + 1]["heading"], + dt=dt + ) + return data + + +def extract_traffic(log_file, lidar_pcs, initial_ego_center, sample_interval): + """ + Modified from: + https://github.com/metadriverse/scenarionet/blob/main/scenarionet/converter/nuplan/utils.py#L388 + + A function to store the trajectory of each object appeared in the scene. + All coordinates are normalizaed to the ego_center at the first frame. + """ + log_length = len(lidar_pcs) + + detection_ret = [] + all_objs = set() # for storing the track ids. + all_objs.add(EGO) # key of sdc. + + for lidar_pc in lidar_pcs: + lidar_boxes = lidar_pc.lidar_boxes + new_frame_data = {} + for obj in lidar_boxes: + new_frame_data[obj.track_token] = obj + all_objs.add(obj.track_token) + detection_ret.append(new_frame_data) + + tracks = { + k: dict( + type="UNSET", + state=dict( + position=np.zeros(shape=(log_length, 3)), + heading=np.zeros(shape=(log_length, )), + velocity=np.zeros(shape=(log_length, 2)), + valid=np.zeros(shape=(log_length, )), + length=np.zeros(shape=(log_length, 1)), + width=np.zeros(shape=(log_length, 1)), + height=np.zeros(shape=(log_length, 1)) + ), + metadata=dict(track_length=log_length, nuplan_type=None, type=None, object_id=k, nuplan_id=k) + ) + for k in list(all_objs) + } + + tracks_to_remove = set() + + for frame_idx, frame in enumerate(detection_ret): + for nuplan_id, obj, in frame.items(): + tracked_objs = obj.tracked_object(None) + assert isinstance(tracked_objs, Agent) or isinstance(tracked_objs, StaticObject) + obj_type = get_traffic_obj_type(tracked_objs.tracked_object_type) + if obj_type is None: + tracks_to_remove.add(nuplan_id) + continue + tracks[nuplan_id]['type'] = obj_type + if tracks[nuplan_id]['metadata']["nuplan_type"] is None: + tracks[nuplan_id]['metadata']["nuplan_type"] = int(tracked_objs.tracked_object_type) + tracks[nuplan_id]['metadata']["type"] = obj_type + + # normalize the tracked object position to the ego_center + # of the first frame ego. + state = parse_object_state(tracked_objs, initial_ego_center) + tracks[nuplan_id]["state"]["position"][frame_idx] = [state["position"][0], state["position"][1], 0.0] + tracks[nuplan_id]["state"]["heading"][frame_idx] = state["heading"] + tracks[nuplan_id]["state"]["velocity"][frame_idx] = state["velocity"] + tracks[nuplan_id]["state"]["valid"][frame_idx] = 1 + tracks[nuplan_id]["state"]["length"][frame_idx] = state["length"] + tracks[nuplan_id]["state"]["width"][frame_idx] = state["width"] + tracks[nuplan_id]["state"]["height"][frame_idx] = state["height"] + + for track in list(tracks_to_remove): + tracks.pop(track) + + # ego + sdc_traj = parse_ego_vehicle_state_trajectory( + log_file, lidar_pcs, initial_ego_center, sample_interval) + ego_track = tracks[EGO] + + for frame_idx, obj_state in enumerate(sdc_traj): + obj_type = "VEHICLE" + ego_track['type'] = obj_type + if ego_track['metadata']["nuplan_type"] is None: + ego_track['metadata']["nuplan_type"] = int(NuPlanEgoType) + ego_track['metadata']["type"] = obj_type + state = obj_state + ego_track["state"]["position"][frame_idx] = [state["position"][0], state["position"][1], 0.0] + ego_track["state"]["valid"][frame_idx] = 1 + ego_track["state"]["heading"][frame_idx] = state["heading"] + local2global_rotation_2d = np.array([ + [np.cos(state["heading"]), -np.sin(state["heading"])], + [np.sin(state["heading"]), np.cos(state["heading"])] + ]) + ego_track["state"]["velocity"][frame_idx] = state["velocity"] @ local2global_rotation_2d.T + + ego_track["state"]["length"][frame_idx] = state["length"] + ego_track["state"]["width"][frame_idx] = state["width"] + ego_track["state"]["height"][frame_idx] = state["height"] + + # check + assert EGO in tracks + for track_id in tracks: + assert tracks[track_id]['type'] != "UNSET" + return tracks + + +def set_light_position(map_api, lane_id, center, target_position=8): + lane = map_api.get_map_object(str(lane_id), SemanticMapLayer.LANE_CONNECTOR) + assert lane is not None, "Can not find lane: {}".format(lane_id) + path = lane.baseline_path.discrete_path + acc_length = 0 + point = [path[0].x, path[0].y] + # Find the distance of the path's different target points; + # as long as the accumulated distance is greater than target_position, + # mark it as the traffic light position. + for k, point in enumerate(path[1:], start=1): + previous_p = path[k - 1] + acc_length += np.linalg.norm([point.x - previous_p.x, point.y - previous_p.y]) + if acc_length > target_position: + break + return [point.x - center[0], point.y - center[1]] + + +def extract_traffic_light( + log_file, lidar_pcs, map_api, initial_ego_center): + log_length = len(lidar_pcs) + + frames = [ + {str(t.lane_connector_id): t.status + for t in + cast( + Generator[TrafficLightStatusData, None, None], + nuplan_scenario_queries.get_traffic_light_status_for_lidarpc_token_from_db( + log_file, lidar_pcs[i].token), + ) + } + for i in range(log_length) + ] + + all_lights = set() + for frame in frames: + all_lights.update(frame.keys()) + + lights = { + k: { + "type": "TRAFFIC_LIGHT", + "state": { + 'traffic_light_state': ["TRAFFIC_LIGHT_UNKNOWN"] * log_length + }, + 'traffic_light_position': None, + 'traffic_light_lane': str(k), + "metadata": dict(track_length=log_length, + type=None, + object_id=str(k), + lane_id=str(k), + dataset="nuplan") + } + for k in list(all_lights) + } + + for k, frame in enumerate(frames): + for lane_id, status in frame.items(): + lane_id = str(lane_id) + lights[lane_id]["state"]['traffic_light_state'][k] = set_light_status(status) + if lights[lane_id]['traffic_light_position'] is None: + assert isinstance(lane_id, str), "Lane ID should be str" + # Store only simple data types to avoid serializing complex object references. + position = set_light_position(map_api, lane_id, initial_ego_center) + # Convert to a plain list without object references. + lights[lane_id]['traffic_light_position'] = [float(pos) for pos in position] + lights[lane_id]['metadata']['type'] = "TRAFFIC_LIGHT" + return lights + + +def extract_centerline(map_obj, nuplan_center): + path = map_obj.baseline_path.discrete_path + points = np.array([normalize_to_ego_center( + [pose.x, pose.y], nuplan_center) for pose in path]) + return points + + +def get_points_from_boundary(boundary, center): + path = boundary.discrete_path + points = [(pose.x, pose.y) for pose in path] + points = normalize_to_ego_center(points, center) + return points + + +def extract_drivable_area(map_api, initial_ego_center, radius=500): + """Serialize nearby native drivable polygons, including holes, in global coordinates.""" + x, y = initial_ego_center[:2] + patch = box(x - radius, y - radius, x + radius, y + radius) + # The pinned nuPlan devkit exposes this combined vector layer through its + # layer accessor, but not through get_proximal_map_objects(). It includes + # road segments, intersections, generic drivable areas, and car parks. + layer = map_api._get_vector_map_layer(SemanticMapLayer.DRIVABLE_AREA) + indices = layer.sindex.query(patch, predicate="intersects") + # Keep whole intersecting polygons: clipping would create artificial road edges. + geometry = unary_union(layer.geometry.iloc[indices]) + if geometry.is_empty or geometry.geom_type not in ("Polygon", "MultiPolygon") or not geometry.is_valid: + raise ValueError(f"No valid nuPlan drivable-area polygons near ({x}, {y})") + return { + "source": "nuplan.DRIVABLE_AREA", + "coordinate_system": "global", + "geometry": mapping(geometry), + } + + +def extract_map_features(map_api, initial_ego_center, radius=500): + ret = {} + np.seterr(all='ignore') + # Center is Important ! + layer_names = [ + SemanticMapLayer.LANE_CONNECTOR, # connectors between different lanes. + SemanticMapLayer.LANE, # basic element of traffic lanes. + SemanticMapLayer.CROSSWALK, # crosswalk for pedestrian on intersections. + SemanticMapLayer.INTERSECTION, # intersections. + SemanticMapLayer.STOP_LINE, # stop line on roads. + SemanticMapLayer.WALKWAYS, # pedestrian walking ways + SemanticMapLayer.CARPARK_AREA, + SemanticMapLayer.ROADBLOCK, # lanes following the same direction. + SemanticMapLayer.ROADBLOCK_CONNECTOR, # connectors of blocks + + # unsupported yet + # SemanticMapLayer.STOP_SIGN, + # SemanticMapLayer.DRIVABLE_AREA, + ] + center_for_query = Point2D(*initial_ego_center) + nearest_vector_map = map_api.get_proximal_map_objects(center_for_query, radius, layer_names) + # Filter out stop polygons in turn stop + if SemanticMapLayer.STOP_LINE in nearest_vector_map: + stop_polygons = nearest_vector_map[SemanticMapLayer.STOP_LINE] + nearest_vector_map[SemanticMapLayer.STOP_LINE] = [ + stop_polygon for stop_polygon in stop_polygons if stop_polygon.stop_line_type != StopLineType.TURN_STOP + ] + block_polygons = [] + + # Deal with lanes in the roadblocks. + # Each lane in nuplan is a centerline with polygon. + # You can also obtain its left / right border with LINE_BROKEN_SINGLE_WHITE. + for layer in [SemanticMapLayer.ROADBLOCK, SemanticMapLayer.ROADBLOCK_CONNECTOR]: + for block in nearest_vector_map[layer]: + block_id = block.id + # Sorting the inside edges from left-to-right. + edges = sorted(block.interior_edges, key=lambda lane: lane.index) \ + if layer == SemanticMapLayer.ROADBLOCK else block.interior_edges + for index, lane_meta_data in enumerate(edges): + if not hasattr(lane_meta_data, "baseline_path"): + continue + # points: + # a list of xy coordinates of the lane. + # x: a list of numbers / y: a list of numbers. + if isinstance(lane_meta_data.polygon.boundary, MultiLineString): + # Multiple lane strings. + # lane boundary polygons. + boundary = gpd.GeoSeries(lane_meta_data.polygon.boundary).explode(index_parts=True) + sizes = [] + for idx, polygon in enumerate(boundary[0]): + sizes.append(len(polygon.xy[1])) + points = boundary[0][np.argmax(sizes)].xy + elif isinstance(lane_meta_data.polygon.boundary, LineString): + # one lane string. + points = lane_meta_data.polygon.boundary.xy + polygon = [[points[0][i], points[1][i]] for i in range(len(points[0]))] + polygon = normalize_to_ego_center(polygon, ego_center=initial_ego_center) + + # According to the map attributes, lanes are numbered left to right with smaller indices being on the + # left and larger indices being on the right. + # @ See NuPlanLane.adjacent_edges() + ret[lane_meta_data.id] = { + 'type': "LANE_SURFACE_STREET" \ + if layer == SemanticMapLayer.ROADBLOCK \ + else "LANE_SURFACE_UNSTRUCTURE", + 'polyline': extract_centerline(lane_meta_data, initial_ego_center), + 'entry_lanes': [edge.id for edge in lane_meta_data.incoming_edges], + 'exit_lanes': [edge.id for edge in lane_meta_data.outgoing_edges], + 'left_neighbor': [edge.id for edge in block.interior_edges[:index]] \ + if layer == SemanticMapLayer.ROADBLOCK else [], + 'right_neighbor': [edge.id for edge in block.interior_edges[index + 1:]] \ + if layer == SemanticMapLayer.ROADBLOCK else [], + 'polygon': polygon, + 'roadblock_id': block_id + } + if layer == SemanticMapLayer.ROADBLOCK_CONNECTOR: + continue + left = lane_meta_data.left_boundary + if left.id not in ret: + # boundary lane of centerline. + line_type = "ROAD_LINE_BROKEN_SINGLE_WHITE" + if line_type != "UNKNOWN_LINE": + ret[left.id] = { + 'type': line_type, + 'polyline': get_points_from_boundary(left, initial_ego_center)} + + if layer == SemanticMapLayer.ROADBLOCK: + block_polygons.append(block.polygon) + + # walkway + for area in nearest_vector_map[SemanticMapLayer.WALKWAYS]: + if isinstance(area.polygon.exterior, MultiLineString): + boundary = gpd.GeoSeries(area.polygon.exterior).explode(index_parts=True) + sizes = [] + for idx, polygon in enumerate(boundary[0]): + sizes.append(len(polygon.xy[1])) + points = boundary[0][np.argmax(sizes)].xy + elif isinstance(area.polygon.exterior, LineString): + points = area.polygon.exterior.xy + polygon = [[points[0][i], points[1][i]] for i in range(len(points[0]))] + polygon = normalize_to_ego_center(polygon, ego_center=initial_ego_center) + ret[area.id] = { + 'type': "ROAD_EDGE_SIDEWALK", + 'polygon': polygon, + } + + # corsswalk + for area in nearest_vector_map[SemanticMapLayer.CROSSWALK]: + if isinstance(area.polygon.exterior, MultiLineString): + boundary = gpd.GeoSeries(area.polygon.exterior).explode(index_parts=True) + sizes = [] + for idx, polygon in enumerate(boundary[0]): + sizes.append(len(polygon.xy[1])) + points = boundary[0][np.argmax(sizes)].xy + elif isinstance(area.polygon.exterior, LineString): + points = area.polygon.exterior.xy + polygon = [[points[0][i], points[1][i]] for i in range(len(points[0]))] + polygon = normalize_to_ego_center(polygon, ego_center=initial_ego_center) + ret[area.id] = { + 'type': "CROSSWALK", + 'polygon': polygon, + } + + # intersections (centerline) + interpolygons = [block.polygon for block in nearest_vector_map[SemanticMapLayer.INTERSECTION]] + # A group of linestrings. + boundaries = gpd.GeoSeries(unary_union(interpolygons + block_polygons)).boundary.explode(index_parts=True) + # boundaries.plot() + # plt.show() + + # Add boundary data validity check + if not boundaries.empty and 0 in boundaries.index: + for idx, boundary in enumerate(boundaries[0]): + # for each boundary. + block_points = np.array(list(i for i in zip(boundary.coords.xy[0], boundary.coords.xy[1]))) + block_points = normalize_to_ego_center(block_points, initial_ego_center) + id = "boundary_{}".format(idx) + ret[id] = { + 'type': "ROAD_LINE_SOLID_SINGLE_WHITE", + 'polyline': block_points} + # Note: No boundary data found in map - this is common for some map regions + + np.seterr(all='warn') + return ret + + +# The main method to convert nuplan data into WorldEngine required pickle file. +def create_nuplan_info( + nuplan_db_wrapper: NuPlanDBWrapper, db_names: List[str], args, return_dict, +): + + nuplan_db_path = args.nuplan_db_path + nuplan_map_version = args.nuplan_map_version + nuplan_map_root = args.nuplan_map_root + nuplan_sensor_root = args.nuplan_sensor_path + + # get all db files & assign db files for current thread. + log_sensors = os.listdir(nuplan_sensor_root) + + # For each sequence... + for log_db_name in tqdm(db_names): + log_db = nuplan_db_wrapper.get_log_db(log_db_name) + log_name = log_db.log_name + log_token = log_db.log.token + map_location = log_db.log.map_version + vehicle_name = log_db.log.vehicle_name + + map_api = get_maps_api(nuplan_map_root, "nuplan-maps-v1.0", map_location) # NOTE: lru cached + + log_file = os.path.join(nuplan_db_path, log_db_name + ".db") + if log_db_name not in log_sensors: + continue + + # list (sequence) of point clouds (each frame). + lidar_pcs = log_db.lidar_pc + lidar_pcs = lidar_pcs[::args.sample_interval] + log_length = len(lidar_pcs) + + # Store some meta information here + info_dict = dict( + id=log_name, + name=log_name, + dataset='nuplan', + map=map_location, + token=log_token, + log_length=log_length, + sample_rate=args.sample_interval, + base_timestamp=lidar_pcs[0].timestamp, + metadata=dict() + ) + + ego_pose = lidar_pcs[0].ego_pose + q = Quaternion(ego_pose.qw, ego_pose.qx, ego_pose.qy, ego_pose.qz) + initial_ego_state = EgoState.build_from_rear_axle( + StateSE2(ego_pose.x, ego_pose.y, q.yaw_pitch_roll[0]), + tire_steering_angle=0.0, + vehicle_parameters=get_pacifica_parameters(), + time_point=TimePoint(ego_pose.timestamp), + rear_axle_velocity_2d=StateVector2D(ego_pose.vx, y=ego_pose.vy), + rear_axle_acceleration_2d=StateVector2D( + x=ego_pose.acceleration_x, y=ego_pose.acceleration_y), + ) + initial_center = [initial_ego_state.waypoint.x, + initial_ego_state.waypoint.y] + info_dict['metadata']['old_origin_in_current_coordinate'] = -np.asarray(initial_center) + + # do ego sensor info extraction. + log_cam_infos = {camera.token : camera for camera in log_db.log.cameras} + cams = {} + for cam_info in log_cam_infos.values(): + cam_name = cam_info.channel + cams[cam_name] = {} + cams[cam_name]['channel'] = cam_info.channel + cams[cam_name]['sensor2ego_rotation'] = cam_info.quaternion.elements + cams[cam_name]['sensor2ego_translation'] = cam_info.translation_np + cams[cam_name]['intrinsic'] = cam_info.intrinsic_np + cams[cam_name]['distortion'] = cam_info.distortion_np + cams[cam_name]['height'] = 1080 + cams[cam_name]['width'] = 1920 + info_dict['cameras'] = cams + info_dict['lidar'] = { + 'channel': 'LIDAR_TOP', + 'sensor2ego_rotation': np.array(NUPLAN_REAL_LIDAR2EGO_ROTATION), + 'sensor2ego_translation': np.array(NUPLAN_REAL_LIDAR2EGO_TRANSLATION), + } + + # do object track statistics. + info_dict.update(dict( + object_track=extract_traffic( + log_file=log_file, + lidar_pcs=lidar_pcs, + initial_ego_center=initial_center, + sample_interval=args.sample_interval), + sdc_id=EGO, + )) + + # do traffic light statistics. + # dynamic_map_states: elements related to traffic light, + # some changeable components in the scene. + info_dict.update(dict( + dynamic_map_states=extract_traffic_light( + log_file=log_file, + lidar_pcs=lidar_pcs, + map_api=map_api, + initial_ego_center=initial_center, + ) + )) + + # do map element extraction. + # extract polygons of each map element. + info_dict.update( + map_features=extract_map_features( + map_api=map_api, + initial_ego_center=initial_center) + ) + + del map_api + return_dict[log_name] = info_dict + +class CanBus: + """Wrapper class to convert lidar_can_bus to numpy array""" + + def __init__(self, lidar_pc): + self.x = lidar_pc.ego_pose.x + self.y = lidar_pc.ego_pose.y + self.z = lidar_pc.ego_pose.z + + self.qw = lidar_pc.ego_pose.qw + self.qx = lidar_pc.ego_pose.qx + self.qy = lidar_pc.ego_pose.qy + self.qz = lidar_pc.ego_pose.qz + + self.acceleration_x = lidar_pc.ego_pose.acceleration_x + self.acceleration_y = lidar_pc.ego_pose.acceleration_y + self.acceleration_z = lidar_pc.ego_pose.acceleration_z + + self.vx = lidar_pc.ego_pose.vx + self.vy = lidar_pc.ego_pose.vy + self.vz = lidar_pc.ego_pose.vz + + self.angular_rate_x = lidar_pc.ego_pose.angular_rate_x + self.angular_rate_y = lidar_pc.ego_pose.angular_rate_y + self.angular_rate_z = lidar_pc.ego_pose.angular_rate_z + + # loc: [0:3], quat: [3:7], accel: [7:10], velocity: [10:13], rotation_rate: [13:16] + self.tensor = np.array( + [ + self.x, + self.y, + self.z, + self.qw, + self.qx, + self.qy, + self.qz, + self.acceleration_x, + self.acceleration_y, + self.acceleration_z, + self.vx, + self.vy, + self.vz, + self.angular_rate_x, + self.angular_rate_y, + self.angular_rate_z, + 0.0, + 0.0, + ] + ) + +def is_vehicle_moving(scene_tensor, agent_idx, validity, movement_threshold=3.0): + """ + Determine whether a vehicle is moving from its cumulative L2 displacement over valid timesteps. + + Args: + scene_tensor: Scene data as a torch.Tensor or numpy.ndarray. + agent_idx: Index of the agent. + validity: Validity mask for the agent. + movement_threshold: Cumulative displacement threshold in meters. Defaults to 3.0. + + Returns: + bool: True if cumulative displacement exceeds the threshold; otherwise False. + """ + # Use coordinates in meters; normalized displacements may never exceed the threshold. + if isinstance(scene_tensor, torch.Tensor): + scene_tensor_copy = scene_tensor.clone() + scene_tensor_copy = decode_scene_tensor(scene_tensor_copy) + else: + scene_tensor_copy = scene_tensor.copy() + scene_tensor_copy = torch.from_numpy(scene_tensor_copy) + scene_tensor_copy = decode_scene_tensor(scene_tensor_copy) + + # Identify the valid timesteps for this agent. + if isinstance(validity, np.ndarray): + validity = torch.from_numpy(validity) + valid_timesteps = validity[agent_idx] > 0.5 + if valid_timesteps.sum() < 2: # At least two valid timesteps are needed to compute displacement. + return False + + # Get positions at valid timesteps. + valid_positions = scene_tensor_copy[agent_idx, valid_timesteps, :2] # [x, y] + + # Sum the L2 distances between consecutive valid positions. + cumulative_displacement = 0.0 + for i in range(len(valid_positions) - 1): + displacement = torch.norm(valid_positions[i+1] - valid_positions[i]).item() + cumulative_displacement += displacement + + return cumulative_displacement > movement_threshold diff --git a/projects/BWM/scripts/generation_general/utils/type.py b/projects/BWM/scripts/generation_general/utils/type.py new file mode 100644 index 0000000..abd63d4 --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/type.py @@ -0,0 +1,240 @@ +""" +Types of different componenets in the simulator. +""" + +import logging + +logger = logging.getLogger(__name__) + + +class WorldEngineObjectType: + """ + Following waymo style, this class defines a set of strings used to denote different types of objects. + + NOTE: when add new keys, make sure class method works well for them + """ + + # ===== Lane, Road ===== + LANE_SURFACE_STREET = "LANE_SURFACE_STREET" + # Unlike a set of lanes separated by broken/solid line, this includes intersection and some unstructured roads. + LANE_SURFACE_UNSTRUCTURE = "LANE_SURFACE_UNSTRUCTURE" + # use them as less frequent as possible, it is for waymo compatibility + LANE_UNKNOWN = "LANE_UNKNOWN" + LANE_FREEWAY = "LANE_FREEWAY" + LANE_BIKE_LANE = "LANE_BIKE_LANE" + + # ===== Lane Line ===== + LINE_UNKNOWN = "UNKNOWN_LINE" + LINE_BROKEN_SINGLE_WHITE = "ROAD_LINE_BROKEN_SINGLE_WHITE" + LINE_SOLID_SINGLE_WHITE = "ROAD_LINE_SOLID_SINGLE_WHITE" + LINE_SOLID_DOUBLE_WHITE = "ROAD_LINE_SOLID_DOUBLE_WHITE" + LINE_BROKEN_SINGLE_YELLOW = "ROAD_LINE_BROKEN_SINGLE_YELLOW" + LINE_BROKEN_DOUBLE_YELLOW = "ROAD_LINE_BROKEN_DOUBLE_YELLOW" + LINE_SOLID_SINGLE_YELLOW = "ROAD_LINE_SOLID_SINGLE_YELLOW" + LINE_SOLID_DOUBLE_YELLOW = "ROAD_LINE_SOLID_DOUBLE_YELLOW" + LINE_PASSING_DOUBLE_YELLOW = "ROAD_LINE_PASSING_DOUBLE_YELLOW" + + # ===== Edge/Boundary/SideWalk/Region ===== + BOUNDARY_UNKNOWN = "UNKNOWN" # line + BOUNDARY_LINE = "ROAD_EDGE_BOUNDARY" # line + BOUNDARY_MEDIAN = "ROAD_EDGE_MEDIAN" # line + BOUNDARY_SIDEWALK = "ROAD_EDGE_SIDEWALK" # polygon + STOP_SIGN = "STOP_SIGN" + CROSSWALK = "CROSSWALK" + SPEED_BUMP = "SPEED_BUMP" + DRIVEWAY = "DRIVEWAY" + GUARDRAIL = "GUARDRAIL" # A thickened sidewalk that doesn't allow object to penetrate. + + # ===== Traffic Light ===== + LANE_STATE_UNKNOWN = "LANE_STATE_UNKNOWN" + LANE_STATE_ARROW_STOP = "LANE_STATE_ARROW_STOP" + LANE_STATE_ARROW_CAUTION = "LANE_STATE_ARROW_CAUTION" + LANE_STATE_ARROW_GO = "LANE_STATE_ARROW_GO" + LANE_STATE_STOP = "LANE_STATE_STOP" + LANE_STATE_CAUTION = "LANE_STATE_CAUTION" + LANE_STATE_GO = "LANE_STATE_GO" + LANE_STATE_FLASHING_STOP = "LANE_STATE_FLASHING_STOP" + LANE_STATE_FLASHING_CAUTION = "LANE_STATE_FLASHING_CAUTION" + + # the light states above will be converted to the following 4 types + LIGHT_GREEN = "TRAFFIC_LIGHT_GREEN" + LIGHT_RED = "TRAFFIC_LIGHT_RED" + LIGHT_YELLOW = "TRAFFIC_LIGHT_YELLOW" + LIGHT_UNKNOWN = "TRAFFIC_LIGHT_UNKNOWN" + + # ===== Agent type ===== + UNSET = "UNSET" + VEHICLE = "VEHICLE" + PEDESTRIAN = "PEDESTRIAN" + CYCLIST = "CYCLIST" + OTHER = "OTHER" + + # ===== Object type ===== + TRAFFIC_LIGHT = "TRAFFIC_LIGHT" + TRAFFIC_BARRIER = "TRAFFIC_BARRIER" + TRAFFIC_CONE = "TRAFFIC_CONE" + TRAFFIC_OBJECT = "TRAFFIC_OBJECT" + GROUND = "GROUND" + INVISIBLE_WALL = "INVISIBLE_WALL" + BUILDING = "BUILDING" + + # ===== Coordinate system ===== + COORDINATE_METADRIVE = "metadrive" + COORDINATE_WAYMO = "waymo" + + @classmethod + def is_traffic_object(cls, type): + return type in [cls.TRAFFIC_CONE, cls.TRAFFIC_BARRIER, cls.TRAFFIC_OBJECT] + + @classmethod + def has_type(cls, type_string: str): + return type_string in cls.__dict__ + + @classmethod + def from_waymo(cls, waymo_type_string: str): + assert cls.__dict__[waymo_type_string] + return waymo_type_string + + @classmethod + def is_lane(cls, type): + return type in [ + cls.LANE_SURFACE_STREET, cls.LANE_SURFACE_UNSTRUCTURE, cls.LANE_UNKNOWN, cls.LANE_BIKE_LANE, + cls.LANE_FREEWAY + ] + + @classmethod + def is_road_line(cls, line): + """ + This function relates to is_road_edge. We will have different processing when treating a line that + is in the boundary or not. + """ + return line in [ + cls.LINE_UNKNOWN, cls.LINE_BROKEN_SINGLE_WHITE, cls.LINE_SOLID_SINGLE_WHITE, cls.LINE_SOLID_DOUBLE_WHITE, + cls.LINE_BROKEN_SINGLE_YELLOW, cls.LINE_BROKEN_DOUBLE_YELLOW, cls.LINE_SOLID_SINGLE_YELLOW, + cls.LINE_SOLID_DOUBLE_YELLOW, cls.LINE_PASSING_DOUBLE_YELLOW + ] + + @classmethod + def is_yellow_line(cls, line): + return line in [ + cls.LINE_SOLID_DOUBLE_YELLOW, cls.LINE_PASSING_DOUBLE_YELLOW, cls.LINE_SOLID_SINGLE_YELLOW, + cls.LINE_BROKEN_DOUBLE_YELLOW, cls.LINE_BROKEN_SINGLE_YELLOW + ] + + @classmethod + def is_white_line(cls, line): + return WorldEngineObjectType.is_road_line(line) and not WorldEngineObjectType.is_yellow_line(line) + + @classmethod + def is_broken_line(cls, line): + return line in [cls.LINE_BROKEN_DOUBLE_YELLOW, cls.LINE_BROKEN_SINGLE_YELLOW, cls.LINE_BROKEN_SINGLE_WHITE] + + @classmethod + def is_solid_line(cls, line): + return line in [ + cls.LINE_SOLID_DOUBLE_WHITE, cls.LINE_SOLID_DOUBLE_YELLOW, cls.LINE_SOLID_SINGLE_YELLOW, + cls.LINE_SOLID_SINGLE_WHITE + ] + + @classmethod + def is_road_boundary_line(cls, edge): + """ + This function relates to is_road_line. + """ + return edge in [cls.BOUNDARY_UNKNOWN, cls.BOUNDARY_LINE, cls.BOUNDARY_MEDIAN] + + @classmethod + def is_sidewalk(cls, edge): + return edge == cls.BOUNDARY_SIDEWALK + + @classmethod + def is_stop_sign(cls, type): + return type == WorldEngineObjectType.STOP_SIGN + + @classmethod + def is_speed_bump(cls, type): + return type == WorldEngineObjectType.SPEED_BUMP + + @classmethod + def is_driveway(cls, type): + return type == WorldEngineObjectType.DRIVEWAY + + @classmethod + def is_crosswalk(cls, type): + return type == WorldEngineObjectType.CROSSWALK + + @classmethod + def is_vehicle(cls, type): + return type == cls.VEHICLE + + @classmethod + def is_pedestrian(cls, type): + return type == cls.PEDESTRIAN + + @classmethod + def is_cyclist(cls, type): + return type == cls.CYCLIST + + @classmethod + def is_participant(cls, type): + return type in (cls.CYCLIST, cls.PEDESTRIAN, cls.VEHICLE, cls.UNSET, cls.OTHER) + + @classmethod + def is_traffic_light_in_yellow(cls, light): + return cls.simplify_light_status(light) == cls.LIGHT_YELLOW + + @classmethod + def is_traffic_light_in_green(cls, light): + return cls.simplify_light_status(light) == cls.LIGHT_GREEN + + @classmethod + def is_traffic_light_in_red(cls, light): + return cls.simplify_light_status(light) == cls.LIGHT_RED + + @classmethod + def is_traffic_light_unknown(cls, light): + return cls.simplify_light_status(light) == cls.LIGHT_UNKNOWN + + @classmethod + def parse_light_status(cls, status: str, simplifying=True): + """ + Parse light status from ENUM to STR + """ + # if data_source == "waymo": + # status = cls.LIGHT_ENUM_TO_STR[status] + if simplifying: + return cls.simplify_light_status(status) + else: + return status + + @classmethod + def simplify_light_status(cls, status: str): + """ + Convert status to red/yellow/green/unknown + """ + if status in [cls.LANE_STATE_UNKNOWN, cls.LANE_STATE_FLASHING_STOP, cls.LIGHT_UNKNOWN, None]: + return cls.LIGHT_UNKNOWN + elif status in [cls.LANE_STATE_ARROW_STOP, cls.LANE_STATE_STOP, cls.LIGHT_RED]: + return cls.LIGHT_RED + elif status in [cls.LANE_STATE_ARROW_CAUTION, cls.LANE_STATE_CAUTION, cls.LANE_STATE_FLASHING_CAUTION, + cls.LIGHT_YELLOW]: + return cls.LIGHT_YELLOW + elif status in [cls.LANE_STATE_ARROW_GO, cls.LANE_STATE_GO, cls.LIGHT_GREEN]: + return cls.LIGHT_GREEN + else: + logger.warning("TrafficLightStatus: {} is not WorldEngineObjectType".format(status)) + return cls.LIGHT_UNKNOWN + + def __init__(self, type=None): + # TODO extend this base class to all objects! It is only affect lane so far. + # TODO Or people can only know the type with isinstance() + self.type = WorldEngineObjectType.UNSET + if type is not None: + self.set_type(type) + + def set_type(self, type): + if type in WorldEngineObjectType.__dict__.values(): + # Do something if type matches one of the class variables + self.type = type + else: + raise ValueError(f"'{type}' is not a valid WorldEngineObjectType.") diff --git a/projects/BWM/scripts/generation_general/utils/utils_core.py b/projects/BWM/scripts/generation_general/utils/utils_core.py new file mode 100644 index 0000000..f57f327 --- /dev/null +++ b/projects/BWM/scripts/generation_general/utils/utils_core.py @@ -0,0 +1,771 @@ +from abc import ABC, abstractmethod +import copy +import math +import numpy as np +import torch +from typing import Any, Dict, List, Tuple + +from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario +from nuplan.common.actor_state.vehicle_parameters import VehicleParameters +from nuplan.common.actor_state.ego_state import EgoState +from nuplan.common.actor_state.state_representation import StateSE2, StateVector2D, TimePoint +from nuplan.planning.training.preprocessing.features.abstract_model_feature import AbstractModelFeature +from nuplan.planning.scenario_builder.scenario_filter import ScenarioFilter +from nuplan.common.actor_state.vehicle_parameters import VehicleParameters +from nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario_utils import ScenarioMapping +from nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario_builder import NuPlanScenarioBuilder +from nuplan.planning.utils.multithreading.worker_parallel import SingleMachineParallelExecutor +from nuplan.common.actor_state.tracked_objects_types import TrackedObjectType +from nuplan.planning.training.preprocessing.utils.agents_preprocessing import ( + AgentInternalIndex, + EgoInternalIndex, +) +from nuplan.common.actor_state.state_representation import Point2D, StateSE2 + +import torch +import math +from copy import deepcopy +import numpy as np + +FEATURE_MEANS = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.5, 2.0] +FEATURE_STD = [52.0, 52.0, 0.5, 0.5, 2.0, 2.0, 2.5, 0.8] + + +class MissingFeatureAtCenterException(Exception): + pass + + +class MissingFeatureAtIterationException(Exception): + pass + + +class MissingFeatureException(Exception): + pass + + +NONEXISTENT_FEATURE = object() + +class NpAgentState(np.ndarray): + """A numpy array wrapper for other agent state.""" + dim = 8 + track_token_index = 0 + vx_index = 1 + vy_index = 2 + heading_index = 3 + width_index = 4 + length_index = 5 + x_index = 6 + y_index = 7 + + @property + def data(self): + return self + + @property + def track_token(self): + return self[..., 0] + + @property + def vx(self): + return self[..., 1] + + @property + def vy(self): + return self[..., 2] + + @property + def heading(self): + return self[..., 3] + + @property + def width(self): + return self[..., 4] + + @property + def length(self): + return self[..., 5] + + @property + def x(self): + return self[..., 6] + + @property + def y(self): + return self[..., 7] + + + def bounding_box(self): + """Get the bounding box of the ego vehicle. + + :return The bounding box of the ego vehicle, represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + """ + x = self.x + y = self.y + heading = self.heading + half_length = self.length / 2 + half_width = self.width / 2 + return np.stack([x, y, heading, half_length, half_width], axis=-1) + + def transform(self, trans, heading): + xy = np.stack([self.x, self.y], axis=-1) @ trans[:2, :2].T + trans[:2, 2] + vxy = np.stack([self.vx, self.vy], axis=-1) @ trans[:2, :2].T + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.vx_index] = vxy[..., 0] + self[..., self.vy_index] = vxy[..., 1] + self[..., self.heading_index] = self.heading - heading + + def inverse_transform(self, trans, heading): + xy = (np.stack([self.x, self.y], axis=-1) - trans[:2, 2]) @ np.linalg.inv(trans[:2, :2].T) + vxy = np.stack([self.vx, self.vy], axis=-1) @ np.linalg.inv(trans[:2, :2].T) + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.vx_index] = vxy[..., 0] + self[..., self.vy_index] = vxy[..., 1] + self[..., self.heading_index] = self.heading + heading + + +class NpEgoState(np.ndarray): + """A numpy array wrapper for ego state.""" + + dim = 17 + time_index = 0 + x_index = 1 + y_index = 2 + heading_index = 3 + vel_lon_index = 4 + vel_lat_index = 5 + acc_lon_index = 6 + acc_lat_index = 7 + tire_steering_angle_index = 8 + yaw_rate_index = 9 + yaw_acc_index = 10 + wheel_base_index = 15 + + @property + def data(self): + return self + + @property + def time(self): + # in seconds + return self[..., 0] + + @property + def x(self): + """Real axle x coordinate.""" + return self[..., 1] + + @property + def y(self): + """Real axle y coordinate.""" + return self[..., 2] + + @property + def heading(self): + return self[..., 3] + + @property + def vel_lon(self): + return self[..., 4] + + @property + def vel_lat(self): + return self[..., 5] + + @property + def acc_lon(self): + return self[..., 6] + + @property + def acc_lat(self): + return self[..., 7] + + @property + def tire_steering_angle(self): + return self[..., 8] + + @property + def yaw_rate(self): + return self[..., 9] + + @property + def yaw_acc(self): + return self[..., 10] + + @property + def width(self): + return self[..., 11] + + @property + def length(self): + return self[..., 12] + + @property + def front_length(self): + return self[..., 13] + + @property + def rear_length(self): + return self[..., 14] + + @property + def cog_position_from_rear_axle(self): + return self[..., 15] + + @property + def wheel_base(self): + return self[..., 16] + + @property + def height(self): + return self[..., 17] + + @property + def rear_axle_pose(self): + return StateSE2(self.x, self.y, self.heading) + + @property + def rear_axle_velocity_2d(self): + return StateVector2D(self.vel_lon, self.vel_lat) + + @property + def rear_axle_acceleration_2d(self): + return StateVector2D(self.acc_lon, self.acc_lat) + + def bounding_box(self): + """Get the bounding box of the ego vehicle. + + :return The bounding box of the ego vehicle, represented by 5 numbers: + center_x, center_y, heading, half_length, half_width + """ + # convert to center position + center_x = self.x + self.rear_length * np.cos(self.heading) + center_y = self.y + self.rear_length * np.sin(self.heading) + half_length = self.length / 2 + half_width = self.width / 2 + heading = self.heading + return np.stack([center_x, center_y, heading, half_length, half_width], axis=-1) + + def to_nuplan_ego_state(self) -> EgoState: + rear_axle_pose = self.rear_axle_pose + rear_axle_velocity_2d = self.rear_axle_velocity_2d + rear_axle_acceleration_2d = self.rear_axle_acceleration_2d + tire_steering_angle = self.tire_steering_angle + time_point = TimePoint(int(self.time * 1e6)) + + vehicle_parameters = VehicleParameters( + width=self.width, + front_length=self.front_length, + rear_length=self.rear_length, + wheel_base=self.wheel_base, + height=self.height, + cog_position_from_rear_axle=self.cog_position_from_rear_axle, + ) + + return EgoState.build_from_rear_axle( + rear_axle_pose=rear_axle_pose, + rear_axle_velocity_2d=rear_axle_velocity_2d, + rear_axle_acceleration_2d=rear_axle_acceleration_2d, + tire_steering_angle=tire_steering_angle, + time_point=time_point, + vehicle_parameters=vehicle_parameters, + angular_vel=self.yaw_rate, + angular_accel=self.yaw_acc, + ) + + def transform(self, trans, heading): + xy = np.stack([self.x, self.y], axis=-1) @ trans[:2, :2].T + trans[:2, 2] + vxy = np.stack([self.vel_lon, self.vel_lat], axis=-1) @ trans[:2, :2].T + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.vel_lon_index] = vxy[..., 0] + self[..., self.vel_lat_index] = vxy[..., 1] + self[..., self.heading_index] = self.heading - heading + + def inverse_transform(self, trans, heading): + xy = (np.stack([self.x, self.y], axis=-1) - trans[:2, 2]) @ np.linalg.inv(trans[:2, :2].T) + vxy = np.stack([self.vel_lon, self.vel_lat], axis=-1) @ np.linalg.inv(trans[:2, :2].T) + self[..., self.x_index] = xy[..., 0] + self[..., self.y_index] = xy[..., 1] + self[..., self.vel_lon_index] = vxy[..., 0] + self[..., self.vel_lat_index] = vxy[..., 1] + self[..., self.heading_index] = self.heading + heading + + def with_range(self, map_range, delta): + assert delta > 0 + return np.where(np.abs(self.x) <= map_range, self, delta).view(NpEgoState) + + +def get_global_to_local_transform(pose: StateSE2): + """ + Transforms from global to agent coordinate system. Used to convert coordinates of nearby agents + relative to ego vehicle. + :param pose: agents position and orientation in global coordinate system + :return: global to local transformation matrix + """ + x, y, heading = pose.x, pose.y, pose.heading + cos_h = np.cos(heading) + sin_h = np.sin(heading) + + # transformation matrix from global to local ego vehicle coordinate system + return np.array( + [[cos_h, sin_h, -cos_h * x - sin_h * y], [-sin_h, cos_h, sin_h * x - cos_h * y], [0, 0, 1]], + dtype=np.float32, + ) + + +def invert_dict(input_dict): + return {v: k for k, v in input_dict.items()} + + +def decode_scene_tensor( + scene_tensor, +) : + return (scene_tensor * (2.0 * np.array(FEATURE_STD)) + np.array(FEATURE_MEANS)) + + +def scene_tensor_to_dict(scene_tensor, idx2token): + if isinstance(scene_tensor, torch.Tensor): + scene_tensor = scene_tensor.detach().cpu().numpy() + decoded_scene_tensor = decode_scene_tensor(scene_tensor) + return {idx2token[i]: decoded_scene_tensor[i] for i in range(len(idx2token))} + + +def encode_scene_tensor( + scene_tensor, +): + """Encode scene tensor for model input.""" + return (scene_tensor - np.array(FEATURE_MEANS)) / (2.0 * np.array(FEATURE_STD)) + + +def encode_agent( + cls: str, + agent_state, +) -> np.ndarray: + """Encode agent state to a fixed feature vector.""" + if cls == "VEHICLE": + return np.concatenate( + [ + agent_state[:, 1:3], + np.cos(agent_state[:, 3:4]), + np.sin(agent_state[:, 3:4]), + agent_state[:, 4:6], + agent_state[:, 6:8], + ], + axis=-1, + ) + elif cls == "PEDESTRIAN": + return np.concatenate( + [ + agent_state[:, 1:3], + np.cos(agent_state[:, 3:4]), + np.sin(agent_state[:, 3:4]), + agent_state[:, 4:6], + np.full_like(agent_state[:, 6:8], [1.0, 1.0]), + ], + axis=-1, + ) + elif cls == "BICYCLE": + return np.concatenate( + [ + agent_state[:, 1:3], + np.cos(agent_state[:, 3:4]), + np.sin(agent_state[:, 3:4]), + agent_state[:, 4:6], + agent_state[:, 6:8], + ], + axis=-1, + ) + + +def _radian(d): + """Convert degrees to radians.""" + return d * math.pi / 180 + + +def _get_ego_state(scenario: AbstractScenario, iter: int): + """Get ego state at a given iteration of a scenario. + + Returns: + ego_state: EgoState. + """ + ego_state = scenario.get_ego_state_at_iteration(iter) + return ego_state + + +class PreparedScenario(AbstractModelFeature): + """ + A scenario that has been preprocessed/prepared for multi-feature extraction. + """ + + def __init__(self): + super().__init__() + self._features = {} + self._features_at_center = {} + self._features_at_iteration = {} + self._backup_features = {} + + def serialize(self) -> Dict[str, Any]: + return {} + + def _populate_yaw_rate_and_acc(self): + yaw_rate = np.zeros(self._ego_state.shape) + yaw_acc = np.zeros(self._ego_state.shape) + for i in range(1, len(self._ego_state)): + dt = max( + (self._time_stamps[i] - self._time_stamps[i - 1]) / 1e6, 1e-2 + ) # in seconds + yaw_rate[i] = (self._ego_state[i].heading - self._ego_state[i - 1].heading) / dt + for i in range(1, len(yaw_rate)): + dt = max( + (self._time_stamps[i] - self._time_stamps[i - 1]) / 1e6, 1e-2 + ) # in seconds + yaw_acc[i] = (yaw_rate[i] - yaw_rate[i - 1]) / dt + + # fill the yaw_rate and acc in the ego state + for i in range(len(self._ego_state)): + self._ego_state[i][self._ego_state[i].yaw_rate_index] = yaw_rate[i] + self._ego_state[i][self._ego_state[i].yaw_acc_index] = yaw_acc[i] + + @classmethod + def deserialize(cls, data: Dict[str, Any]) -> AbstractModelFeature: + return cls() + + @property + def map_name(self) -> str: + return self._map_name + + @property + def mission_goal(self) -> StateSE2: + return self._mission_goal + + def _populate_tire_steering_angle(self): + # Populate tire steering angle for ego states. + for ego_state in self._ego_state: + # not populated tire steering angle + if ego_state.tire_steering_angle == 0: + # approximation: delta = L * w / V + vel = np.linalg.norm([ego_state.vel_lon, ego_state.vel_lat]) + if vel > 0.1: + ego_state[ego_state.tire_steering_angle_index] = ego_state.wheel_base * ego_state.yaw_rate / vel + + def to_feature_tensor(self) -> AbstractModelFeature: + return self + + def to_device(self, device: torch.device) -> AbstractModelFeature: + return self + + def unpack(self) -> List[AbstractModelFeature]: + return [self] + + def prepare_scenario(self, scenario: AbstractScenario, + iterations: range) -> None: + """ + Prepare scenario by populating a feature cache. + + Note that this is a pre-processing step. It is called before features are computed. + + :param scenario: Scenario to prepare. + :param iterations: Iterations to prepare. + """ + # Extract scenario information + self._scenario = scenario + self._map_name = scenario.map_api.map_name + self._mission_goal = scenario.get_mission_goal() + self._db_interval = scenario.database_interval + self._log_name = scenario.log_name + self._scenario_token = scenario.token + self._initial_iteration = iterations[0] + self._total_iterations = iterations[-1] - iterations[0] + 1 + self._iterations = iterations + + # Process states + vehicle_parameters = scenario._initial_ego_state.car_footprint.vehicle_parameters + ego_states = scenario._map_name_ego_states(iterations) + timestamps = scenario._map_iteration_to_time_point(iterations) + + # Convert to NpEgoState + self._ego_state = [self._build_np_ego_state(ego_state, vehicle_parameters) for ego_state in ego_states] + self._time_stamps = [t.time_us for t in timestamps] + + # Populate missing dynamics + self._populate_yaw_rate_and_acc() + self._populate_tire_steering_angle() + + def add_ego_state_at_iteration(self, ego_state: EgoState, iteration: int): + """ + Replace the ego state of this scenario at a given iteration. + + :param ego_state: New ego state. + :param iteration: Iteration at which to replace the ego state. + """ + if iteration not in self._iterations: + raise ValueError(f"Cannot replace ego state at iteration {iteration} because it was not included during preparation.") + + np_ego_state = self._build_np_ego_state(ego_state, ego_state.car_footprint.vehicle_parameters) + index = self._iter_to_index(iteration) + self._ego_state[index] = np_ego_state + + def _build_np_ego_state(self, ego_state: EgoState, vehicle_parameters: VehicleParameters) -> NpEgoState: + """Build an NpEgoState from an EgoState.""" + return np.array([ + ego_state.time_point.time_us / 1e6, # Convert to seconds + ego_state.rear_axle.x, + ego_state.rear_axle.y, + ego_state.rear_axle.heading, + ego_state.dynamic_car_state.rear_axle_velocity_2d.x, + ego_state.dynamic_car_state.rear_axle_velocity_2d.y, + ego_state.dynamic_car_state.rear_axle_acceleration_2d.x, + ego_state.dynamic_car_state.rear_axle_acceleration_2d.y, + ego_state.tire_steering_angle, + 0.0, # yaw_rate - populated later + 0.0, # yaw_acc - populated later + vehicle_parameters.width, + vehicle_parameters.length, + vehicle_parameters.front_length, + vehicle_parameters.rear_length, + vehicle_parameters.cog_position_from_rear_axle, + vehicle_parameters.wheel_base, + vehicle_parameters.height, + ]).view(NpEgoState) + + def get_offset(self) -> np.ndarray: + """Get the offset of this scenario.""" + ego_state_start = self._ego_state[0] + return np.array([ego_state_start.x, ego_state_start.y]) + + def get_feature(self, feature_name: str) -> Any: + """ + Get a generic scenario feature. + + :param feature_name: Name of the feature to retrieve. + :return: The feature, if it exists. + :raises MissingFeatureException: If the feature is missing. + """ + if not self.feature_exists(feature_name): + raise MissingFeatureException() + + return self._features[feature_name] + + def feature_exists(self, feature_name: str) -> bool: + """ + Return whether a feature exists. + + :param feature_name: Name of the feature to check. + :return: True if the feature exists, False otherwise. + """ + return feature_name in self._features + + def add_feature(self, feature_name: str, feature_value: Any): + """ + Add a feature to the scenario. + + :param feature_name: Name of the feature to add. + :param feature_value: Value of the feature to add. + """ + self._features[feature_name] = feature_value + + def get_feature_at_center(self, feature_name: str, + center: Tuple[int, int]) -> Any: + """ + Get a feature centered at a particular location on a grid. + + :param feature_name: Name of the feature to retrieve. + :param center: Center of the grid. + :return: The feature, if it exists. + :raises MissingFeatureAtCenterException: If the feature is missing. + """ + if not self.feature_exists_at_center(feature_name, center): + raise MissingFeatureAtCenterException() + + return self._features_at_center[feature_name][center] + + def feature_exists_at_center(self, feature_name: str, + center: Tuple[int, int]) -> bool: + """ + Return whether a feature exists at a particular center. + + :param feature_name: Name of the feature to check. + :param center: Center of the grid. + :return: True if the feature exists, False otherwise. + """ + return feature_name in self._features_at_center and center in self._features_at_center[feature_name] + + def add_feature_at_center(self, feature_name: str, feature_value, + center: Tuple[int, int]): + """ + Add a feature to the scenario at a particular center. + + :param feature_name: Name of the feature to add. + :param feature_value: Value of the feature to add. + :param center: Center of the grid. + """ + if feature_name not in self._features_at_center: + self._features_at_center[feature_name] = {} + self._features_at_center[feature_name][center] = feature_value + + def get_feature_at_iteration(self, feature_name: str, + iteration: int) -> Any: + """ + Get a feature at a particular iteration. + + :param feature_name: Name of the feature to retrieve. + :param iteration: Iteration at which to retrieve the feature. + :return: The feature, if it exists. + :raises MissingFeatureAtIterationException: If the feature is missing. + """ + if not self.feature_exists_at_iteration(feature_name, iteration): + raise MissingFeatureAtIterationException() + + return self._features_at_iteration[feature_name][iteration] + + def feature_exists_at_iteration(self, feature_name: str, + iteration: int) -> bool: + """ + Return whether a feature exists at a particular iteration. + + :param feature_name: Name of the feature to check. + :param iteration: Iteration at which to check the feature. + :return: True if the feature exists, False otherwise. + """ + return feature_name in self._features_at_iteration and iteration in self._features_at_iteration[feature_name] + + def add_feature_at_iteration(self, feature_name: str, feature_value, + iteration: int): + """ + Add a feature to the scenario at a particular iteration. + + :param feature_name: Name of the feature to add. + :param feature_value: Value of the feature to add. + :param iteration: Iteration at which to add the feature. + """ + if feature_name not in self._features_at_iteration: + self._features_at_iteration[feature_name] = {} + self._features_at_iteration[feature_name][iteration] = feature_value + + @property + def log_name(self) -> str: + return self._log_name + + @property + def token(self) -> str: + return self._scenario_token + + @property + def database_interval(self) -> float: + return self._db_interval + + @property + def iterations(self) -> range: + return self._iterations + + def get_mission_goal(self) -> StateSE2: + return self._mission_goal + + def _iter_to_index(self, iteration: int) -> int: + return iteration - self._initial_iteration + + def get_ego_state_at_iteration(self, iteration: int) -> NpEgoState: + """ + Get the ego state of this scenario at a given iteration. + + :param iteration: Iteration at which to get the ego state. + :return: Ego state at the given iteration. + """ + if iteration not in self._iterations: + raise ValueError(f"Cannot get ego state at iteration {iteration} because it was not included during preparation.") + + index = self._iter_to_index(iteration) + return self._ego_state[index] + + def get_number_of_iterations(self) -> int: + return self._total_iterations + + def get_time_point(self, iteration: int) -> TimePoint: + """ + Get the time point corresponding to an iteration. + + :param iteration: Iteration. + :return: Time point. + """ + index = self._iter_to_index(iteration) + return TimePoint(self._time_stamps[index]) + + def backup_feature(self, feature_name: str): + """ + Back up a feature of the scenario. + + :param feature_name: Name of the feature to back up. + """ + if self.feature_exists(feature_name): + self._backup_features[feature_name] = deepcopy(self.get_feature(feature_name)) + else: + self._backup_features[feature_name] = NONEXISTENT_FEATURE + + def get_backup_feature(self, feature_name: str): + """Get a backup feature.""" + return self._backup_features.get(feature_name, NONEXISTENT_FEATURE) + + def restore_feature(self, feature_name: str): + """ + Restore a feature of the scenario from backup. + + :param feature_name: Name of the feature to restore. + """ + backup = self.get_backup_feature(feature_name) + if backup is NONEXISTENT_FEATURE: + if self.feature_exists(feature_name): + del self._features[feature_name] + else: + self.add_feature(feature_name, backup) + + +class ScenarioPreparer(ABC): + """ + Interface for preparing scenarios for feature extraction. + """ + + @abstractmethod + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + """ + Prepare a scenario for feature extraction. + + :param scenario: Scenario to be prepared. + :param prepared_scenario: Prepared scenario to be populated. + :param iterations: Iterations to prepare for. + """ + pass + + +class PreparedScenarioFeatureBuilder(ScenarioPreparer): + + @abstractmethod + def prepare_scenario(self, scenario: AbstractScenario, + prepared_scenario: PreparedScenario, + iterations: range) -> None: + """ + Prepare scenario for feature extraction. + + :param scenario: Scenario to be prepared. + :param prepared_scenario: Prepared scenario to be populated. + :param iterations: Iterations to prepare for. + """ + pass + + @abstractmethod + def get_features_from_prepared_scenario( + self, scenario: PreparedScenario, iteration: int, + ego_state: NpEgoState) -> AbstractModelFeature: + """ + Extract a feature from a prepared scenario. + + :param scenario: Prepared scenario. + :param iteration: Iteration at which to extract the feature. + :param ego_state: Ego state. + :return: Extracted feature. + """ + pass \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/visualizers/__init__.py b/projects/BWM/scripts/generation_general/visualizers/__init__.py new file mode 100644 index 0000000..89ef90e --- /dev/null +++ b/projects/BWM/scripts/generation_general/visualizers/__init__.py @@ -0,0 +1,13 @@ +from visualizers.scene_visualizer import ( + visualize_scene_tensor, + visualize_scene_tensor_global, + visualize_scene_template, + visualize_scenario_description +) + +__all__ = [ + 'visualize_scene_tensor', + 'visualize_scene_tensor_global', + 'visualize_scene_template', + 'visualize_scenario_description' +] \ No newline at end of file diff --git a/projects/BWM/scripts/generation_general/visualizers/scene_visualizer.py b/projects/BWM/scripts/generation_general/visualizers/scene_visualizer.py new file mode 100644 index 0000000..cb7f087 --- /dev/null +++ b/projects/BWM/scripts/generation_general/visualizers/scene_visualizer.py @@ -0,0 +1,562 @@ +""" +Scene visualization functionality for scene tensors and scene templates. +""" +import sys +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.patches as patches +import imageio +import os + +from nuplan_extent.planning.training.preprocessing.features.scene_tensor import decode_scene_tensor + + +def visualize_scene_tensor(scene_tensor, output_dir=None, output_filename="original_scene.gif", fps=2): + """ + Visualize vehicle bounding boxes in the scene and generate GIF animation. + + Args: + scene_tensor: SceneTensor object containing: + - tensor: shape (NA, 21, 8), vehicle states across 21 timesteps, + dimensions: x, y, cos(yaw), sin(yaw), vx, vy, length, width + - validity: shape (NA, 21), indicates if each vehicle is valid at each timestep + - road_graph and road_graph_validity can be extended as needed (not processed here) + output_dir: Output directory path, if None, use current working directory + output_filename: Output GIF filename, default "original_scene.gif" + fps: GIF animation frame rate, default 2 frames per second + """ + + # Construct full output path + if output_dir is None: + output_path = output_filename + else: + os.makedirs(output_dir, exist_ok=True) + output_path = os.path.join(output_dir, output_filename) + + # Get vehicle states and validity information + tensor = scene_tensor.tensor # shape: (NA, 21, 8) - normalized data + validity = scene_tensor.validity # shape: (NA, 21) + + # Denormalize to get real local coordinates + tensor = decode_scene_tensor(tensor) + + num_vehicles, num_timesteps, _ = tensor.shape + + # Calculate coordinate range for all valid vehicles to ensure consistent axes across frames + valid_mask = validity >= 0.5 # Validity mask, using 0.5 as threshold + + all_x = tensor[:, :, 0] + all_y = tensor[:, :, 1] + + # Only take coordinates of valid positions + valid_x = all_x[valid_mask] + valid_y = all_y[valid_mask] + + if len(valid_x) > 0 and len(valid_y) > 0: + margin = 10 # Reserve boundary + x_min, x_max = np.min(valid_x) - margin, np.max(valid_x) + margin + y_min, y_max = np.min(valid_y) - margin, np.max(valid_y) + margin + else: + # If no valid data, use default range + x_min, x_max, y_min, y_max = -50, 50, -50, 50 + + frames = [] # Store each frame image + + for t in range(num_timesteps): + fig, ax = plt.subplots(figsize=(8, 8)) + ax.set_xlim(x_min, x_max) + ax.set_ylim(y_min, y_max) + ax.set_aspect('equal') + ax.set_title(f"Time step {t}") + + # Iterate through each vehicle + for i in range(num_vehicles): + # Skip if vehicle is invalid at current timestep + if validity[i, t] < 0.5: + continue + + # Extract vehicle state information + x = tensor[i, t, 0] + y = tensor[i, t, 1] + cos_yaw = tensor[i, t, 2] + sin_yaw = tensor[i, t, 3] + # vx and vy not used for drawing here + length = tensor[i, t, 6] + width = tensor[i, t, 7] + # Calculate yaw angle (vehicle heading) in radians + yaw = np.arctan2(sin_yaw, cos_yaw) + yaw_deg = np.degrees(yaw) + + # Calculate bbox drawing parameters: + # matplotlib.patches.Rectangle requires bottom-left corner coordinates, + # while vehicle state gives (x, y) as center point, so conversion is needed: + half_length = length / 2 + half_width = width / 2 + # According to rotated rectangle formula: + # bottom_left = center - [half_length*cos(yaw) - half_width*sin(yaw), half_length*sin(yaw) + half_width*cos(yaw)] + bottom_left_x = x - (half_length * np.cos(yaw) - half_width * np.sin(yaw)) + bottom_left_y = y - (half_length * np.sin(yaw) + half_width * np.cos(yaw)) + + # Create rectangle patch representing vehicle bbox (no fill, only border) + rect = patches.Rectangle( + (bottom_left_x, bottom_left_y), + length, width, + angle=yaw_deg, + edgecolor='red', + facecolor='none', + lw=2 + ) + ax.add_patch(rect) + # Draw vehicle center point for easy observation of vehicle position + ax.plot(x, y, 'bo') + + # Convert current plot to image frame + fig.canvas.draw() + image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') + image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + frames.append(image) + plt.close(fig) + + # Generate GIF animation using imageio + imageio.mimsave(output_path, frames, fps=fps) + + +def visualize_scene_tensor_global(scene_tensor, local_to_global, center, global_offset, output_dir=None, output_filename="original_scene_global.gif", fps=2): + """ + Convert decoded scene_tensor from local to global coordinate system for visualization and generate GIF animation. + + Args: + scene_tensor: Decoded SceneTensor object containing: + - tensor: numpy array, shape (NA, 21, 8), vehicle states across 21 timesteps, + dimensions: x, y, cos(yaw), sin(yaw), vx, vy, length, width + - validity: numpy array, shape (NA, 21), indicates if vehicle is valid at each timestep + local_to_global: 3×3 numpy array, homogeneous transformation matrix from local to global coordinates + center: Global coordinate system center reference object, must contain heading attribute (in radians) for vehicle orientation adjustment + global_offset: numpy array, shape (2,), x, y offset in global coordinate system + output_dir: Output directory path, if None, use current working directory + output_filename: Output GIF filename, default "scene_global.gif" + fps: GIF frame rate, default 2 frames per second + """ + + # Construct full output path + if output_dir is None: + output_path = output_filename + else: + os.makedirs(output_dir, exist_ok=True) + output_path = os.path.join(output_dir, output_filename) + + # Get original tensor and validity information (tensor data is in local coordinates) + tensor = decode_scene_tensor(scene_tensor.tensor) # shape: (NA, 21, 8) + validity = scene_tensor.validity # shape: (NA, 21) + num_vehicles, num_timesteps, _ = tensor.shape + + # Coordinate transformation + # 1. Position transformation: apply homogeneous coordinate transformation to x,y in tensor (shape: (NA, T, 2)) + xy_local = tensor[:, :, 0:2] # local coordinates (x, y) + ones = np.ones((num_vehicles, num_timesteps, 1)) + xy_local_h = np.concatenate([xy_local, ones], axis=-1) # (NA, T, 3) + # Use np.einsum to apply local_to_global transformation to each point + xy_global_h = np.einsum('ij,ntj->nti', local_to_global, xy_local_h) + xy_global = xy_global_h[:, :, :2] # Extract transformed (x, y) + # Add global offset + xy_global = xy_global + global_offset # broadcast offset (2,) + + # 2. Orientation transformation: local yaw needs to add center.heading + local_yaw = np.arctan2(tensor[:, :, 3], tensor[:, :, 2]) # shape: (NA, T) + global_yaw = local_yaw + center.heading + global_cos = np.cos(global_yaw) + global_sin = np.sin(global_yaw) + + # 3. Velocity transformation (optional): only transform rotation part (ignore translation) + local_vel = tensor[:, :, 4:6] # (NA, T, 2) + # Rotation matrix given by center.heading + ch = center.heading + rot = np.array([[np.cos(ch), -np.sin(ch)], + [np.sin(ch), np.cos(ch)]]) + global_vel = np.einsum('ij,ntj->nti', rot, local_vel) + + # Construct transformed global_tensor + global_tensor = tensor.copy() + global_tensor[:, :, 0:2] = xy_global # Update center position + global_tensor[:, :, 2] = global_cos # Update cos(yaw) + global_tensor[:, :, 3] = global_sin # Update sin(yaw) + global_tensor[:, :, 4:6] = global_vel # Update velocity + + # Visualization + # Calculate drawing range based on global data + all_x = global_tensor[:, :, 0] + all_y = global_tensor[:, :, 1] + margin = 10 + x_min, x_max = np.min(all_x) - margin, np.max(all_x) + margin + y_min, y_max = np.min(all_y) - margin, np.max(all_y) + margin + + frames = [] + + for t in range(num_timesteps): + fig, ax = plt.subplots(figsize=(8, 8)) + ax.set_xlim(x_min, x_max) + ax.set_ylim(y_min, y_max) + ax.set_aspect('equal') + ax.set_title(f"Global Time step {t}") + + for i in range(num_vehicles): + if validity[i, t] < 0.5: + continue + # Extract transformed global vehicle state + x = global_tensor[i, t, 0] + y = global_tensor[i, t, 1] + cos_yaw = global_tensor[i, t, 2] + sin_yaw = global_tensor[i, t, 3] + length = global_tensor[i, t, 6] + width = global_tensor[i, t, 7] + yaw = np.arctan2(sin_yaw, cos_yaw) + yaw_deg = np.degrees(yaw) + + half_length = length / 2 + half_width = width / 2 + # Calculate bottom-left corner coordinates (since Rectangle uses bottom-left as anchor point) + bottom_left_x = x - (half_length * np.cos(yaw) - half_width * np.sin(yaw)) + bottom_left_y = y - (half_length * np.sin(yaw) + half_width * np.cos(yaw)) + + # Set colors based on vehicle type: ego (index 0) vs other vehicles + if i == 0: # Ego vehicle + edge_color = 'blue' # Special color for ego vehicle + center_color = 'go' # blue dot for ego center + else: # Other vehicles + edge_color = 'red' # Red for other vehicles + center_color = 'ro' # Red dot for other vehicle centers + + rect = patches.Rectangle( + (bottom_left_x, bottom_left_y), + length, width, + angle=yaw_deg, + edgecolor=edge_color, + facecolor='none', + lw=2 + ) + ax.add_patch(rect) + ax.plot(x, y, center_color) # Draw vehicle center with appropriate color + + fig.canvas.draw() + image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') + image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + frames.append(image) + plt.close(fig) + + imageio.mimsave(output_path, frames, fps=fps) + + +def visualize_scene_template(scene_template, output_dir=None, output_filename="scene_template.gif", fps=2): + """ + Visualize scenes in scene_template as GIF animation. + + Args: + scene_template: Scene template dictionary containing frames and metadata + output_dir: Output directory path, if None, use current working directory + output_filename: Output GIF filename, default "scene_template.gif" + fps: GIF frame rate, default 2 frames per second + + Input scene_template format example: + + scene_template = { + "scene_metadata": { + "log_name": "nuplan log name", + "map_name": "nuplan map/city name, e.g. us-nv-las-vegas-strip", + "initial_token": "The token I gave to you", + }, + "frames": [ + { + "token": , + "ego_status": { + "ego_pose": np.array([x, y, heading]), # Global coordinates, heading in radians + "ego_velocity": np.array([vx, vy]), # Global coordinates + "ego_acceleration": np.array([ax, ay]), # Global coordinates (can be set to 0) + }, + "annotations": { + "boxes": np.array([ # Each row represents a target vehicle bbox, [x, y, z, l, w, h, heading] + [x, y, z, l, w, h, heading], + ... + ]), + "velocity_3d": np.array([ # Each row corresponds to a target vehicle velocity, [vx, vy, vz] (vz set to 0) + [vx, vy, vz], + ... + ]), + "names": [ "vehicle", ... ], + "track_tokens": [ token, ... ] + } + }, + ... + ] + } + + All coordinate information is in global coordinate system. + """ + + # Construct full output path + if output_dir is None: + output_path = output_filename + else: + os.makedirs(output_dir, exist_ok=True) + output_path = os.path.join(output_dir, output_filename) + + frames = scene_template["frames"] + + # Calculate global drawing range (extract x,y range from ego and all vehicle bboxes) + all_x = [] + all_y = [] + for frame in frames: + # Ego position + ego_pose = frame["ego_status"]["ego_pose"] + all_x.append(ego_pose[0]) + all_y.append(ego_pose[1]) + # Target vehicle bboxes for each frame + boxes = frame["annotations"]["boxes"] + if boxes.size > 0: + # boxes is 2D array (N,7), take columns 0 and 1 + all_x.extend(boxes[:, 0]) + all_y.extend(boxes[:, 1]) + margin = 10 + x_min = min(all_x) - margin + x_max = max(all_x) + margin + y_min = min(all_y) - margin + y_max = max(all_y) + margin + + gif_frames = [] + for idx, frame in enumerate(frames): + fig, ax = plt.subplots(figsize=(8,8)) + ax.set_xlim(x_min, x_max) + ax.set_ylim(y_min, y_max) + ax.set_aspect("equal") + ax.set_title(f"Frame {idx}") + + # Draw ego vehicle + ego_status = frame["ego_status"] + ego_pose = ego_status["ego_pose"] # [x, y, heading] + ego_x, ego_y, ego_heading = ego_pose + ego_vel = ego_status["ego_velocity"] + + # Assume ego vehicle size is unknown, use default size (4,2) m to draw ego vehicle + ego_length = 4.0 + ego_width = 2.0 + half_length = ego_length / 2.0 + half_width = ego_width / 2.0 + # Calculate bottom-left corner coordinates based on center coordinates and rotation angle + ego_bl_x = ego_x - (half_length * np.cos(ego_heading) - half_width * np.sin(ego_heading)) + ego_bl_y = ego_y - (half_length * np.sin(ego_heading) + half_width * np.cos(ego_heading)) + rect_ego = patches.Rectangle((ego_bl_x, ego_bl_y), ego_length, ego_width, + angle=np.degrees(ego_heading), + edgecolor="blue", facecolor="none", lw=2, label="ego") + ax.add_patch(rect_ego) + ax.plot(ego_x, ego_y, "bo") # Ego center point + + # Draw ego velocity vector (as arrow) + ax.arrow(ego_x, ego_y, ego_vel[0], ego_vel[1], + head_width=0.5, head_length=0.5, fc="blue", ec="blue") + + # Draw other vehicles + ann = frame["annotations"] + boxes = ann["boxes"] + velocities = ann["velocity_3d"] + # Draw bbox for each target vehicle + if boxes.size > 0: + for i in range(boxes.shape[0]): + x, y, z, l, w, h, heading = boxes[i] + half_l = l / 2.0 + half_w = w / 2.0 + # Calculate bottom-left corner + bl_x = x - (half_l * np.cos(heading) - half_w * np.sin(heading)) + bl_y = y - (half_l * np.sin(heading) + half_w * np.cos(heading)) + rect = patches.Rectangle((bl_x, bl_y), l, w, + angle=np.degrees(heading), + edgecolor="red", facecolor="none", lw=2) + ax.add_patch(rect) + ax.plot(x, y, "ro") + # Draw velocity vector (red arrow) + vx, vy, vz = velocities[i] + ax.arrow(x, y, vx, vy, head_width=0.5, head_length=0.5, fc="red", ec="red") + + # Draw current frame's lidar_pc token as title supplement (optional) + ax.text(x_min + 5, y_max - 5, f"Token: {frame['token']}", color="black", fontsize=12) + + # Convert current frame to image + fig.canvas.draw() + image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + gif_frames.append(image) + plt.close(fig) + + # Generate GIF animation + imageio.mimsave(output_path, gif_frames, fps=fps) + + +def visualize_scenario_description(scenario_description, output_dir=None, output_filename="scenario_description.gif", fps=2): + """ + Visualize scenario description as GIF animation. + + Args: + scenario_description: Scenario description dictionary containing object tracks and metadata + output_dir: Output directory path, if None, use current working directory + output_filename: Output GIF filename, default "scenario_description.gif" + fps: GIF frame rate, default 2 frames per second + + Input scenario_description format: + { + "scenario_id": { + "id": str, + "log_length": int, + "metadata": { + "nuplan_lidar_pc_tokens": [str, ...], + "total_frames": int, + ... + }, + "object_track": { + "ego": { + "type": "VEHICLE", + "state": { + "position": np.array([[x,y,z], ...]), # Shape: (total_frames, 3) + "heading": np.array([h, ...]), # Shape: (total_frames,) + "velocity": np.array([[vx,vy], ...]), # Shape: (total_frames, 2) + "valid": np.array([1.0, ...]), # Shape: (total_frames,) + "length": np.array([l, ...]), # Shape: (total_frames,) + "width": np.array([w, ...]), # Shape: (total_frames,) + "height": np.array([h, ...]), # Shape: (total_frames,) + }, + "metadata": { + "type": "VEHICLE", + "track_length": total_frames, + "object_id": "ego", + "nuplan_type": "ego" + } + }, + # ... other agents with same structure + }, + ... + } + } + """ + + # Extract scenario data (assume scenario_description is a dict with one key - scenario_id) + scenario_id = list(scenario_description.keys())[0] + scenario_data = scenario_description[scenario_id] + + # Construct full output path + if output_dir is None: + output_path = output_filename + else: + os.makedirs(output_dir, exist_ok=True) + output_path = os.path.join(output_dir, output_filename) + + # Get basic info + total_frames = scenario_data["metadata"]["total_frames"] + lidar_tokens = scenario_data["metadata"]["nuplan_lidar_pc_tokens"] + object_tracks = scenario_data["object_track"] + + # Calculate global drawing range from all tracks + all_x = [] + all_y = [] + + for track_id, track_data in object_tracks.items(): + state = track_data["state"] + valid = state["valid"] + positions = state["position"] + + # Only use valid positions + valid_mask = valid >= 0.5 + if np.any(valid_mask): + valid_positions = positions[valid_mask] + all_x.extend(valid_positions[:, 0]) + all_y.extend(valid_positions[:, 1]) + + if len(all_x) > 0 and len(all_y) > 0: + margin = 10 + x_min = min(all_x) - margin + x_max = max(all_x) + margin + y_min = min(all_y) - margin + y_max = max(all_y) + margin + else: + # Default range if no valid data + x_min, x_max, y_min, y_max = -50, 50, -50, 50 + + gif_frames = [] + + # Generate frames + for frame_idx in range(total_frames): + fig, ax = plt.subplots(figsize=(8, 8)) + ax.set_xlim(x_min, x_max) + ax.set_ylim(y_min, y_max) + ax.set_aspect("equal") + ax.set_title(f"Frame {frame_idx}") + + # Draw each track for current frame + for track_id, track_data in object_tracks.items(): + state = track_data["state"] + + # Check if track is valid at current frame + if frame_idx >= len(state["valid"]) or state["valid"][frame_idx] < 0.5: + continue + + # Get track info for current frame + position = state["position"][frame_idx] # [x, y, z] + heading = state["heading"][frame_idx] + velocity = state["velocity"][frame_idx] # [vx, vy] + + # Get vehicle dimensions + if "length" in state and frame_idx < len(state["length"]): + length = state["length"][frame_idx] + if hasattr(length, '__len__') and len(length) > 0: + length = length[0] # Extract from array if needed + else: + length = 4.0 # Default length + + if "width" in state and frame_idx < len(state["width"]): + width = state["width"][frame_idx] + if hasattr(width, '__len__') and len(width) > 0: + width = width[0] # Extract from array if needed + else: + width = 2.0 # Default width + + x, y = position[0], position[1] + + # Set colors based on track type + if track_id == "ego": + color = "blue" + label = "ego" + else: + color = "red" + label = "other" + + # Draw vehicle bounding box + half_length = length / 2.0 + half_width = width / 2.0 + + # Calculate bottom-left corner coordinates + bl_x = x - (half_length * np.cos(heading) - half_width * np.sin(heading)) + bl_y = y - (half_length * np.sin(heading) + half_width * np.cos(heading)) + + rect = patches.Rectangle((bl_x, bl_y), length, width, + angle=np.degrees(heading), + edgecolor=color, facecolor="none", lw=2) + ax.add_patch(rect) + + # Draw center point + ax.plot(x, y, color[0] + "o") # 'bo' for blue, 'ro' for red + + # Draw velocity vector as arrow + if len(velocity) >= 2: + ax.arrow(x, y, velocity[0], velocity[1], + head_width=0.5, head_length=0.5, fc=color, ec=color) + + # Add frame info + if frame_idx < len(lidar_tokens): + ax.text(x_min + 5, y_max - 5, f"Token: {lidar_tokens[frame_idx]}", + color="black", fontsize=10) + + # Convert current frame to image + fig.canvas.draw() + image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + gif_frames.append(image) + plt.close(fig) + + # Generate GIF animation + imageio.mimsave(output_path, gif_frames, fps=fps) \ No newline at end of file diff --git a/projects/BWM/tests/test_checkpoint_loader.py b/projects/BWM/tests/test_checkpoint_loader.py new file mode 100644 index 0000000..9afe743 --- /dev/null +++ b/projects/BWM/tests/test_checkpoint_loader.py @@ -0,0 +1,163 @@ +import importlib.util +import subprocess +import sys +from pathlib import Path + +import pytest +import torch + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +LOADER_PATH = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "utils" + / "checkpoint_loader.py" +) + +KNOWN_TRAINING_METADATA = ( + ( + "nuplan_extent.planning.training.modeling.objectives.diffusion_objective", + "DiffusionObjective", + ), + ( + "nuplan_extent.planning.training.modeling.metrics.dummy_metric", + "DummyMetric", + ), + ( + "nuplan_extent.planning.training.modeling.aggregated_metrics.behavior_prediction", + "BehaviorPredictionMetric", + ), +) + + +def _load_checkpoint_loader(): + assert LOADER_PATH.is_file(), "checkpoint loader has not been implemented" + spec = importlib.util.spec_from_file_location( + "bwm_checkpoint_loader", + LOADER_PATH, + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _write_synthetic_checkpoint( + tmp_path, + module_name, + class_name, +): + checkpoint_path = tmp_path / f"{class_name}.ckpt" + script = """ +import collections +import sys +import types + +import torch + + +checkpoint_path, module_name, class_name = sys.argv[1:] +module_parts = module_name.split(".") +for index in range(1, len(module_parts) + 1): + current_name = ".".join(module_parts[:index]) + current_module = types.ModuleType(current_name) + if index < len(module_parts): + current_module.__path__ = [] + sys.modules[current_name] = current_module + if index > 1: + parent_name = ".".join(module_parts[: index - 1]) + setattr( + sys.modules[parent_name], + module_parts[index - 1], + current_module, + ) + +metadata_class = type(class_name, (), {}) +metadata_class.__module__ = module_name +setattr(sys.modules[module_name], class_name, metadata_class) + +torch.save( + { + "state_dict": collections.OrderedDict( + {"model.weight": torch.tensor([1.0])} + ), + "training_metadata": metadata_class(), + }, + checkpoint_path, +) +""" + result = subprocess.run( + [ + sys.executable, + "-c", + script, + str(checkpoint_path), + module_name, + class_name, + ], + cwd=WORLDENGINE_ROOT, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + return checkpoint_path + + +@pytest.mark.parametrize( + ("module_name", "class_name"), + KNOWN_TRAINING_METADATA, +) +def test_loads_state_dict_without_deleted_training_metadata( + tmp_path, + module_name, + class_name, +): + checkpoint = _write_synthetic_checkpoint( + tmp_path, + module_name, + class_name, + ) + with pytest.raises(ModuleNotFoundError): + torch.load( + checkpoint, + map_location="cpu", + weights_only=False, + ) + + loader = _load_checkpoint_loader() + state_dict = loader.load_inference_state_dict(checkpoint) + + assert list(state_dict) == ["model.weight"] + assert torch.equal( + state_dict["model.weight"], + torch.tensor([1.0]), + ) + + +def test_does_not_ignore_unknown_missing_classes(tmp_path): + checkpoint = _write_synthetic_checkpoint( + tmp_path, + "removed.unrelated.metadata", + "UnknownMetadata", + ) + loader = _load_checkpoint_loader() + + with pytest.raises(ModuleNotFoundError): + loader.load_inference_state_dict(checkpoint) + + +def test_rejects_checkpoint_without_mapping_state_dict(tmp_path): + checkpoint = tmp_path / "malformed.ckpt" + torch.save({"state_dict": None}, checkpoint) + loader = _load_checkpoint_loader() + + with pytest.raises( + loader.CheckpointFormatError, + match="mapping-valued 'state_dict'", + ): + loader.load_inference_state_dict(checkpoint) diff --git a/projects/BWM/tests/test_config_loader.py b/projects/BWM/tests/test_config_loader.py new file mode 100644 index 0000000..d54474c --- /dev/null +++ b/projects/BWM/tests/test_config_loader.py @@ -0,0 +1,429 @@ +import importlib.util +from pathlib import Path +import pytest + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +CONFIG_LOADER_PATH = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "utils" + / "config_loader.py" +) + + +def _load_config_loader(): + assert CONFIG_LOADER_PATH.is_file(), "BWM config loader has not been implemented" + spec = importlib.util.spec_from_file_location( + "bwm_config_loader", CONFIG_LOADER_PATH + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_composes_layers_and_imports_only_scene_selection(tmp_path): + default_path = tmp_path / "configs" / "default.yaml" + scenario_path = tmp_path / "configs" / "scenarios" / "sample.yaml" + scene_filter_path = tmp_path / "filters" / "sample.yaml" + default_path.parent.mkdir(parents=True) + scenario_path.parent.mkdir(parents=True) + scene_filter_path.parent.mkdir(parents=True) + + default_path.write_text( + "\n".join( + [ + "data_type: default", + "generation:", + " tasks:", + " goal_conditional_copy_with_noise:", + " max_attempts: 30", + " max_success: 7", + " intent_attack_with_goal_selection:", + " max_attempts: 20", + " max_success: 3", + "num_history_frames: 4", + "num_future_frames: 16", + "model:", + " diffuser:", + " steps: 32", + " hidden_dim: 256", + ] + ), + encoding="utf-8", + ) + scenario_path.write_text( + "\n".join( + [ + "data_type: sample", + "generation:", + " tasks:", + " goal_conditional_copy_with_noise:", + " max_attempts: 10", + "scene_filter_path: filters/sample.yaml", + "model:", + " diffuser:", + " steps: 16", + ] + ), + encoding="utf-8", + ) + scene_filter_path.write_text( + "\n".join( + [ + "log_names:", + " - log-a", + "tokens:", + " - token-a", + "num_history_frames: 99", + "num_future_frames: 99", + ] + ), + encoding="utf-8", + ) + + config_loader = _load_config_loader() + cfg = config_loader.load_generation_config( + "configs/scenarios/sample.yaml", + default_config_path="configs/default.yaml", + overrides={ + "generation": {"tasks": {"goal_conditional_copy_with_noise": {"max_success": 2}}}, + "model": {"diffuser": {"steps": 8}}, + }, + repo_root=tmp_path, + ) + + assert cfg.data_type == "sample" + assert cfg.generation.tasks.goal_conditional_copy_with_noise.max_attempts == 10 + assert cfg.generation.tasks.goal_conditional_copy_with_noise.max_success == 2 + assert cfg.generation.tasks.intent_attack_with_goal_selection.max_attempts == 20 + assert cfg.generation.tasks.intent_attack_with_goal_selection.max_success == 3 + assert cfg.model.diffuser.steps == 8 + assert cfg.model.diffuser.hidden_dim == 256 + assert cfg.num_history_frames == 4 + assert cfg.num_future_frames == 16 + assert list(cfg.log_names) == ["log-a"] + assert list(cfg.tokens) == ["token-a"] + assert cfg.scene_filter_path == str(scene_filter_path.resolve()) + +@pytest.mark.parametrize("selection_key", ["log_names", "tokens"]) +def test_rejects_scene_selection_embedded_in_scenario(tmp_path, selection_key): + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + scene_filter_path = tmp_path / "scene_filter.yaml" + default_path.write_text("num_history_frames: 4\n", encoding="utf-8") + scenario_path.write_text( + "\n".join( + [ + "scene_filter_path: scene_filter.yaml", + f"{selection_key}:", + " - embedded-value", + ] + ), + encoding="utf-8", + ) + scene_filter_path.write_text("tokens:\n - selected-token\n", encoding="utf-8") + + config_loader = _load_config_loader() + with pytest.raises( + config_loader.ConfigError, + match=f"{selection_key}.*scene_filter_path", + ): + config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + repo_root=tmp_path, + ) + +def test_reports_missing_scene_filter_file(tmp_path): + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + default_path.write_text("num_history_frames: 4\n", encoding="utf-8") + scenario_path.write_text( + "scene_filter_path: filters/missing.yaml\n", + encoding="utf-8", + ) + + config_loader = _load_config_loader() + with pytest.raises( + config_loader.ConfigError, + match=r"SceneFilter config does not exist: .*filters/missing\.yaml", + ): + config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + repo_root=tmp_path, + ) + +def test_requires_scene_filter_path(tmp_path): + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + default_path.write_text("num_history_frames: 4\n", encoding="utf-8") + scenario_path.write_text("data_type: sample\n", encoding="utf-8") + + config_loader = _load_config_loader() + with pytest.raises( + config_loader.ConfigError, + match="scenario config must define scene_filter_path", + ): + config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + repo_root=tmp_path, + ) + +@pytest.mark.parametrize("selection", [ + "has_route: true\n", "log_names: null\n", "log_names: null\ntokens: null\n", +]) +def test_rejects_scene_filter_without_supported_selection(tmp_path, selection): + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + scene_filter_path = tmp_path / "scene_filter.yaml" + default_path.write_text("num_history_frames: 4\n", encoding="utf-8") + scenario_path.write_text( + "scene_filter_path: scene_filter.yaml\n", + encoding="utf-8", + ) + scene_filter_path.write_text(selection, encoding="utf-8") + + config_loader = _load_config_loader() + with pytest.raises( + config_loader.ConfigError, + match="SceneFilter must define log_names or tokens", + ): + config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + repo_root=tmp_path, + ) + +@pytest.mark.parametrize("selection_key", ["log_names", "tokens"]) +@pytest.mark.parametrize("include_null_other", [False, True]) +def test_preserves_explicit_empty_scene_selection(tmp_path, selection_key, include_null_other): + (tmp_path / "default.yaml").write_text("num_history_frames: 4\n", encoding="utf-8") + (tmp_path / "scenario.yaml").write_text("scene_filter_path: filter.yaml\n", encoding="utf-8") + selection = f"{selection_key}: []\n" + if include_null_other: + other_key = "tokens" if selection_key == "log_names" else "log_names" + selection += f"{other_key}: null\n" + (tmp_path / "filter.yaml").write_text(selection, encoding="utf-8") + cfg = _load_config_loader().load_generation_config( + "scenario.yaml", default_config_path="default.yaml", repo_root=tmp_path, + ) + assert cfg.get(selection_key) is not None + assert list(cfg[selection_key]) == [] + +@pytest.mark.parametrize( + ("missing_file", "error_label"), + [ + ("default.yaml", "Default"), + ("scenario.yaml", "Scenario"), + ], +) +def test_reports_missing_generation_config_file(tmp_path, missing_file, error_label): + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + if missing_file != "default.yaml": + default_path.write_text("num_history_frames: 4\n", encoding="utf-8") + if missing_file != "scenario.yaml": + scenario_path.write_text( + "scene_filter_path: scene_filter.yaml\n", + encoding="utf-8", + ) + + config_loader = _load_config_loader() + with pytest.raises( + config_loader.ConfigError, + match=rf"{error_label} config does not exist: .*{missing_file}", + ): + config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + repo_root=tmp_path, + ) + +def test_repository_example_composes_with_bwm_temporal_settings(): + config_loader = _load_config_loader() + cfg = config_loader.load_generation_config( + "projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml" + ) + + assert cfg.data_type == "navtrain_ep_per1" + assert cfg.num_history_frames == 4 + assert cfg.num_future_frames == 16 + assert cfg.model.diffuser.steps == 32 + assert list(cfg.log_names) + assert list(cfg.tokens) + assert cfg.scene_filter_path == str( + ( + WORLDENGINE_ROOT + / "projects" + / "AlgEngine" + / "configs" + / "navsim_splits" + / "navtrain_split" + / "e2e_vadv2_50pct_rare" + / "navtrain_50pct_ep_1pct.yaml" + ).resolve() + ) + + +def test_entrypoint_requires_explicit_layered_config(): + config_loader = _load_config_loader() + + with pytest.raises( + config_loader.ConfigError, + match="layered BWM scenario config is required", + ): + config_loader.load_entrypoint_config() + + +def test_entrypoint_selects_layered_scenario_config(): + config_loader = _load_config_loader() + scenario_path = "projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml" + + loaded = config_loader.load_entrypoint_config(scenario_path) + + assert loaded.mode == "layered" + assert loaded.source == (WORLDENGINE_ROOT / scenario_path).resolve() + assert loaded.config.scenario_name == "navtrain_50pct_ep_1pct" + assert loaded.config.num_future_frames == 16 + + +def test_resolves_runtime_paths_after_layer_merge_without_dereferencing_symlinks( + tmp_path, +): + physical_data = tmp_path / "physical-data" + physical_data.mkdir() + (tmp_path / "data").symlink_to(physical_data, target_is_directory=True) + + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + scene_filter_path = tmp_path / "scene_filter.yaml" + absolute_checkpoint = tmp_path / "external" / "nuplan.ckpt" + + default_path.write_text( + "\n".join( + [ + "checkpoint: data/default.ckpt", + "digitaltwin_data_root: data/default-assets", + "openscene_data_root: data/default-openscene", + "scenario_builder:", + " data_root: data/default-db", + " map_root: data/default-maps", + " sensor_root: data/default-sensors", + ] + ), + encoding="utf-8", + ) + scenario_path.write_text( + "\n".join( + [ + "scene_filter_path: scene_filter.yaml", + "digitaltwin_data_root: data/scenario-assets", + ] + ), + encoding="utf-8", + ) + scene_filter_path.write_text("tokens:\n - token-a\n", encoding="utf-8") + + config_loader = _load_config_loader() + cfg = config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + overrides={ + "checkpoint": str(absolute_checkpoint), + "scenario_builder": {"map_root": "data/override-maps"}, + }, + repo_root=tmp_path, + ) + + assert cfg.checkpoint == str(absolute_checkpoint) + assert cfg.digitaltwin_data_root == str(tmp_path / "data/scenario-assets") + assert cfg.openscene_data_root == str( + tmp_path / "data/default-openscene" + ) + assert cfg.scenario_builder.data_root == str(tmp_path / "data/default-db") + assert cfg.scenario_builder.map_root == str(tmp_path / "data/override-maps") + assert cfg.scenario_builder.sensor_root == str( + tmp_path / "data/default-sensors" + ) + + +def test_resolves_output_paths_against_repository_root(tmp_path): + default_path = tmp_path / "default.yaml" + scenario_path = tmp_path / "scenario.yaml" + scene_filter_path = tmp_path / "scene_filter.yaml" + absolute_log_dir = tmp_path / "external-logs" + + default_path.write_text( + "\n".join( + [ + "scenario_name: default", + "output_dir: projects/BWM/outputs/${scenario_name}", + "log_dir: projects/BWM/logs", + "publish_root: data/sim_engine/scenarios/augmented", + ] + ), + encoding="utf-8", + ) + scenario_path.write_text( + "\n".join( + [ + "scenario_name: sample", + "scene_filter_path: scene_filter.yaml", + ] + ), + encoding="utf-8", + ) + scene_filter_path.write_text("tokens:\n - token-a\n", encoding="utf-8") + + config_loader = _load_config_loader() + cfg = config_loader.load_generation_config( + "scenario.yaml", + default_config_path="default.yaml", + overrides={"log_dir": str(absolute_log_dir)}, + repo_root=tmp_path, + ) + + assert cfg.output_dir == str( + tmp_path / "projects/BWM/outputs/sample" + ) + assert cfg.log_dir == str(absolute_log_dir) + assert cfg.publish_root == str( + tmp_path / "data/sim_engine/scenarios/augmented" + ) + + +def test_validate_runtime_paths_reports_unset_and_missing_values(tmp_path): + existing_path = tmp_path / "existing" + existing_path.mkdir() + missing_sensor_root = tmp_path / "missing-sensors" + + config_loader = _load_config_loader() + cfg = config_loader.OmegaConf.create( + { + "checkpoint": None, + "digitaltwin_data_root": str(existing_path), + "scenario_builder": { + "data_root": str(existing_path), + "map_root": str(existing_path), + "sensor_root": str(missing_sensor_root), + }, + } + ) + + with pytest.raises(config_loader.ConfigError) as error: + config_loader.validate_runtime_paths(cfg) + + message = str(error.value) + assert "checkpoint=" in message + assert "openscene_data_root=" in message + assert ( + f"scenario_builder.sensor_root={missing_sensor_root}" + in message + ) diff --git a/projects/BWM/tests/test_drivable_area.py b/projects/BWM/tests/test_drivable_area.py new file mode 100644 index 0000000..b6196a0 --- /dev/null +++ b/projects/BWM/tests/test_drivable_area.py @@ -0,0 +1,177 @@ +"""Keep DAC aligned with the complete nuPlan geometry and its polygon holes.""" + +import copy +import importlib +import json +import pickle +from pathlib import Path +from types import SimpleNamespace + +import geopandas as gpd +import numpy as np +import pytest +from nuplan.common.actor_state.vehicle_parameters import get_pacifica_parameters +from shapely.affinity import translate +from shapely.geometry import MultiPolygon, Polygon, box, mapping, shape +from shapely.ops import unary_union + + +@pytest.fixture +def modules(monkeypatch): + root = Path(__file__).resolve().parents[3] + for relative in ("projects/BWM", "projects/BWM/scripts/generation_general", "projects/SimEngine"): + monkeypatch.syspath_prepend(str(root / relative)) + return SimpleNamespace( + export=importlib.import_module("utils.nuplan_utils"), + converter=importlib.import_module("post_processor.eval_metric.description_converter"), + metrics=importlib.import_module("post_processor.eval_metric.standalone_metrics"), + native=importlib.import_module("nuplan.common.maps.nuplan_map.nuplan_map"), + publisher=importlib.import_module("publish_scenarios"), + sim=importlib.import_module("worldengine.scenario.scenarios.scenario_description"), + ) + + +@pytest.fixture +def native_map(modules): + origin = np.array([1000.0, 2000.0]) + parking = Polygon(box(60, 0, 80, 20).exterior.coords, + [box(67, 7, 73, 13).exterior.coords]) + local = { + "road_segments": [box(0, 0, 10, 10)], + "intersections": [box(10, 0, 30, 10)], + "generic_drivable_areas": [box(40, 0, 50, 10)], + "carpark_areas": [MultiPolygon([parking, box(120, 0, 130, 10)])], + } + expected = unary_union([geometry for values in local.values() for geometry in values]) + layers = { + name: gpd.GeoDataFrame(geometry=[translate(geometry, *origin) for geometry in values]) + for name, values in local.items() + } + # A remote polygon should not be included in this scene's metadata. + layers["road_segments"] = gpd.GeoDataFrame(geometry=[ + *layers["road_segments"].geometry, box(4000, 5000, 4010, 5010), + ]) + loaded = [] + + def load_vector_layer(map_name, layer_name): + loaded.append(layer_name) + return layers[layer_name] + + api = modules.native.NuPlanMap(SimpleNamespace(load_vector_layer=load_vector_layer), "test-map") + return SimpleNamespace(api=api, origin=origin, expected=expected, loaded=loaded) + + +def make_scene(native_map, position, authoritative=True, legacy_covers_everything=False): + def track(token): + track_position = np.asarray(position, dtype=float).copy() + # Explicit rear-axle data keeps geometry tests independent of the + # separate export-coordinate correction and exercises legacy tracks. + coordinate_system = "rear_axle" if token == "ego" else "center" + if token == "ego": + track_position[0] -= get_pacifica_parameters().rear_axle_to_center + return { + "type": "VEHICLE", + "state": { + "position": np.tile([*track_position, 0.0], (5, 1)), + "heading": np.zeros(5), "velocity": np.zeros((5, 2)), + "valid": np.ones(5), "length": np.full((5, 1), 4.0), + "width": np.full((5, 1), 2.0), "height": np.full((5, 1), 1.5), + }, + "metadata": {"object_id": token, "type": "VEHICLE", "coordinate_system": coordinate_system}, + } + + lane = box(-50, -50, 250, 80) if legacy_covers_everything else box(0, 0, 10, 10) + scene = { + "id": "example", "name": "example", "token": "example-token", "dataset": "bwm.nuplan", + "map": "test-map", "log_length": 5, "sample_rate": 10, "base_timestamp": 123, + "cameras": {}, "lidar": {}, "sdc_id": "ego", "dynamic_map_states": {}, + "metadata": {"old_origin_in_current_coordinate": -native_map.origin}, + "object_track": {token: track(token) for token in ("ego", "car")}, + "map_features": {"lane": { + "type": "LANE_SURFACE_STREET", "polygon": np.asarray(lane.exterior.coords), + "polyline": np.array([[0.0, 5.0], [10.0, 5.0]]), + }}, + } + if authoritative: + scene["metadata"]["drivable_area"] = { + "source": "nuplan.DRIVABLE_AREA", "coordinate_system": "global", + "geometry": mapping(translate(native_map.expected, *native_map.origin)), + } + return scene + + +def score(modules, scene, token="ego"): + agent, _, map_info = modules.converter.convert_scenario_data_with_agent_token(scene, token) + return modules.metrics.StandaloneMetricsCalculator().calculate_dac_metric_for_agent(agent, map_info)[0] + + +def test_export_uses_all_native_layers_and_preserves_holes(modules, native_map): + payload = modules.export.extract_drivable_area(native_map.api, native_map.origin, radius=200) + # Persist only native Python values; both JSON and pickle preserve this geometry. + payload = pickle.loads(pickle.dumps(json.loads(json.dumps(payload)))) + assert payload["source"] == "nuplan.DRIVABLE_AREA" + assert payload["coordinate_system"] == "global" + local_geometry = translate(shape(payload["geometry"]), *(-native_map.origin)) + assert local_geometry.equals(native_map.expected) + assert set(native_map.loaded) == { + "road_segments", "intersections", "generic_drivable_areas", "carpark_areas", + } + + +@pytest.mark.parametrize("token", ["ego", "car"]) +@pytest.mark.parametrize( + "position, expected, broad_legacy_lane", + [ + ((5, 5), 1.0, False), + ((20, 5), 1.0, False), + ((45, 5), 1.0, False), + ((65, 5), 1.0, False), + ((125, 5), 1.0, False), + ((70, 10), 0.0, True), + ((150, 50), 0.0, True), + ((-1, 5), 0.25, False), + ], + ids=["road", "intersection", "generic_area", "parking", "multipolygon_part", "hole", "off_road", "partial_overlap"], +) +def test_dac_uses_native_area_in_the_tracks_coordinate_frame(modules, native_map, token, position, expected, broad_legacy_lane): + scene = make_scene(native_map, position, legacy_covers_everything=broad_legacy_lane) + assert score(modules, scene, token) == pytest.approx(expected) + + +def test_legacy_scene_still_uses_its_lane_polygons(modules, native_map): + assert score(modules, make_scene(native_map, (5, 5), authoritative=False)) == 1.0 + assert score(modules, make_scene(native_map, (20, 5), authoritative=False)) == 0.0 + + +@pytest.mark.parametrize("problem", ["local_coordinates", "empty_geometry", "non_polygon"]) +def test_malformed_authoritative_area_does_not_silently_fall_back(modules, native_map, problem): + scene = make_scene(native_map, (5, 5)) + payload = scene["metadata"]["drivable_area"] + if problem == "local_coordinates": + payload["coordinate_system"] = "local" + elif problem == "empty_geometry": + payload["geometry"] = mapping(Polygon()) + else: + payload["geometry"] = {"type": "Point", "coordinates": [1005.0, 2005.0]} + with pytest.raises(ValueError, match="drivable.area"): + score(modules, scene) + + +def test_empty_native_query_is_reported_instead_of_assuming_dac_pass(modules, native_map): + with pytest.raises(ValueError, match="drivable.area"): + modules.export.extract_drivable_area(native_map.api, (10000, 10000), radius=10) + + +def test_publication_and_simengine_loading_preserve_dac_geometry(modules, native_map, tmp_path): + scene = make_scene(native_map, (20, 5)) + original_geometry = copy.deepcopy(scene["metadata"]["drivable_area"]) + source = tmp_path / "source.pkl" + source.write_bytes(pickle.dumps({scene["id"]: scene})) + published = modules.publisher.merge_source_files([source]) + loaded = modules.sim.ScenarioDescription(published[scene["id"]]) + loaded = modules.sim.ScenarioDescription.centralize_to_ego_car_initial_position(loaded) + modules.sim.ScenarioDescription.update_summaries(loaded) + modules.sim._recursive_check_type(loaded["metadata"]["drivable_area"], modules.sim.ScenarioDescription.ALLOW_TYPES) + modules.sim.ScenarioDescription._check_map_features(loaded["map_features"]) + assert loaded["metadata"]["drivable_area"] == original_geometry + assert score(modules, loaded) == 1.0 diff --git a/projects/BWM/tests/test_environment_contract.py b/projects/BWM/tests/test_environment_contract.py new file mode 100644 index 0000000..6a5f47a --- /dev/null +++ b/projects/BWM/tests/test_environment_contract.py @@ -0,0 +1,108 @@ +from pathlib import Path + +import yaml + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +BWM_ROOT = WORLDENGINE_ROOT / "projects" / "BWM" +ENVIRONMENT = BWM_ROOT / "environment.yml" +RUNTIME_REQUIREMENTS = BWM_ROOT / "requirements.txt" +DEV_REQUIREMENTS = BWM_ROOT / "requirements-dev.txt" +NEXUS_REQUIREMENTS = BWM_ROOT / "requirements_nexus.txt" +PUBLIC_ENTRYPOINT = WORLDENGINE_ROOT / "scripts" / "run_bwm.sh" + +NUPLAN_REQUIREMENT = ( + "nuplan-devkit @ " + "git+https://github.com/motional/nuplan-devkit.git" + "@e9241677997dd86bfc0bcd44817ab04fe631405b" +) + + +def _meaningful_lines(path): + return [ + line.strip() + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + + +def test_environment_defines_the_single_bwm_platform(): + config = yaml.safe_load(ENVIRONMENT.read_text(encoding="utf-8")) + dependencies = config["dependencies"] + pip_sections = [ + dependency["pip"] + for dependency in dependencies + if isinstance(dependency, dict) and "pip" in dependency + ] + + assert config["name"] == "bwm" + assert config["channels"] == ["pytorch", "nvidia", "conda-forge"] + assert "python=3.9" in dependencies + assert "pytorch=2.3.0" in dependencies + assert "torchvision=0.18.0" in dependencies + assert "pytorch-cuda=12.1" in dependencies + assert pip_sections == [] + + +def test_runtime_requirements_are_public_and_inference_only(): + text = RUNTIME_REQUIREMENTS.read_text(encoding="utf-8") + lines = _meaningful_lines(RUNTIME_REQUIREMENTS) + banned_fragments = ( + "/cpfs01", + "/inspire", + "file://", + "git+ssh", + "flash_attn", + "tensorflow", + "waymo-open-dataset", + "wandb", + "requirements_nexus", + ) + + assert NUPLAN_REQUIREMENT in lines + assert "pytorch-lightning==2.2.5" in lines + assert "casadi==3.7.2" in lines + assert "numba==0.60.0" in lines + assert "shapely==2.0.7" in lines + assert not any( + line.startswith(("torch==", "torchvision==", "torchaudio==")) + for line in lines + ) + for fragment in banned_fragments: + assert fragment not in text + + +def test_dev_requirements_extend_runtime_without_a_second_environment(): + lines = _meaningful_lines(DEV_REQUIREMENTS) + + assert lines[0] == "-r requirements.txt" + assert "pytest==8.4.2" in lines + assert not NEXUS_REQUIREMENTS.exists() + + +def test_public_runtime_surface_is_portable_and_uses_bwm_identity(): + public_files = [ + path + for path in BWM_ROOT.rglob("*") + if path.is_file() + and path.suffix in {".py", ".yaml", ".yml", ".txt"} + and "docs" not in path.parts + and "tests" not in path.parts + ] + public_files.append(PUBLIC_ENTRYPOINT) + + banned_fragments = ( + "/cpfs01", + "/inspire", + "scenegen.nuplan", + ) + violations = {} + for path in public_files: + text = path.read_text(encoding="utf-8") + matches = [ + fragment for fragment in banned_fragments if fragment in text + ] + if matches: + violations[str(path.relative_to(WORLDENGINE_ROOT))] = matches + + assert violations == {} diff --git a/projects/BWM/tests/test_generation_regressions.py b/projects/BWM/tests/test_generation_regressions.py new file mode 100644 index 0000000..d8d53b6 --- /dev/null +++ b/projects/BWM/tests/test_generation_regressions.py @@ -0,0 +1,176 @@ +"""Exercise scene changes, sampled goals, and incomplete tracks on CPU.""" + +import importlib +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + + +@pytest.fixture +def modules(monkeypatch): + root = Path(__file__).resolve().parents[3] + monkeypatch.syspath_prepend(str(root / "projects/BWM")) + monkeypatch.syspath_prepend(str(root / "projects/BWM/scripts/generation_general")) + return SimpleNamespace( + generator=importlib.import_module("processors.scene_generator_v2"), + features=importlib.import_module( + "nuplan_extent.planning.training.preprocessing.features.scene_tensor" + ), + diffusion=importlib.import_module( + "nuplan_extent.planning.training.modeling.models.diffusion.scenediffusion_with_opt" + ), + ) + + +def make_trajectories(n_agents=2): + trajectory = torch.zeros(n_agents, 21, 8) + trajectory[..., 2] = 1 + trajectory[..., 4] = 10 + trajectory[..., 6:] = torch.tensor([4.5, 2.0]) + trajectory[..., 0] = torch.arange(21) * 5.0 + return trajectory + + +@pytest.mark.parametrize("second_scene", ["translated_and_rotated", "empty_map", "larger_batch"]) +def test_routes_follow_each_sample_input(modules, monkeypatch, second_scene): + monkeypatch.delenv("EXTRAPOLATE", raising=False) + monkeypatch.delenv("GT_REPLACE", raising=False) + diffuser = modules.diffusion.simpleDiffusion(torch.nn.Identity(), steps=3) + route_builds = [] + solve_routes = [] + compute_routes = diffuser.compute_routes_tensor + + def count_route_builds(features): + route_builds.append(features) + compute_routes(features) + + def solve(z_t, **kwargs): + solve_routes.append(diffuser.routes_tensor.clone()) + return z_t + + def sampling_step(features, scene_tensor, z_t, keep_mask, *args, **kwargs): + result = diffuser.optimization_constrain( + features, scene_tensor.clone(), keep_mask, features.validity, + optimization=True, forward_simulation=False, + ) + return result, result, result + + # Keep the real sample loop and route builder; omit neural inference and IPOPT. + monkeypatch.setattr(diffuser, "compute_routes_tensor", count_route_builds) + monkeypatch.setattr(diffuser, "scene_nlp_optimization", solve) + monkeypatch.setattr(diffuser, "sampler_step", sampling_step) + + def run_sample(start, end, batch=1, empty=False): + tensor = modules.features.encode_scene_tensor(make_trajectories(1)).unsqueeze(0).repeat(batch, 1, 1, 1) + road = torch.zeros(batch, 1, 21, 7) + for axis in range(2): + road[:, 0, :, axis] = torch.linspace(start[axis], end[axis], 21) / 104.0 + road[..., 2] = 1 + road_validity = torch.zeros_like(road) if empty else torch.ones_like(road) + features = modules.features.SceneTensor(tensor, torch.ones(batch, 1, 21), road, road_validity) + diffuser.sample(features, tensor, features.validity, torch.ones_like(tensor), None) + + run_sample((0, 0), (10, 0)) + assert len(route_builds) == 1 + torch.testing.assert_close(diffuser.routes_tensor[0, 0, -1, :2], torch.tensor([10.0, 0.0])) + + empty = second_scene == "empty_map" + batch = 2 if second_scene == "larger_batch" else 1 + run_sample((20, 0), (20, 10), batch=batch, empty=empty) + assert len(route_builds) == 2 + assert len(solve_routes) > len(route_builds) # Reuse routes within each sample. + assert diffuser.routes_tensor.shape[0] == batch + if empty: + assert not diffuser.routes_mask.any() + else: + for b in range(batch): + assert diffuser.routes_mask[b, 0] + torch.testing.assert_close(diffuser.routes_tensor[b, 0, 0, :2], torch.tensor([20.0, 0.0])) + torch.testing.assert_close(diffuser.routes_tensor[b, 0, -1, :2], torch.tensor([20.0, 10.0])) + + +@pytest.mark.parametrize( + "points, tangent", + [ + ([(100, 0), (120, 5), (140, 5)], (20, 5)), + ([(0, 0), (100, 0), (120, 10)], (20, 10)), + ([(0, -10), (80, -10), (100, 0)], (20, 10)), + ], + ids=["first_point", "interior_point", "last_point"], +) +def test_goal_is_the_selected_sector_point(modules, points, tangent): + trajectory = make_trajectories() + trajectory[0, :, 0] = -100 # Keep ego's endpoint outside the goal sector. + road = torch.zeros(1, len(points) * 2, 7) + road[0, :, :2] = torch.tensor(points).repeat_interleave(2, dim=0) / 104.0 + encoded = modules.features.encode_scene_tensor(trajectory) + goal, valid = modules.generator.get_goal_point(encoded, road, torch.ones(2, 21)) + actual = modules.features.decode_scene_tensor(goal) + + # At frame 4 the car is at x=20 m, moving east at 10 m/s. Only x=100 + # falls in the 7-9 second sector, regardless of its index in the polyline. + assert valid == 1 + torch.testing.assert_close(actual[:2], torch.tensor([100.0, 0.0])) + direction = torch.tensor(tangent, dtype=torch.float32) + direction /= direction.norm() + torch.testing.assert_close(actual[2:4], direction) + torch.testing.assert_close(actual[4:6], 10 * direction) + torch.testing.assert_close(actual[6:], trajectory[1, 4, 6:]) + + +@pytest.mark.parametrize("empty_map", [False, True]) +def test_goal_fallback_preserves_last_valid_state(modules, empty_map): + trajectory = make_trajectories() + trajectory[1, 11:] = 0 + validity = torch.ones(2, 21) + validity[1, 11:] = 0 + road = torch.zeros(1, 21, 7) + if not empty_map: + road[..., 0] = -100 / 104.0 + goal, valid = modules.generator.get_goal_point( + modules.features.encode_scene_tensor(trajectory), road, validity, + ) + assert valid == 0 + torch.testing.assert_close(modules.features.decode_scene_tensor(goal), trajectory[1, 10]) + + +@pytest.mark.parametrize("has_complete_car", [False, True]) +def test_missing_final_frame_remains_invalid_and_in_log_replay(modules, has_complete_car): + trajectory = make_trajectories(3 if has_complete_car else 2) + trajectory[1, :, 0] += 10 + trajectory[1, 11:] = 0 + if has_complete_car: + trajectory[2, :, 0] += 5 + validity = torch.ones(trajectory.shape[:2]) + validity[1, 11:] = 0 + features = modules.features.SceneTensor( + modules.features.encode_scene_tensor(trajectory), validity, + torch.zeros(1, 21, 7), torch.zeros(1, 21, 7), + ) + wrapper = SimpleNamespace( + scene_tensor=features, + idx2token=["ego", "disappearing-car"] + (["complete-car"] if has_complete_car else []), + agent_type=["vehicle"] * len(trajectory), + ) + original_tensor = features.tensor.clone() + original_validity = validity.clone() + info = modules.generator.create_goal_conditional_copy_mask(wrapper) + + torch.testing.assert_close(features.validity, original_validity) + torch.testing.assert_close(features.tensor[1], original_tensor[1]) + assert info["scenario_valid"] == has_complete_car + if has_complete_car: + assert info["attack_agent_token"] == "complete-car" + assert info["task_mask"][1].all() + for agent in (0, 2): + assert info["task_mask"][agent, :5].all() + assert not info["task_mask"][agent, 5:-1].any() + assert info["task_mask"][agent, -1].all() + torch.testing.assert_close(features.tensor[agent, :-1], original_tensor[agent, :-1]) + torch.testing.assert_close(features.tensor[agent, -1, 2:], original_tensor[agent, -1, 2:]) + assert not torch.equal(features.tensor[agent, -1, :2], original_tensor[agent, -1, :2]) + else: + assert info["attack_agent_token"] is None + torch.testing.assert_close(features.tensor, original_tensor) diff --git a/projects/BWM/tests/test_generation_settings.py b/projects/BWM/tests/test_generation_settings.py new file mode 100644 index 0000000..d5de9b4 --- /dev/null +++ b/projects/BWM/tests/test_generation_settings.py @@ -0,0 +1,211 @@ +"""Verify generation budgets, saving, and validation without model inference.""" + +import copy +import importlib +import pickle +from collections import Counter +from pathlib import Path +from types import SimpleNamespace + +import pytest +from omegaconf import OmegaConf + + +TASKS = ("goal_conditional_copy_with_noise", "intent_attack_with_goal_selection") +DEFAULT_CONFIG = Path(__file__).resolve().parents[1] / "configs/default.yaml" + + +@pytest.fixture +def pipeline(monkeypatch): + root = Path(__file__).resolve().parents[3] + monkeypatch.syspath_prepend(str(root / "projects/BWM")) + monkeypatch.syspath_prepend(str(root / "projects/BWM/scripts/generation_general")) + return importlib.import_module("pipeline_w_opt") + + +@pytest.fixture +def cfg(): + return OmegaConf.merge(OmegaConf.load(DEFAULT_CONFIG), {"scenario_name": "test"}) + + +@pytest.fixture +def harness(pipeline, monkeypatch): + state = SimpleNamespace( + calls=[], original_visualizations=[], accepted_visualizations=[], metrics=[], + outcome=lambda task, index: "pass", + wrapper=SimpleNamespace(scene_tensor=None, trans=None, center=None, offset=None, base="base"), + ) + + def infer(wrapper, model, task): + index = state.calls.count(task) + state.calls.append(task) + outcome = state.outcome(task, index) + if outcome == "error": + raise RuntimeError("test candidate failure") + wrapper.outcome = outcome + return wrapper, {"scenario_valid": outcome != "invalid", "attack_agent_token": "car"} + + def convert(wrapper, *args): + return {wrapper.base: { + "id": wrapper.base, "name": wrapper.base, "token": wrapper.base, + "outcome": wrapper.outcome, + }} + + def check(scene, agents, *args): + assert agents == ["ego", "car"] + state.metrics.append(scene) + return None if next(iter(scene.values()))["outcome"] == "reject" else scene + + monkeypatch.setattr(pipeline, "process_scene_tensor", infer) + monkeypatch.setattr(pipeline, "convert_scene_tensor_wrapper_to_scenario_description", convert) + monkeypatch.setattr(pipeline, "metric_check", check) + monkeypatch.setattr(pipeline, "visualize_scene_tensor_global", + lambda **kwargs: state.original_visualizations.append(kwargs)) + monkeypatch.setattr(pipeline, "visualize_scenario_description", + lambda scene, **kwargs: state.accepted_visualizations.append(scene)) + return state + + +def generate(pipeline, harness, cfg): + pipeline.validate_generation_settings(cfg) + return pipeline.generate_valid_scenarios( + harness.wrapper, None, cfg.generation.tasks, None, "unused", "unused", "unused", + ) + + +@pytest.mark.parametrize("outcome, expected_calls, expected_successes", [ + ("pass", (7, 3), 10), ("reject", (30, 20), 0), +]) +def test_default_limits_order_and_output_ids(pipeline, cfg, harness, outcome, expected_calls, expected_successes): + before = OmegaConf.to_container(cfg) + harness.outcome = lambda task, index: outcome + result = generate(pipeline, harness, cfg) + assert harness.calls == [TASKS[0]] * expected_calls[0] + [TASKS[1]] * expected_calls[1] + assert list(result) == [f"base-{i:03d}" for i in range(expected_successes)] + for i, (key, scene) in enumerate(result.items()): + assert scene["id"] == scene["name"] == key + assert scene["token"] == f"base-{TASKS[0] if i < 7 else TASKS[1]}" + assert len(harness.accepted_visualizations) == expected_successes + assert OmegaConf.to_container(cfg) == before + + +def test_attempts_include_errors_invalid_candidates_and_metric_rejections(pipeline, cfg, harness): + for task in TASKS: + cfg.generation.tasks[task] = {"max_attempts": 4, "max_success": 2} + harness.outcome = lambda task, index: ["error", "invalid", "reject", "pass"][index] + result = generate(pipeline, harness, cfg) + assert Counter(harness.calls) == {task: 4 for task in TASKS} + assert len(harness.metrics) == 4 + assert list(result) == ["base-000", "base-001"] + + +def test_custom_success_limits_stop_each_task_early(pipeline, cfg, harness): + # Reverse YAML key order; runtime order must remain fixed. + cfg.generation.tasks = { + TASKS[1]: {"max_attempts": 6, "max_success": 1}, + TASKS[0]: {"max_attempts": 5, "max_success": 2}, + } + result = generate(pipeline, harness, cfg) + assert harness.calls == [TASKS[0], TASKS[0], TASKS[1]] + assert list(result) == ["base-000", "base-001", "base-002"] + + +@pytest.mark.parametrize("key", ["max_attempts", "max_success"]) +def test_zero_skips_only_that_task(pipeline, cfg, harness, key): + cfg.generation.tasks[TASKS[0]][key] = 0 + generate(pipeline, harness, cfg) + assert harness.calls == [TASKS[1]] * 3 + + +@pytest.mark.parametrize("saving", [True, False]) +def test_database_run_applies_budgets_per_base_and_controls_final_pkls( + pipeline, cfg, harness, monkeypatch, tmp_path, capsys, saving, +): + assets = tmp_path / "assets" + for base in ("log-a-ta", "log-b-tb"): + folder = assets / base + folder.mkdir(parents=True) + (folder / "video_scene_dict.pkl").touch() + cfg.tokens = ["ta", "tb"] + cfg.output_dir = str(tmp_path / "outputs") + cfg.save_scenario_description = saving + for task in TASKS: + cfg.generation.tasks[task] = {"max_attempts": 3, "max_success": 1} + before = OmegaConf.to_container(cfg) + monkeypatch.setattr(pipeline, "NuPlanDB", lambda **kwargs: SimpleNamespace( + log=SimpleNamespace(map_version="test-map"))) + monkeypatch.setattr(pipeline, "get_maps_api", lambda *args: None) + + def features(builder, log, token, *args, **kwargs): + wrapper = copy.deepcopy(harness.wrapper) + wrapper.base = f"{log}-{token}" + return wrapper + + monkeypatch.setattr(pipeline, "get_features_from_db", features) + pipeline.process_database_based_approach(cfg, None, None, str(assets)) + assert harness.calls == list(TASKS) * 2 + assert len(harness.metrics) == len(harness.accepted_visualizations) == 4 + assert len(harness.original_visualizations) == 2 + files = sorted(Path(cfg.output_dir).rglob("*.pkl")) + assert len(files) == (2 if saving else 0) + for path in files: + assert path.stem == path.parent.name + result = pickle.loads(path.read_bytes()) + assert list(result) == [f"{path.stem}-000", f"{path.stem}-001"] + assert OmegaConf.to_container(cfg) == before + output = capsys.readouterr().out + assert ("scene PKL saving is disabled" in output) == (not saving) + assert "No valid scenario description" not in output + + +@pytest.mark.parametrize("key, value, message", [ + (f"generation.tasks.{TASKS[0]}.max_attempts", -1, "non-negative integer"), + (f"generation.tasks.{TASKS[0]}.max_attempts", True, "non-negative integer"), + (f"generation.tasks.{TASKS[0]}.max_attempts", 1.5, "non-negative integer"), + (f"generation.tasks.{TASKS[0]}.max_success", "2", "non-negative integer"), + (f"generation.tasks.{TASKS[0]}.max_success", None, "non-negative integer"), + (f"generation.tasks.{TASKS[0]}.typo", 1, "max_attempts and max_success"), + (f"generation.tasks.{TASKS[0]}", {"max_attempts": 1}, "max_attempts and max_success"), + ("generation.tasks.unknown_task", {}, "must contain exactly"), + ("generation.tasks", [], "must contain exactly"), + ("generation", None, "tasks mapping"), + ("generation.typo", 1, "tasks mapping"), + ("save_scenario_description", "false", "true or false"), + ("save_scenario_description", 0, "true or false"), + ("max_iterations", 3, "max_attempts"), + ("worker", {"max_workers": 36}, "runs sequentially"), +]) +def test_invalid_generation_settings_fail_before_side_effects( + pipeline, cfg, monkeypatch, capsys, key, value, message, +): + OmegaConf.update(cfg, key, value, merge=False) + monkeypatch.setattr(pipeline, "load_entrypoint_config", lambda path: SimpleNamespace(config=cfg)) + + def unexpected(*args, **kwargs): + pytest.fail("Invalid settings must fail before runtime setup") + + for name in ("validate_runtime_paths", "setup_logging", "setup_model_and_feature_builder"): + monkeypatch.setattr(pipeline, name, unexpected) + assert pipeline.main(["--config", "unused"]) == 2 + assert message in capsys.readouterr().err + + +def test_partial_scenario_override_is_visible_in_validation(pipeline, monkeypatch, tmp_path, capsys): + scene_filter = tmp_path / "filter.yaml" + scene_filter.write_text("tokens: [ta]\n") + scenario = tmp_path / "scenario.yaml" + OmegaConf.save(OmegaConf.create({ + "scenario_name": "test", "scene_filter_path": str(scene_filter), + "generation": {"tasks": {TASKS[0]: {"max_attempts": 10, "max_success": 2}}}, + "save_scenario_description": False, + }), scenario) + monkeypatch.setattr(pipeline, "validate_runtime_paths", lambda cfg: None) + monkeypatch.setattr(pipeline, "setup_model_and_feature_builder", + lambda cfg: pytest.fail("Validation must not load the model")) + loaded = pipeline.load_entrypoint_config(str(scenario)) + assert loaded.config.model == OmegaConf.load(DEFAULT_CONFIG).model + assert pipeline.main(["--config", str(scenario), "--validate-config"]) == 0 + output = capsys.readouterr().out + assert f"{TASKS[0]}: max_attempts=10, max_success=2" in output + assert f"{TASKS[1]}: max_attempts=20, max_success=3" in output + assert "save_scenario_description: false" in output diff --git a/projects/BWM/tests/test_inference_imports.py b/projects/BWM/tests/test_inference_imports.py new file mode 100644 index 0000000..b3db357 --- /dev/null +++ b/projects/BWM/tests/test_inference_imports.py @@ -0,0 +1,77 @@ +import subprocess +import sys +from pathlib import Path + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +BWM_ROOT = WORLDENGINE_ROOT / "projects" / "BWM" +PIPELINE_DIR = BWM_ROOT / "scripts" / "generation_general" +DEFAULT_CONFIG = BWM_ROOT / "configs" / "default.yaml" + +BLOCKED_MODULES = ( + "alf", + "cvxpy", + "diffusers", + "perceiver", + "ray", + "rotary_embedding_torch", + "tensorflow", + "torchaudio", + "wandb", + "waymo_open_dataset", +) + + +def test_default_inference_graph_imports_without_optional_research_packages(): + probe = f""" +import importlib +import sys +from pathlib import Path + +from omegaconf import OmegaConf + +for module_name in {BLOCKED_MODULES!r}: + sys.modules[module_name] = None + +bwm_root = Path({str(BWM_ROOT)!r}) +pipeline_dir = Path({str(PIPELINE_DIR)!r}) +sys.path.insert(0, str(bwm_root)) +sys.path.insert(0, str(pipeline_dir)) + +import pipeline_w_opt + + +def collect_targets(node): + if isinstance(node, dict): + target = node.get("_target_") + if target: + yield str(target) + for child in node.values(): + yield from collect_targets(child) + elif isinstance(node, list): + for child in node: + yield from collect_targets(child) + + +config = OmegaConf.to_container( + OmegaConf.load(Path({str(DEFAULT_CONFIG)!r})), + resolve=False, +) +targets = sorted(set(collect_targets(config))) +for target in targets: + module_name, attribute = target.rsplit(".", 1) + module = importlib.import_module(module_name) + getattr(module, attribute) + +print(f"loaded_targets={{len(targets)}}") +""" + result = subprocess.run( + [sys.executable, "-c", probe], + cwd=WORLDENGINE_ROOT, + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0, result.stderr + assert "loaded_targets=" in result.stdout diff --git a/projects/BWM/tests/test_launcher.py b/projects/BWM/tests/test_launcher.py new file mode 100644 index 0000000..2daeece --- /dev/null +++ b/projects/BWM/tests/test_launcher.py @@ -0,0 +1,108 @@ +import os +import subprocess +from pathlib import Path + +import pytest + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +LAUNCHER = WORLDENGINE_ROOT / "scripts" / "run_bwm.sh" +PIPELINE = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "pipeline_w_opt.py" +) +SCENARIO = "projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml" + + +def _fake_python(tmp_path, *, exit_code=0): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + capture_path = tmp_path / "python-arguments.txt" + fake_python = bin_dir / "python" + fake_python.write_text( + "#!/usr/bin/env bash\n" + 'printf "%s\\n" "$@" > "$BWM_LAUNCHER_CAPTURE"\n' + 'exit "${BWM_FAKE_EXIT_CODE:-0}"\n', + encoding="utf-8", + ) + fake_python.chmod(0o755) + + env = os.environ.copy() + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["BWM_LAUNCHER_CAPTURE"] = str(capture_path) + env["BWM_FAKE_EXIT_CODE"] = str(exit_code) + return env, capture_path + + +def _run_launcher(tmp_path, *arguments, exit_code=0): + env, capture_path = _fake_python(tmp_path, exit_code=exit_code) + result = subprocess.run( + ["bash", str(LAUNCHER), *arguments], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + captured = ( + capture_path.read_text(encoding="utf-8").splitlines() + if capture_path.exists() + else [] + ) + return result, captured + + +@pytest.mark.parametrize( + ("subcommand", "expected"), + [ + ( + "validate", + [str(PIPELINE), "--validate-config", "--config", SCENARIO], + ), + ( + "generate", + [str(PIPELINE), "--config", SCENARIO], + ), + ], +) +def test_dispatches_from_any_working_directory(tmp_path, subcommand, expected): + result, captured = _run_launcher( + tmp_path, + subcommand, + "--config", + SCENARIO, + ) + + assert result.returncode == 0, result.stderr + assert captured == expected + + +@pytest.mark.parametrize( + "arguments", + [ + (), + ("unknown",), + ], +) +def test_rejects_missing_or_unknown_subcommand(tmp_path, arguments): + result, captured = _run_launcher(tmp_path, *arguments) + + assert result.returncode == 2 + assert "Usage: scripts/run_bwm.sh {validate|generate|publish}" in result.stderr + assert captured == [] + + +def test_propagates_pipeline_exit_code(tmp_path): + result, _ = _run_launcher( + tmp_path, + "generate", + "--config", + SCENARIO, + exit_code=7, + ) + + assert result.returncode == 7 diff --git a/projects/BWM/tests/test_launcher_publish.py b/projects/BWM/tests/test_launcher_publish.py new file mode 100644 index 0000000..ea2aecc --- /dev/null +++ b/projects/BWM/tests/test_launcher_publish.py @@ -0,0 +1,90 @@ +import os +import subprocess +from pathlib import Path + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +LAUNCHER = WORLDENGINE_ROOT / "scripts" / "run_bwm.sh" +PUBLISHER = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "publish_scenarios.py" +) +SCENARIO = "projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml" + + +def _run_launcher(tmp_path, *arguments, exit_code=0): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + capture_path = tmp_path / "python-arguments.txt" + fake_python = bin_dir / "python" + fake_python.write_text( + "#!/usr/bin/env bash\n" + 'printf "%s\\n" "$@" > "$BWM_LAUNCHER_CAPTURE"\n' + 'exit "${BWM_FAKE_EXIT_CODE:-0}"\n', + encoding="utf-8", + ) + fake_python.chmod(0o755) + + env = os.environ.copy() + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["BWM_LAUNCHER_CAPTURE"] = str(capture_path) + env["BWM_FAKE_EXIT_CODE"] = str(exit_code) + result = subprocess.run( + ["bash", str(LAUNCHER), *arguments], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + captured = ( + capture_path.read_text(encoding="utf-8").splitlines() + if capture_path.exists() + else [] + ) + return result, captured + + +def test_dispatches_publish_from_any_working_directory(tmp_path): + result, captured = _run_launcher( + tmp_path, + "publish", + "--config", + SCENARIO, + "--overwrite", + ) + + assert result.returncode == 0, result.stderr + assert captured == [ + str(PUBLISHER), + "--config", + SCENARIO, + "--overwrite", + ] + + +def test_propagates_publisher_exit_code(tmp_path): + result, _ = _run_launcher( + tmp_path, + "publish", + "--config", + SCENARIO, + exit_code=9, + ) + + assert result.returncode == 9 + + +def test_usage_lists_publish(tmp_path): + result, captured = _run_launcher(tmp_path, "unknown") + + assert result.returncode == 2 + assert ( + "Usage: scripts/run_bwm.sh {validate|generate|publish}" + in result.stderr + ) + assert captured == [] diff --git a/projects/BWM/tests/test_map_feature_geometry.py b/projects/BWM/tests/test_map_feature_geometry.py new file mode 100644 index 0000000..49c0ba1 --- /dev/null +++ b/projects/BWM/tests/test_map_feature_geometry.py @@ -0,0 +1,44 @@ +"""Keep database map inputs consistent with the training feature builder.""" + +import importlib +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +from shapely.geometry import LineString, Polygon + + +@pytest.mark.parametrize("feature_type", ["LANE", "LANE_CONNECTOR", "STOP_LINE", "CROSSWALK"]) +@pytest.mark.parametrize("heading", [None, np.pi / 2], ids=["translated", "rotated"]) +def test_map_geometry_matches_training_features(monkeypatch, feature_type, heading): + root = Path(__file__).resolve().parents[3] + monkeypatch.syspath_prepend(str(root / "projects/BWM")) + monkeypatch.syspath_prepend(str(root / "projects/BWM/scripts/generation_general")) + loader = importlib.import_module("data_loaders.database_loader") + training = importlib.import_module( + "nuplan_extent.planning.training.preprocessing.features.raster_builders" + ) + map_object = SimpleNamespace( + baseline_path=SimpleNamespace( + linestring=LineString([(100, 200), (101, 204), (104, 210)]) + ), + polygon=Polygon([(99, 198), (107, 198), (107, 212), (99, 212)]), + speed_limit_mps=8.5, + ) + offset = np.array([100.0, 200.0]) + rotation = None if heading is None else (np.cos(heading), np.sin(heading)) + actual = loader.MapObjectWrapper(map_object, feature_type, offset, rotation) + + # Match the real training geometry, including its point order. + if feature_type in ("LANE", "LANE_CONNECTOR"): + expected = training._linestring_to_coords(map_object) - offset + else: + expected = training._polygon_to_coords(map_object) - offset + if rotation is not None: + c, s = rotation + expected = expected @ np.array([[c, -s], [s, c]]) + + np.testing.assert_allclose(actual.coords, expected, atol=1e-12) + assert actual.object_type == feature_type + assert actual.speed_limit == 8.5 diff --git a/projects/BWM/tests/test_pipeline_cli.py b/projects/BWM/tests/test_pipeline_cli.py new file mode 100644 index 0000000..82b23e0 --- /dev/null +++ b/projects/BWM/tests/test_pipeline_cli.py @@ -0,0 +1,240 @@ +import importlib.util +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +PIPELINE_PATH = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "pipeline_w_opt.py" +) +SCENARIO_PATH = "projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml" + + +def _run_pipeline(*arguments): + source = PIPELINE_PATH.read_text(encoding="utf-8") + assert "--validate-config" in source, "validation CLI has not been implemented" + return subprocess.run( + [sys.executable, str(PIPELINE_PATH), *arguments], + cwd=WORLDENGINE_ROOT, + capture_output=True, + text=True, + check=False, + ) + + +def _load_pipeline(monkeypatch): + monkeypatch.syspath_prepend(str(PIPELINE_PATH.parent)) + spec = importlib.util.spec_from_file_location("bwm_pipeline", PIPELINE_PATH) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_validate_config_requires_explicit_layered_config(): + result = _run_pipeline("--validate-config") + + assert result.returncode == 2 + assert "--config" in result.stderr + assert "=== Pipeline Started ===" not in result.stdout + assert "Logs will be saved to:" not in result.stdout + + +def test_validate_config_composes_explicit_layered_scenario(): + result = _run_pipeline( + "--config", + SCENARIO_PATH, + "--validate-config", + ) + + assert result.returncode == 0, result.stderr + assert "mode: layered" in result.stdout + assert "scenario_name: navtrain_50pct_ep_1pct" in result.stdout + assert "data_type: navtrain_ep_per1" in result.stdout + assert "num_history_frames: 4" in result.stdout + assert "num_future_frames: 16" in result.stdout + assert "log_names_count:" in result.stdout + assert "tokens_count:" in result.stdout + assert "generation_execution: sequential" in result.stdout + assert "goal_conditional_copy_with_noise: max_attempts=30, max_success=7" in result.stdout + assert "intent_attack_with_goal_selection: max_attempts=20, max_success=3" in result.stdout + assert "save_scenario_description: true" in result.stdout + expected_runtime_paths = { + "checkpoint": "data/alg_engine/ckpts/nuplan.ckpt", + "digitaltwin_data_root": ( + "data/sim_engine/assets/navtrain/assets" + ), + "scenario_builder.data_root": ( + "data/raw/nuplan/dataset/nuplan-v1.1/trainval" + ), + "scenario_builder.map_root": "data/raw/nuplan/dataset/maps", + "scenario_builder.sensor_root": ( + "data/raw/nuplan/dataset/nuplan-v1.1/sensor_blobs" + ), + } + for key, relative_path in expected_runtime_paths.items(): + assert f"{key}: {WORLDENGINE_ROOT / relative_path}" in result.stdout + assert "runtime_unset: none" in result.stdout + assert "=== Pipeline Started ===" not in result.stdout + assert "Logs will be saved to:" not in result.stdout + + +def test_validate_config_reports_missing_layered_scenario(): + result = _run_pipeline( + "--config", + "projects/BWM/configs/scenarios/missing.yaml", + "--validate-config", + ) + + assert result.returncode == 2 + assert "Configuration error: Scenario config does not exist:" in result.stderr + assert "=== Pipeline Started ===" not in result.stdout + + +def test_layered_run_rejects_missing_runtime_path_before_side_effects(tmp_path): + missing_checkpoint = tmp_path / "missing.ckpt" + scene_filter_path = ( + WORLDENGINE_ROOT + / "projects" + / "AlgEngine" + / "configs" + / "navsim_splits" + / "navtrain_split" + / "e2e_vadv2_50pct_rare" + / "navtrain_50pct_ep_1pct.yaml" + ) + scenario_path = tmp_path / "missing-runtime.yaml" + scenario_path.write_text( + "\n".join( + [ + "scenario_name: missing_runtime", + "data_type: navtrain_ep_per1", + f"scene_filter_path: {scene_filter_path}", + f"checkpoint: {missing_checkpoint}", + ] + ), + encoding="utf-8", + ) + + result = _run_pipeline("--config", str(scenario_path)) + + assert result.returncode == 2 + assert ( + f"checkpoint={missing_checkpoint}" + in result.stderr + ) + assert "=== Pipeline Started ===" not in result.stdout + assert "Logs will be saved to:" not in result.stdout + + +@pytest.mark.filterwarnings("ignore::pyparsing.PyparsingDeprecationWarning") +def test_main_dispatches_layered_digitaltwin_root(monkeypatch): + pipeline = _load_pipeline(monkeypatch) + layered_root = "/worldengine/data/layered-assets" + layered_cfg = pipeline.OmegaConf.merge( + pipeline.OmegaConf.load(WORLDENGINE_ROOT / "projects/BWM/configs/default.yaml"), + { + "data_type": "navtrain_ep_per1", + "digitaltwin_data_root": layered_root, + "log_dir": "/unused", + "task_type": "layered-test", + } + ) + loaded_by_source = { + "scenario.yaml": SimpleNamespace( + config=layered_cfg, + mode="layered", + source=Path("scenario.yaml"), + ), + } + model = object() + feature_builder = object() + processed_roots = [] + + monkeypatch.setattr( + pipeline, + "load_entrypoint_config", + lambda source: loaded_by_source[source], + ) + monkeypatch.setattr(pipeline, "validate_runtime_paths", lambda cfg: None) + monkeypatch.setattr( + pipeline, + "setup_logging", + lambda log_dir, log_filename: "/tmp/bwm-test.log", + ) + monkeypatch.setattr( + pipeline, + "setup_model_and_feature_builder", + lambda cfg: (model, feature_builder), + ) + + def record_processing(cfg, actual_model, actual_feature_builder, root): + assert actual_model is model + assert actual_feature_builder is feature_builder + processed_roots.append(root) + + monkeypatch.setattr( + pipeline, + "process_database_based_approach", + record_processing, + ) + + assert pipeline.main(["--config", "scenario.yaml"]) == 0 + assert processed_roots == [layered_root] + + +@pytest.mark.filterwarnings("ignore::pyparsing.PyparsingDeprecationWarning") +def test_setup_model_uses_inference_checkpoint_loader(monkeypatch): + pipeline = _load_pipeline(monkeypatch) + loaded = [] + + class FakeModel: + def load_state_dict(self, state_dict, strict): + loaded.append((state_dict, strict)) + + def get_list_of_required_feature(self): + return ["feature-builder"] + + model = FakeModel() + source_state = {"model.weight": object()} + monkeypatch.setattr( + pipeline, + "build_torch_module_wrapper", + lambda cfg: model, + ) + monkeypatch.setattr( + pipeline, + "load_inference_state_dict", + lambda path, map_location: source_state, + raising=False, + ) + monkeypatch.setattr( + pipeline.torch.cuda, + "is_available", + lambda: False, + ) + cfg = pipeline.OmegaConf.create( + { + "model": {}, + "checkpoint": "/tmp/model.ckpt", + } + ) + + actual_model, feature_builder = ( + pipeline.setup_model_and_feature_builder(cfg) + ) + + assert actual_model is model + assert feature_builder == "feature-builder" + assert loaded == [ + ({"weight": source_state["model.weight"]}, True) + ] diff --git a/projects/BWM/tests/test_publisher.py b/projects/BWM/tests/test_publisher.py new file mode 100644 index 0000000..3c35552 --- /dev/null +++ b/projects/BWM/tests/test_publisher.py @@ -0,0 +1,212 @@ +import importlib.util +import pickle +import sys +from pathlib import Path + +import pytest + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +PUBLISHER_PATH = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "publish_scenarios.py" +) + + +def _load_publisher(): + assert PUBLISHER_PATH.is_file(), "BWM publisher has not been implemented" + spec = importlib.util.spec_from_file_location("bwm_publisher", PUBLISHER_PATH) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _scenario(scenario_id): + return { + "id": scenario_id, + "name": scenario_id, + "token": f"{scenario_id}-token", + "dataset": "bwm.nuplan", + "map": "sg-one-north", + "log_length": 20, + "sample_rate": 10, + "base_timestamp": 123, + "metadata": {}, + "cameras": {}, + "lidar": {}, + "object_track": {}, + "sdc_id": "ego", + "map_features": {}, + "dynamic_map_states": {}, + } + + +def _write_source(staging, source_name, scenarios): + source_dir = staging / source_name + source_dir.mkdir(parents=True) + source_path = source_dir / f"{source_name}.pkl" + with source_path.open("wb") as stream: + pickle.dump(scenarios, stream, protocol=pickle.HIGHEST_PROTOCOL) + return source_path + + +def test_discovers_only_sorted_canonical_source_pickles(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source_b = _write_source(staging, "b", {"b": _scenario("b")}) + source_a = _write_source(staging, "a", {"a": _scenario("a")}) + (staging / "loose.pkl").write_bytes(b"ignored") + (staging / "a" / "other.pkl").write_bytes(b"ignored") + nested = staging / "nested" / "c" + nested.mkdir(parents=True) + (nested / "c.pkl").write_bytes(b"ignored") + + discovered = publisher.discover_source_files(staging) + + assert discovered == [source_a, source_b] + + +def test_merges_multiple_valid_sources_deterministically(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source_b = _write_source(staging, "b", {"b": _scenario("b")}) + source_a = _write_source(staging, "a", {"a": _scenario("a")}) + + merged = publisher.merge_source_files([source_a, source_b]) + + assert list(merged) == ["a", "b"] + assert merged["a"]["token"] == "a-token" + assert merged["b"]["token"] == "b-token" + + +def test_rejects_missing_canonical_sources(tmp_path): + publisher = _load_publisher() + + with pytest.raises(publisher.PublicationError, match="No canonical"): + publisher.merge_source_files([]) + + +def test_reports_corrupt_source_pickle(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source_dir = staging / "broken" + source_dir.mkdir(parents=True) + source_path = source_dir / "broken.pkl" + source_path.write_bytes(b"not a pickle") + + with pytest.raises( + publisher.PublicationError, + match=r"Unable to load.*broken\.pkl", + ): + publisher.merge_source_files([source_path]) + + +@pytest.mark.parametrize( + ("payload", "message"), + [ + ([], "must contain a mapping"), + ({}, "must not be empty"), + ], +) +def test_rejects_invalid_top_level_values(tmp_path, payload, message): + publisher = _load_publisher() + staging = tmp_path / "staging" + source = _write_source(staging, "invalid", payload) + + with pytest.raises(publisher.PublicationError, match=message): + publisher.merge_source_files([source]) + + +def test_rejects_non_string_scenario_id(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source = _write_source(staging, "invalid", {1: _scenario("one")}) + + with pytest.raises( + publisher.PublicationError, + match="non-empty string scenario ID", + ): + publisher.merge_source_files([source]) + + +def test_rejects_non_mapping_scenario(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source = _write_source(staging, "invalid", {"sample": []}) + + with pytest.raises( + publisher.PublicationError, + match="scenario 'sample' must be a mapping", + ): + publisher.merge_source_files([source]) + + +def test_rejects_missing_required_scenario_field(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + scenario = _scenario("sample") + del scenario["dynamic_map_states"] + source = _write_source(staging, "invalid", {"sample": scenario}) + + with pytest.raises( + publisher.PublicationError, + match="missing required fields: dynamic_map_states", + ): + publisher.merge_source_files([source]) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("id", "different"), + ("name", "different"), + ], +) +def test_rejects_key_identity_mismatch(tmp_path, field, value): + publisher = _load_publisher() + staging = tmp_path / "staging" + scenario = _scenario("sample") + scenario[field] = value + source = _write_source(staging, "invalid", {"sample": scenario}) + + with pytest.raises( + publisher.PublicationError, + match=rf"scenario 'sample'.*{field}.*top-level key", + ): + publisher.merge_source_files([source]) + + +@pytest.mark.parametrize("token", ["", None, 123]) +def test_rejects_invalid_scenario_token(tmp_path, token): + publisher = _load_publisher() + staging = tmp_path / "staging" + scenario = _scenario("sample") + scenario["token"] = token + source = _write_source(staging, "invalid", {"sample": scenario}) + + with pytest.raises( + publisher.PublicationError, + match="token must be a non-empty string", + ): + publisher.merge_source_files([source]) + + +def test_rejects_duplicate_ids_and_names_both_sources(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source_a = _write_source(staging, "a", {"duplicate": _scenario("duplicate")}) + source_b = _write_source(staging, "b", {"duplicate": _scenario("duplicate")}) + + with pytest.raises(publisher.PublicationError) as error: + publisher.merge_source_files([source_a, source_b]) + + message = str(error.value) + assert "Duplicate scenario ID 'duplicate'" in message + assert str(source_a) in message + assert str(source_b) in message diff --git a/projects/BWM/tests/test_publisher_atomic.py b/projects/BWM/tests/test_publisher_atomic.py new file mode 100644 index 0000000..9da35c2 --- /dev/null +++ b/projects/BWM/tests/test_publisher_atomic.py @@ -0,0 +1,213 @@ +import importlib.util +import pickle +import sys +from pathlib import Path + +import pytest + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +PUBLISHER_PATH = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "publish_scenarios.py" +) + + +def _load_publisher(): + spec = importlib.util.spec_from_file_location( + "bwm_atomic_publisher", + PUBLISHER_PATH, + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _scenario(scenario_id): + return { + "id": scenario_id, + "name": scenario_id, + "token": f"{scenario_id}-token", + "dataset": "bwm.nuplan", + "map": "sg-one-north", + "log_length": 20, + "sample_rate": 10, + "base_timestamp": 123, + "metadata": {}, + "cameras": {}, + "lidar": {}, + "object_track": {}, + "sdc_id": "ego", + "map_features": {}, + "dynamic_map_states": {}, + } + + +def _write_source(staging, source_name, scenarios): + source_dir = staging / source_name + source_dir.mkdir(parents=True) + source_path = source_dir / f"{source_name}.pkl" + with source_path.open("wb") as stream: + pickle.dump(scenarios, stream, protocol=pickle.HIGHEST_PROTOCOL) + return source_path + + +def _temporary_publication_files(destination): + return list(destination.parent.glob(f".{destination.name}.*.tmp")) + + +def test_publishes_exact_simengine_pickle_contract(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source_b = _write_source(staging, "b", {"b": _scenario("b")}) + source_a = _write_source(staging, "a", {"a": _scenario("a")}) + publish_root = tmp_path / "augmented" + + result = publisher.publish_scenarios( + staging, + publish_root, + "sample", + ) + + destination = publish_root / "sample" / "all_scenarios.pkl" + assert result.destination == destination + assert result.source_files == (source_a, source_b) + assert result.source_count == 2 + assert result.scenario_count == 2 + assert result.replaced is False + with destination.open("rb") as stream: + assert pickle.load(stream) == { + "a": _scenario("a"), + "b": _scenario("b"), + } + assert _temporary_publication_files(destination) == [] + + +def test_refuses_existing_destination_by_default(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + _write_source(staging, "new", {"new": _scenario("new")}) + publish_root = tmp_path / "augmented" + destination = publish_root / "sample" / "all_scenarios.pkl" + destination.parent.mkdir(parents=True) + destination.write_bytes(b"existing") + + with pytest.raises(publisher.PublicationError, match="already exists"): + publisher.publish_scenarios(staging, publish_root, "sample") + + assert destination.read_bytes() == b"existing" + assert _temporary_publication_files(destination) == [] + + +def test_explicit_overwrite_replaces_existing_destination(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + _write_source(staging, "new", {"new": _scenario("new")}) + publish_root = tmp_path / "augmented" + destination = publish_root / "sample" / "all_scenarios.pkl" + destination.parent.mkdir(parents=True) + destination.write_bytes(b"existing") + + result = publisher.publish_scenarios( + staging, + publish_root, + "sample", + overwrite=True, + ) + + assert result.replaced is True + with destination.open("rb") as stream: + assert pickle.load(stream) == {"new": _scenario("new")} + assert _temporary_publication_files(destination) == [] + + +def test_invalid_replacement_preserves_existing_destination(tmp_path): + publisher = _load_publisher() + staging = tmp_path / "staging" + source_dir = staging / "broken" + source_dir.mkdir(parents=True) + (source_dir / "broken.pkl").write_bytes(b"not a pickle") + publish_root = tmp_path / "augmented" + destination = publish_root / "sample" / "all_scenarios.pkl" + destination.parent.mkdir(parents=True) + destination.write_bytes(b"existing") + + with pytest.raises(publisher.PublicationError, match="Unable to load"): + publisher.publish_scenarios( + staging, + publish_root, + "sample", + overwrite=True, + ) + + assert destination.read_bytes() == b"existing" + assert _temporary_publication_files(destination) == [] + + +def test_write_failure_removes_temporary_file(tmp_path, monkeypatch): + publisher = _load_publisher() + staging = tmp_path / "staging" + _write_source(staging, "new", {"new": _scenario("new")}) + publish_root = tmp_path / "augmented" + destination = publish_root / "sample" / "all_scenarios.pkl" + + def fail_after_partial_write(value, stream, protocol): + stream.write(b"partial") + raise OSError("disk full") + + monkeypatch.setattr(publisher.pickle, "dump", fail_after_partial_write) + + with pytest.raises(publisher.PublicationError, match="Unable to publish"): + publisher.publish_scenarios(staging, publish_root, "sample") + + assert not destination.exists() + assert _temporary_publication_files(destination) == [] + + +def test_no_clobber_commit_preserves_concurrent_destination(tmp_path, monkeypatch): + publisher = _load_publisher() + staging = tmp_path / "staging" + _write_source(staging, "new", {"new": _scenario("new")}) + publish_root = tmp_path / "augmented" + destination = publish_root / "sample" / "all_scenarios.pkl" + competing_value = {"other": _scenario("other")} + + def install_competing_destination(source, target): + with Path(target).open("wb") as stream: + pickle.dump(competing_value, stream) + raise FileExistsError(target) + + monkeypatch.setattr(publisher.os, "link", install_competing_destination) + + with pytest.raises(publisher.PublicationError, match="already exists"): + publisher.publish_scenarios(staging, publish_root, "sample") + + with destination.open("rb") as stream: + assert pickle.load(stream) == competing_value + assert _temporary_publication_files(destination) == [] + + +@pytest.mark.parametrize( + "scenario_name", + ["", ".", "..", "nested/name", r"nested\name"], +) +def test_rejects_unsafe_scenario_name(tmp_path, scenario_name): + publisher = _load_publisher() + staging = tmp_path / "staging" + _write_source(staging, "new", {"new": _scenario("new")}) + + with pytest.raises( + publisher.PublicationError, + match="safe path component", + ): + publisher.publish_scenarios( + staging, + tmp_path / "augmented", + scenario_name, + ) diff --git a/projects/BWM/tests/test_publisher_cli.py b/projects/BWM/tests/test_publisher_cli.py new file mode 100644 index 0000000..d328a0b --- /dev/null +++ b/projects/BWM/tests/test_publisher_cli.py @@ -0,0 +1,117 @@ +import pickle +import subprocess +import sys +from pathlib import Path + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] +PUBLISHER_PATH = ( + WORLDENGINE_ROOT + / "projects" + / "BWM" + / "scripts" + / "generation_general" + / "publish_scenarios.py" +) + + +def _scenario(scenario_id): + return { + "id": scenario_id, + "name": scenario_id, + "token": f"{scenario_id}-token", + "dataset": "bwm.nuplan", + "map": "sg-one-north", + "log_length": 20, + "sample_rate": 10, + "base_timestamp": 123, + "metadata": {}, + "cameras": {}, + "lidar": {}, + "object_track": {}, + "sdc_id": "ego", + "map_features": {}, + "dynamic_map_states": {}, + } + + +def _build_fixture(tmp_path): + staging = tmp_path / "staging" + source_dir = staging / "source" + source_dir.mkdir(parents=True) + with (source_dir / "source.pkl").open("wb") as stream: + pickle.dump({"sample": _scenario("sample")}, stream) + + scene_filter = tmp_path / "scene-filter.yaml" + scene_filter.write_text("tokens:\n - token-a\n", encoding="utf-8") + publish_root = tmp_path / "augmented" + config = tmp_path / "scenario.yaml" + config.write_text( + "\n".join( + [ + "scenario_name: sample", + "data_type: navtrain_ep_per1", + f"scene_filter_path: {scene_filter}", + f"output_dir: {staging}", + f"publish_root: {publish_root}", + ] + ), + encoding="utf-8", + ) + return config, staging, publish_root + + +def _run_publisher(tmp_path, config, *extra_arguments): + return subprocess.run( + [ + sys.executable, + str(PUBLISHER_PATH), + "--config", + str(config), + *extra_arguments, + ], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + + +def test_cli_publishes_layered_config_from_any_working_directory(tmp_path): + config, staging, publish_root = _build_fixture(tmp_path) + + result = _run_publisher(tmp_path, config) + + destination = publish_root / "sample" / "all_scenarios.pkl" + assert result.returncode == 0, result.stderr + assert f"staging: {staging}" in result.stdout + assert f"destination: {destination}" in result.stdout + assert "source_files: 1" in result.stdout + assert "scenarios: 1" in result.stdout + assert "replaced: no" in result.stdout + with destination.open("rb") as stream: + assert pickle.load(stream) == {"sample": _scenario("sample")} + + +def test_cli_requires_explicit_overwrite(tmp_path): + config, _, publish_root = _build_fixture(tmp_path) + destination = publish_root / "sample" / "all_scenarios.pkl" + + first = _run_publisher(tmp_path, config) + refused = _run_publisher(tmp_path, config) + replaced = _run_publisher(tmp_path, config, "--overwrite") + + assert first.returncode == 0, first.stderr + assert refused.returncode == 2 + assert "Publication error:" in refused.stderr + assert "already exists" in refused.stderr + assert replaced.returncode == 0, replaced.stderr + assert "replaced: yes" in replaced.stdout + assert destination.is_file() + + +def test_cli_reports_missing_scenario_config(tmp_path): + result = _run_publisher(tmp_path, tmp_path / "missing.yaml") + + assert result.returncode == 2 + assert "Configuration error:" in result.stderr diff --git a/projects/BWM/tests/test_scene_selection.py b/projects/BWM/tests/test_scene_selection.py new file mode 100644 index 0000000..485c6a8 --- /dev/null +++ b/projects/BWM/tests/test_scene_selection.py @@ -0,0 +1,125 @@ +"""Exercise scene membership through the database generation entry point.""" + +import importlib +from pathlib import Path +from types import SimpleNamespace + +import pytest +from omegaconf import OmegaConf + + +@pytest.fixture +def pipeline(monkeypatch): + root = Path(__file__).resolve().parents[3] + monkeypatch.syspath_prepend(str(root / "projects/BWM")) + monkeypatch.syspath_prepend(str(root / "projects/BWM/scripts/generation_general")) + return importlib.import_module("pipeline_w_opt") + + +@pytest.fixture +def generation(pipeline, monkeypatch, tmp_path): + assets = tmp_path / "assets" + assets.mkdir() + for name in ("log-a-ta", "log-a-tc", "log-b-tb"): + folder = assets / name + folder.mkdir() + (folder / "video_scene_dict.pkl").touch() + # An asset folder without its source metadata must never reach generation. + (assets / "log-a-missing").mkdir() + (assets / "README.txt").touch() + loaded, generated, saved = [], [], [] + + def load_features(builder, log, token, *args, **kwargs): + loaded.append((log, token)) + return (log, token) + + def generate(wrapper, *args, **kwargs): + generated.append(wrapper) + return {"generated": {}} + + monkeypatch.setattr(pipeline, "NuPlanDB", lambda **kwargs: SimpleNamespace( + log=SimpleNamespace(map_version="test-map"))) + monkeypatch.setattr(pipeline, "get_maps_api", lambda *args: object()) + monkeypatch.setattr(pipeline, "get_features_from_db", load_features) + monkeypatch.setattr(pipeline, "generate_valid_scenarios", generate) + monkeypatch.setattr(pipeline, "save_scenario_description", + lambda scene, output, prefix: saved.append(prefix)) + return SimpleNamespace(assets=assets, loaded=loaded, generated=generated, saved=saved) + + +def make_config(tmp_path, selection, source): + defaults = Path(__file__).resolve().parents[1] / "configs/default.yaml" + cfg = OmegaConf.merge(OmegaConf.load(defaults), { + "scenario_builder": {"data_root": "unused", "map_root": "unused"}, + "openscene_data_root": "unused", "output_dir": str(tmp_path / "outputs"), + "num_history_frames": 4, "num_future_frames": 16, + "world_engine_compatible": True, + }) + if source == "file": + path = tmp_path / "filter.yaml" + OmegaConf.save(OmegaConf.create(selection), path) + cfg.scene_filter_path = str(path) + # The referenced SceneFilter remains the source of membership rules. + cfg.log_names = ["stale-log"] + cfg.tokens = ["stale-token"] + else: + cfg = OmegaConf.merge(cfg, selection) + return cfg + + +@pytest.mark.parametrize("source", ["file", "direct"]) +@pytest.mark.parametrize( + "selection, expected", + [ + ({"log_names": ["log-a"], "tokens": ["ta", "tb"]}, {("log-a", "ta")}), + ({"log_names": ["log-b", "log-a"], "tokens": ["ta"]}, {("log-a", "ta")}), + ({"log_names": ["log-a"]}, {("log-a", "ta"), ("log-a", "tc")}), + ({"tokens": ["tb", "tc"]}, {("log-b", "tb"), ("log-a", "tc")}), + ({"log_names": None, "tokens": ["tb"]}, {("log-b", "tb")}), + ({"log_names": ["log-a"], "tokens": None}, {("log-a", "ta"), ("log-a", "tc")}), + ({"tokens": []}, set()), + ({"log_names": []}, set()), + ({"log_names": ["log-a"], "tokens": []}, set()), + ({"log_names": [], "tokens": ["ta"]}, set()), + ({"log_names": [], "tokens": []}, set()), + ({"tokens": ["missing", "unknown"]}, set()), + ], + ids=["intersection", "independent_lists", "logs_only", "tokens_only", "null_logs", + "null_tokens", "empty_tokens", "empty_logs", "logs_with_empty_tokens", + "tokens_with_empty_logs", "both_empty", "unavailable_assets"], +) +def test_only_selected_available_scenes_reach_generation( + pipeline, generation, tmp_path, source, selection, expected, +): + cfg = make_config(tmp_path, selection, source) + pipeline.process_database_based_approach(cfg, None, None, str(generation.assets)) + assert set(generation.loaded) == expected + assert generation.generated == generation.loaded + assert set(generation.saved) == {f"{log}-{token}" for log, token in expected} + + +@pytest.mark.parametrize("source", ["file", "direct"]) +@pytest.mark.parametrize("selection", [{}, {"log_names": None, "tokens": None}]) +def test_missing_selection_cannot_expand_to_all_assets(pipeline, generation, tmp_path, source, selection): + cfg = make_config(tmp_path, selection, source) + with pytest.raises(pipeline.ConfigError, match="SceneFilter must define log_names or tokens"): + pipeline.process_database_based_approach(cfg, None, None, str(generation.assets)) + assert generation.loaded == generation.generated == generation.saved == [] + + +def test_existing_canonical_output_is_still_skipped(pipeline, generation, tmp_path): + cfg = make_config(tmp_path, {"log_names": ["log-a"]}, "file") + existing = Path(cfg.output_dir) / "log-a-ta" / "log-a-ta.pkl" + existing.parent.mkdir(parents=True) + existing.touch() + pipeline.process_database_based_approach(cfg, None, None, str(generation.assets)) + assert generation.generated == [("log-a", "tc")] + + +def test_scene_identity_preserves_both_log_and_token(pipeline, generation, tmp_path): + duplicate_token = generation.assets / "log-b-ta" + duplicate_token.mkdir() + (duplicate_token / "video_scene_dict.pkl").touch() + cfg = make_config(tmp_path, {"tokens": ["ta"]}, "file") + pipeline.process_database_based_approach(cfg, None, None, str(generation.assets)) + assert set(generation.generated) == {("log-a", "ta"), ("log-b", "ta")} diff --git a/projects/BWM/tests/test_simengine_contract.py b/projects/BWM/tests/test_simengine_contract.py new file mode 100644 index 0000000..fb8cb89 --- /dev/null +++ b/projects/BWM/tests/test_simengine_contract.py @@ -0,0 +1,214 @@ +"""Exercise BWM conversion against the existing SimEngine consumers on CPU.""" + +import copy +import importlib +import pickle +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import geopandas as gpd +import pytest +from pyquaternion import Quaternion +from shapely.geometry import box, shape + + +WORLDENGINE_ROOT = Path(__file__).resolve().parents[3] + + +@pytest.fixture +def modules(monkeypatch): + for relative_path in ( + "projects/BWM", + "projects/BWM/scripts/generation_general", + "projects/SimEngine", + ): + monkeypatch.syspath_prepend(str(WORLDENGINE_ROOT / relative_path)) + return SimpleNamespace( + loader=importlib.import_module("data_loaders.database_loader"), + converter=importlib.import_module("processors.data_converter"), + features=importlib.import_module( + "nuplan_extent.planning.training.preprocessing.features.scene_tensor" + ), + metrics=importlib.import_module("post_processor.eval_metric.description_converter"), + baseline=importlib.import_module("worldengine.utils.dataset_utils.nuplan.nuplan_utils"), + engine=importlib.import_module("worldengine.engine.base_engine"), + renderer=importlib.import_module("worldengine.manager.render_manager"), + vehicle=importlib.import_module("worldengine.components.agents.vehicle_model.vehicle_utils"), + parameters=importlib.import_module("worldengine.components.agents.vehicle_model.pacifica_vehicle"), + ) + + +@pytest.fixture(params=[0.0, np.pi / 2, -2.0], ids=["east", "north", "southwest"]) +def converted_scene(request, modules, monkeypatch, tmp_path): + log_name = "example-log" + tokens = [f"token{i}" for i in range(21)] + pcs = {} + for i, token in enumerate(tokens): + quaternion = Quaternion(axis=[0, 0, 1], angle=request.param + i * 0.015) + pose = SimpleNamespace( + x=100.0 + i * 2.0, y=200.0 + i * 0.5, + quaternion=quaternion, + qw=quaternion.w, qx=quaternion.x, qy=quaternion.y, qz=quaternion.z, + vx=4.0, vy=1.0, acceleration_x=0.0, acceleration_y=0.0, + timestamp=1_000_000 + i * 500_000, + ) + agent = SimpleNamespace( + category=SimpleNamespace(name="vehicle"), track_token="other-car", + x=pose.x + 12.0, y=pose.y + 4.0, yaw=0.0, + vx=4.0, vy=1.0, length=4.5, width=2.0, height=1.5, + ) + pcs[token] = SimpleNamespace( + ego_pose=pose, timestamp=pose.timestamp, lidar_boxes=[agent], + ) + database = SimpleNamespace( + lidar_pc=SimpleNamespace(get=lambda token: pcs[token]), + map_name="sg-one-north", log=SimpleNamespace(cameras=[]), + ) + drivable_geometry = box(80, 180, 180, 240) + map_api = SimpleNamespace( + get_proximal_map_objects=lambda *args: {}, + _get_vector_map_layer=lambda layer: gpd.GeoDataFrame(geometry=[drivable_geometry]), + ) + map_polyline = np.array([[90.0, 200.0], [150.0, 210.0]]) + monkeypatch.setattr(modules.loader, "NuPlanDB", lambda **kwargs: database) + monkeypatch.setattr(modules.loader, "GPKGMapsDB", lambda **kwargs: None) + monkeypatch.setattr(modules.loader, "get_maps_api", lambda *args: map_api) + monkeypatch.setattr(modules.converter, "NuPlanDB", lambda **kwargs: database) + monkeypatch.setattr(modules.converter, "extract_traffic_light", lambda **kwargs: {}) + monkeypatch.setattr( + modules.converter, "extract_map_features", + lambda **kwargs: {"road": { + "type": "LANE_SURFACE_STREET", + "polyline": map_polyline - kwargs["initial_ego_center"], + }}, + ) + + (tmp_path / f"{log_name}.db").touch() + metadata_dir = tmp_path / "meta_datas/trainval" + metadata_dir.mkdir(parents=True) + with (metadata_dir / f"{log_name}.pkl").open("wb") as stream: + pickle.dump([{"token": token, "lidar_path": f"lidar/{token}.pcd"} + for token in tokens], stream) + asset_dir = tmp_path / f"{log_name}-{tokens[4]}" + asset_dir.mkdir() + with (asset_dir / "video_scene_dict.pkl").open("wb") as stream: + pickle.dump({"video": {"frame_infos": [ + {"ego2global": np.eye(4)} for _ in tokens + ]}}, stream) + builder = SimpleNamespace( + _radius=100.0, _map_features=[], _num_max_agents=[128, 64, 32], + _map_num_max_polylines=128, _map_num_points_polylines=21, + _map_dim_points_polyline=7, + ) + wrapper = modules.loader.get_features_from_db( + builder, log_name, tokens[4], str(tmp_path), str(tmp_path), str(tmp_path), + past_timesteps=4, future_timesteps=16, world_engine_compatible=True, + ) + scene = next(iter(modules.converter.convert_scene_tensor_wrapper_to_scenario_description( + wrapper, map_api, str(tmp_path), str(tmp_path), str(tmp_path), + ).values())) + origin = -scene["metadata"]["old_origin_in_current_coordinate"] + baseline = modules.baseline.parse_ego_vehicle_state_trajectory( + "unused", list(pcs.values()), np.zeros(2), sample_interval=10, + ) + return SimpleNamespace( + wrapper=wrapper, scene=scene, origin=origin, pcs=list(pcs.values()), + rear_positions=np.array([[pc.ego_pose.x, pc.ego_pose.y] for pc in pcs.values()]), + center_positions=np.array([state["position"] for state in baseline]), + other_positions=np.array([[pc.lidar_boxes[0].x, pc.lidar_boxes[0].y] + for pc in pcs.values()]), + map_polyline=map_polyline, + drivable_geometry=drivable_geometry, + ) + + +def test_features_preserve_rear_axle_and_other_agent_positions(modules, converted_scene): + data = converted_scene + decoded = modules.features.decode_scene_tensor(data.wrapper.scene_tensor.tensor) + np.testing.assert_allclose( + decoded[0, :, :2] + data.wrapper.offset, data.rear_positions, rtol=0, atol=1e-5, + ) + np.testing.assert_allclose( + decoded[1, :, :2] + data.wrapper.offset, data.other_positions, rtol=0, atol=1e-5, + ) + + +def test_export_matches_simengine_centers_and_preserves_map_origin(converted_scene): + data = converted_scene + tracks = data.scene["object_track"] + np.testing.assert_allclose( + tracks["ego"]["state"]["position"][:, :2] + data.origin, + data.center_positions, rtol=0, atol=1e-5, + ) + np.testing.assert_allclose( + tracks["other-car"]["state"]["position"][:, :2] + data.origin, + data.other_positions, rtol=0, atol=1e-5, + ) + np.testing.assert_allclose( + data.scene["map_features"]["road"]["polyline"] + data.origin, data.map_polyline, + ) + assert shape(data.scene["metadata"]["drivable_area"]["geometry"]).equals(data.drivable_geometry) + + +def render_frame(modules, data, frame): + state = data.scene["object_track"]["ego"]["state"] + agent = SimpleNamespace( + current_position=state["position"][frame, :2], current_heading=state["heading"][frame], + vehicle=modules.parameters.get_pacifica_parameters(), + policy=SimpleNamespace(is_current_step_valid=True), + ) + agent.rear_vehicle = modules.vehicle.RearVehicle(agent) + engine = SimpleNamespace( + episode_step=frame, + sim_time_interval=modules.engine.BaseEngine.sim_time_interval.fget( + SimpleNamespace(current_scene=data.scene) + ), + managers={"agent_manager": SimpleNamespace(get_dynamic_agents={"ego": agent})}, + ) + manager = SimpleNamespace( + engine=engine, current_scene=data.scene, + base_timestamp=data.scene["base_timestamp"], local2global_translation_xy=data.origin, + renderer=SimpleNamespace(render=lambda state: state), + ) + return modules.renderer.RenderManager.render(manager) + + +def test_renderer_receives_original_rear_axle_positions(modules, converted_scene): + for frame in (0, 4, 20): + rendered = render_frame(modules, converted_scene, frame) + np.testing.assert_allclose( + rendered["agent_state"]["ego"][:2], converted_scene.rear_positions[frame], + rtol=0, atol=1e-5, + ) + + +def test_renderer_timestamps_follow_the_source_2hz_sequence(modules, converted_scene): + for frame in (0, 4, 20): + rendered = render_frame(modules, converted_scene, frame) + assert rendered["timestamp"] == converted_scene.pcs[frame].timestamp + + +def test_metrics_use_the_same_ego_center_for_both_target_agents(modules, converted_scene): + data = converted_scene + for target_token in ("ego", "other-car"): + target, others, _ = modules.metrics.convert_scenario_data_with_agent_token( + data.scene, target_token, + ) + ego = target if target_token == "ego" else next( + track for track in others if track.object_id == "ego" + ) + np.testing.assert_allclose( + ego.positions + data.origin, data.center_positions, rtol=0, atol=1e-5, + ) + + +def test_metrics_convert_explicit_rear_axle_tracks_once(modules, converted_scene): + data = converted_scene + track = copy.deepcopy(data.scene["object_track"]["ego"]) + track["metadata"]["coordinate_system"] = "rear_axle" + track["state"]["position"][:, :2] = data.rear_positions - data.origin + trajectory = modules.metrics.ScenarioDataConverter._convert_ego_trajectory(track) + np.testing.assert_allclose( + trajectory.positions + data.origin, data.center_positions, rtol=0, atol=1e-5, + ) diff --git a/projects/BWM/third_party/CAT/LICENSE.txt b/projects/BWM/third_party/CAT/LICENSE.txt new file mode 100644 index 0000000..c594907 --- /dev/null +++ b/projects/BWM/third_party/CAT/LICENSE.txt @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2020] [MetaDrive Authors] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/projects/BWM/third_party/CAT/advgen/__init__.py b/projects/BWM/third_party/CAT/advgen/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/BWM/third_party/CAT/advgen/utils_scenegen.py b/projects/BWM/third_party/CAT/advgen/utils_scenegen.py new file mode 100644 index 0000000..91d0311 --- /dev/null +++ b/projects/BWM/third_party/CAT/advgen/utils_scenegen.py @@ -0,0 +1,70 @@ +import pickle +import os +# visualization +import numpy as np +from PIL import Image +# from metadrive.policy.replay_policy import ReplayEgoCarPolicy +# from metadrive.envs.scenario_env import ScenarioEnv + +MDMapTypeConvert={'LANE_SURFACE_STREET':1, + 'LANE_SURFACE_UNSTRUCTURE':2, + 'ROAD_LINE_SOLID_SINGLE_WHITE':3, + 'CROSSWALK':4, + 'ROAD_EDGE_SIDEWALK':5, + 'ROAD_LINE_BROKEN_SINGLE_WHITE':6} + +MDAgentTypeConvert={ +'VEHICLE':1, +'PEDESTRIAN':2, +'CYCLIST':3, +'TRAFFIC_BARRIER':4, +'TRAFFIC_CONE':5} + +MDLightTypeConvert={'TRAFFIC_LIGHT_GREEN':0, +'TRAFFIC_LIGHT_RED':1, +'TRAFFIC_LIGHT_UNKNOWN':2} + +def make_GIF(frames, name="demo.gif"): + print("Generate gif...") + imgs = [frame for frame in frames] + imgs = [Image.fromarray(img) for img in imgs] + imgs[0].save(name, save_all=True, append_images=imgs[1:], duration=50, loop=0) +class Scenarios: + def __init__(self,path): + self.path = path + if 'dataset_mapping.pkl' in os.listdir(path): + with open(os.path.join(path, 'dataset_mapping.pkl'), 'rb') as f: + self.mapping = pickle.load(f) + self.mapping=[os.path.join(path,v,k) for k,v in self.mapping.items()] + else: + self.mapping=os.listdir(path) + self.mapping=[os.path.join(path,i) for i in self.mapping] + self.tokens=[i.split('/')[-1].split('_')[-1].split('.')[0] for i in self.mapping] + self.index=0 + def get_env(self,token): + if token not in self.tokens: + return None + idx=self.tokens.index(token) + with open(self.mapping[idx], 'rb') as f: + f=pickle.load(f) + f['metadata']['current_seed']=idx + return self.mapping[idx],f + def __getitem__(self, idx): + with open(self.mapping[idx], 'rb') as f: + f=pickle.load(f) + f['metadata']['current_seed']=idx + return self.mapping[idx],f + def __len__(self): + return len(self.mapping) + def __iter__(self): + return self + def __next__(self): + if self.index >= len(self.mapping): + raise StopIteration + with open(self.mapping[self.index], 'rb') as f: + f=pickle.load(f) + f['metadata']['current_seed']=self.index + self.index+=1 + return self.mapping[self.index-1],f + + diff --git a/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/observation/pdm_observation.py b/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/observation/pdm_observation.py index 0e26177..94df4ca 100644 --- a/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/observation/pdm_observation.py +++ b/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/observation/pdm_observation.py @@ -70,6 +70,9 @@ def __init__( # lazy loaded (during update) self._occupancy_maps: Optional[List[PDMOccupancyMap]] = None self._object_manager: Optional[PDMObjectManager] = None + # Replay objects share the sampling grid of the occupancy maps. None + # denotes constant-velocity prediction from a single observation. + self._tracked_objects_by_sample: Optional[List[Dict[str, TrackedObject]]] = None self._initialized: bool = False @@ -79,13 +82,29 @@ def __getitem__(self, time_idx) -> PDMOccupancyMap: :param time_idx: index for future simulation iterations [10Hz] :return: occupancy map """ + return self._occupancy_maps[self._get_local_idx(time_idx)] + + def _get_local_idx(self, time_idx: int) -> int: + """Resolve the common sampling index for geometry and object state.""" assert self._initialized, "PDMObservation: Has not been updated yet!" assert ( 0 <= time_idx < len(self._global_to_local_idcs) ), f"PDMObservation: index {time_idx} out of range!" - local_idx = self._global_to_local_idcs[time_idx] - return self._occupancy_maps[local_idx] + return self._global_to_local_idcs[time_idx] + + def get_tracked_object(self, time_idx: int, token: str) -> TrackedObject: + """Return the object used to classify contact at the requested sample. + + Replay returns the object from the same frame as ``self[time_idx]``. + Prediction keeps the initial velocity and heading under its constant- + velocity model; callers must use ``self[time_idx][token]`` for position. + Missing replay objects raise KeyError instead of using another frame. + """ + local_idx = self._get_local_idx(time_idx) + if self._tracked_objects_by_sample is not None: + return self._tracked_objects_by_sample[local_idx][token] + return self._unique_objects[token] @property def collided_track_ids(self) -> List[str]: @@ -107,7 +126,8 @@ def red_light_token(self) -> str: @property def unique_objects(self) -> Dict[str, TrackedObject]: """ - Getter for unique tracked objects + Getter for initial/first-seen tracked objects, not time-aligned state. + Use get_tracked_object() to classify contact in a replay sequence. :return: dictionary of tokens, tracked objects """ assert self._initialized, "PDMObservation: Has not been updated yet!" @@ -138,6 +158,12 @@ def update( :param map_api: map object of nuPlan """ + self._initialized = False + self._tracked_objects_by_sample = None + self._global_to_local_idcs = [ + idx // self._observation_sample_res + for idx in range(self._observation_samples + self._observation_sample_res) + ] self._occupancy_maps: List[PDMOccupancyMap] = [] self._object_manager = self._get_object_manager(ego_state, observation) @@ -302,7 +328,9 @@ def update_detections_tracks( By default, it uses the existing `_occupancy_maps_tl` if `_occupancy_maps_tl` is not `None`. Args: - detection_tracks: List of detection tracks. + detection_tracks: Consecutive frames at the trajectory sampling interval, + starting at time index zero. Unlike predicted occupancy maps, these + frames are not subsampled by observation_sample_res. traffic_light_data: Optional traffic light data corresponding to detection tracks. route_lane_dict: Optional mapping of route lanes to lane graph edge objects. compute_traffic_light_data: If 'True', the traffic light data provided in parameter 'traffic_light_data' @@ -319,7 +347,9 @@ def update_detections_tracks( - If `_occupancy_maps_tl` is available, extract traffic light tokens and polygons from it for the current detection track. 3. Append the extracted tokens and polygons (from either source) to the current track's occupancy map. """ + self._initialized = False occupancy_maps = [] + tracked_objects_by_sample = [] occupancy_maps_tl = ( [] if compute_traffic_light_data else self._occupancy_maps_tl ) @@ -327,10 +357,12 @@ def update_detections_tracks( for idx, detection_track in enumerate(detection_tracks): tokens, polygons = [], [] + frame_objects = {} for tracked_object in detection_track.tracked_objects: token, polygon = tracked_object.track_token, tracked_object.box.geometry tokens.append(token) polygons.append(polygon) + frame_objects[token] = tracked_object if token not in unique_objects.keys(): unique_objects[token] = tracked_object @@ -382,6 +414,7 @@ def update_detections_tracks( occupancy_map = PDMOccupancyMap(tokens, polygons) occupancy_maps.append(occupancy_map) + tracked_objects_by_sample.append(frame_objects) # Validate occupancy_maps length if len(occupancy_maps) != self._observation_samples + 1: @@ -394,6 +427,8 @@ def update_detections_tracks( # Update class state self._detections_tracks = detection_tracks self._occupancy_maps: List[PDMOccupancyMap] = occupancy_maps + self._tracked_objects_by_sample = tracked_objects_by_sample + self._global_to_local_idcs = list(range(len(occupancy_maps))) self._occupancy_maps_tl = ( occupancy_maps_tl # Retain or update _occupancy_maps_tl ) diff --git a/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/scoring/pdm_scorer.py b/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/scoring/pdm_scorer.py index 3e09c50..d2c73a1 100644 --- a/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/scoring/pdm_scorer.py +++ b/projects/SimEngine/worldengine/components/agents/policy/pdm_planner/scoring/pdm_scorer.py @@ -371,7 +371,8 @@ def _calculate_no_at_fault_collision(self) -> None: ] ) - tracked_object = self._observation.unique_objects[token] + # Match velocity/heading to the geometry at the contact sample. + tracked_object = self._observation.get_tracked_object(time_idx, token) # classify collision collision_type: CollisionType = get_collision_type( diff --git a/scripts/run_bwm.sh b/scripts/run_bwm.sh new file mode 100755 index 0000000..a482caf --- /dev/null +++ b/scripts/run_bwm.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +WORLDENGINE_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)" +BWM_PIPELINE="${WORLDENGINE_ROOT}/projects/BWM/scripts/generation_general/pipeline_w_opt.py" +BWM_PUBLISHER="${WORLDENGINE_ROOT}/projects/BWM/scripts/generation_general/publish_scenarios.py" + +usage() { + echo "Usage: scripts/run_bwm.sh {validate|generate|publish} [arguments...]" >&2 +} + +command_name="${1:-}" +case "${command_name}" in + validate) + shift + exec python "${BWM_PIPELINE}" --validate-config "$@" + ;; + generate) + shift + exec python "${BWM_PIPELINE}" "$@" + ;; + publish) + shift + exec python "${BWM_PUBLISHER}" "$@" + ;; + *) + usage + exit 2 + ;; +esac