Update nuScenes & Waymo Optimization (#47)
* update can bus * Create LICENSE * update waymo doc * protobuf requirement * just warning * Add warning for proto * update PR template * fix length bug * try sharing nusc * imu heading * fix 161 168 * add badge * fix doc * update doc * format * update cp * update nuscenes interface * update doc * prediction nuscenes * use drivable aread for nuscenes * allow converting prediction * format * fix bug * optimize * clean RAM * delete more * restore to * add only lane * use token * add warning * format * fix bug
This commit is contained in:
2
.github/pull_request_template.md
vendored
2
.github/pull_request_template.md
vendored
@@ -6,4 +6,6 @@
|
|||||||
|
|
||||||
* [ ] I have merged the latest main branch into current branch.
|
* [ ] I have merged the latest main branch into current branch.
|
||||||
* [ ] I have run `bash scripts/format.sh` before merging.
|
* [ ] I have run `bash scripts/format.sh` before merging.
|
||||||
|
* [ ] I updated documentation, if there are related change
|
||||||
|
* [ ] I add tests if there are new functions or bug-fixing
|
||||||
* Please use "squash and merge" mode.
|
* Please use "squash and merge" mode.
|
||||||
|
|||||||
201
LICENSE
Normal file
201
LICENSE
Normal file
@@ -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 [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
# ScenarioNet
|
# ScenarioNet
|
||||||
|
|
||||||
|
[](https://scenarionet.readthedocs.io/en/latest/?badge=latest)
|
||||||
|
[](http://github.com/metadriverse/scenarionet/actions)
|
||||||
|
[](https://github.com/metadriverse/scenarionet/blob/main/LICENSE.txt)
|
||||||
|
|
||||||
**Open-Source Platform for Large-Scale Traffic Scenario Simulation and Modeling**
|
**Open-Source Platform for Large-Scale Traffic Scenario Simulation and Modeling**
|
||||||
|
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -28,18 +28,17 @@ After that, the scenarios will be loaded to MetaDrive simulator for closed-loop
|
|||||||
First of all, please install `MetaDrive <https://github.com/metadriverse/metadrive>`_ and `ScenarioNet <https://github.com/metadriverse/scenarionet>`_ following these steps :ref:`installation`.
|
First of all, please install `MetaDrive <https://github.com/metadriverse/metadrive>`_ and `ScenarioNet <https://github.com/metadriverse/scenarionet>`_ following these steps :ref:`installation`.
|
||||||
|
|
||||||
|
|
||||||
1. Setup Waymo toolkit
|
1. Setup Requirements
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
For any dataset, the first step after installing ScenarioNet is to install the corresponding official toolkit as we need to use it to parse the original data and convert to our internal scenario description. For Waymo data, please install the toolkit via::
|
For any dataset, the first step after installing ScenarioNet is to install the corresponding official toolkit as we need to use it to parse the original data and convert to our internal scenario description.
|
||||||
|
For Waymo data, we already have the parser in ScenarioNet so just install the TensorFlow and Protobuf via::
|
||||||
|
|
||||||
pip install waymo-open-dataset-tf-2-11-0
|
|
||||||
pip install tensorflow==2.11.0
|
pip install tensorflow==2.11.0
|
||||||
|
conda install protobuf==3.20
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
This package is only supported on Linux platform.
|
You may fail to install ``protobuf`` if using ``pip install protobuf==3.20``.
|
||||||
`waymo-open-dataset` may degrade numpy, causing conflicts with `cv2` (`opencv-python`).
|
|
||||||
A workaround is to ``pip install numpy==1.24.2``
|
|
||||||
|
|
||||||
For other datasets like nuPlan and nuScenes, you need to setup `nuplan-devkit <https://github.com/motional/nuplan-devkit>`_ and `nuscenes-devkit <https://github.com/nutonomy/nuscenes-devkit>`_ respectively.
|
For other datasets like nuPlan and nuScenes, you need to setup `nuplan-devkit <https://github.com/motional/nuplan-devkit>`_ and `nuscenes-devkit <https://github.com/nutonomy/nuscenes-devkit>`_ respectively.
|
||||||
Guidance on how to setup these datasets and connect them with ScenarioNet can be found at :ref:`datasets`.
|
Guidance on how to setup these datasets and connect them with ScenarioNet can be found at :ref:`datasets`.
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ First of all, we have to install the ``nuplan-devkit``.
|
|||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
pip install -e .
|
pip install -e .
|
||||||
|
|
||||||
|
# additional requirements
|
||||||
|
pip install pytorch-lightning
|
||||||
|
|
||||||
# 2. or install from PyPI
|
# 2. or install from PyPI
|
||||||
pip install nuplan-devkit
|
pip install nuplan-devkit
|
||||||
|
|
||||||
@@ -51,7 +54,7 @@ Thus please download the following files:
|
|||||||
|
|
||||||
|
|
||||||
We recommend to download the mini split to test and make yourself familiar with the setup process.
|
We recommend to download the mini split to test and make yourself familiar with the setup process.
|
||||||
All downloaded files are ``.tgz`` files and can be uncompressed by ``tar -zxf xyz.tgz``.
|
All downloaded files are ``.zip`` files and can be uncompressed by ``unzip "*.zip"``.
|
||||||
All data should be placed to ``~/nuplan/dataset`` and the folder structure should comply `file hierarchy <https://nuplan-devkit.readthedocs.io/en/latest/dataset_setup.html#filesystem-hierarchy>`_.
|
All data should be placed to ``~/nuplan/dataset`` and the folder structure should comply `file hierarchy <https://nuplan-devkit.readthedocs.io/en/latest/dataset_setup.html#filesystem-hierarchy>`_.
|
||||||
|
|
||||||
.. code-block:: text
|
.. code-block:: text
|
||||||
@@ -85,7 +88,7 @@ All data should be placed to ``~/nuplan/dataset`` and the folder structure shoul
|
|||||||
│ │ ├── 2021.06.09.17.23.18_veh-38_00773_01140.db
|
│ │ ├── 2021.06.09.17.23.18_veh-38_00773_01140.db
|
||||||
│ │ ├── ...
|
│ │ ├── ...
|
||||||
│ │ └── 2021.10.11.08.31.07_veh-50_01750_01948.db
|
│ │ └── 2021.10.11.08.31.07_veh-50_01750_01948.db
|
||||||
│ └── trainval
|
│ └── train_boston
|
||||||
│ ├── 2021.05.12.22.00.38_veh-35_01008_01518.db
|
│ ├── 2021.05.12.22.00.38_veh-35_01008_01518.db
|
||||||
│ ├── 2021.06.09.17.23.18_veh-38_00773_01140.db
|
│ ├── 2021.06.09.17.23.18_veh-38_00773_01140.db
|
||||||
│ ├── ...
|
│ ├── ...
|
||||||
|
|||||||
@@ -60,7 +60,9 @@ Secondly, all files should be organized to the following structure::
|
|||||||
├── maps/
|
├── maps/
|
||||||
| ├──basemap/
|
| ├──basemap/
|
||||||
| ├──prediction/
|
| ├──prediction/
|
||||||
| ├──expansion/
|
| └──expansion/
|
||||||
|
├── can_bus/
|
||||||
|
| ├──scene-1110_meta.json
|
||||||
| └──...
|
| └──...
|
||||||
├── samples/
|
├── samples/
|
||||||
| ├──CAM_BACK
|
| ├──CAM_BACK
|
||||||
@@ -95,9 +97,9 @@ Please try ``nuscenes-devkit/python-sdk/tutorials/nuscenes_tutorial.ipynb`` and
|
|||||||
After setup the raw data, convertors in ScenarioNet can read the raw data, convert scenario format and build the database.
|
After setup the raw data, convertors in ScenarioNet can read the raw data, convert scenario format and build the database.
|
||||||
Here we take converting raw data in ``nuscenes-mini`` as an example::
|
Here we take converting raw data in ``nuscenes-mini`` as an example::
|
||||||
|
|
||||||
python -m scenarionet.convert_nuscenes -d /path/to/your/database --version v1.0-mini --dataroot /nuscens/data/path
|
python -m scenarionet.convert_nuscenes -d /path/to/your/database --split v1.0-mini --dataroot /nuscens/data/path
|
||||||
|
|
||||||
The ``version`` is to determine which split to convert. ``dataroot`` is set to ``/data/sets/nuscenes`` by default,
|
The ``split`` is to determine which split to convert. ``dataroot`` is set to ``/data/sets/nuscenes`` by default,
|
||||||
but you need to specify it if your data is stored in any other directory.
|
but you need to specify it if your data is stored in any other directory.
|
||||||
Now all converted scenarios will be placed at ``/path/to/your/database`` and are ready to be used in your work.
|
Now all converted scenarios will be placed at ``/path/to/your/database`` and are ready to be used in your work.
|
||||||
|
|
||||||
|
|||||||
@@ -113,8 +113,12 @@ Convert nuScenes (Lyft)
|
|||||||
.. code-block:: text
|
.. code-block:: text
|
||||||
|
|
||||||
python -m scenarionet.convert_nuscenes [-h] [--database_path DATABASE_PATH]
|
python -m scenarionet.convert_nuscenes [-h] [--database_path DATABASE_PATH]
|
||||||
[--dataset_name DATASET_NAME] [--version VERSION]
|
[--dataset_name DATASET_NAME]
|
||||||
[--overwrite] [--num_workers NUM_WORKERS]
|
[--split
|
||||||
|
{v1.0-mini,mini_val,v1.0-test,train,train_val,val,mini_train,v1.0-trainval}]
|
||||||
|
[--dataroot DATAROOT] [--map_radius MAP_RADIUS]
|
||||||
|
[--future FUTURE] [--past PAST] [--overwrite]
|
||||||
|
[--num_workers NUM_WORKERS]
|
||||||
|
|
||||||
Build database from nuScenes/Lyft scenarios
|
Build database from nuScenes/Lyft scenarios
|
||||||
|
|
||||||
@@ -124,13 +128,31 @@ Convert nuScenes (Lyft)
|
|||||||
directory, The path to place the data
|
directory, The path to place the data
|
||||||
--dataset_name DATASET_NAME, -n DATASET_NAME
|
--dataset_name DATASET_NAME, -n DATASET_NAME
|
||||||
Dataset name, will be used to generate scenario files
|
Dataset name, will be used to generate scenario files
|
||||||
--version VERSION, -v VERSION
|
--split
|
||||||
version of nuscenes data, scenario of this version
|
{v1.0-mini,mini_val,v1.0-test,train,train_val,val,mini_train,v1.0-trainval}
|
||||||
will be converted
|
Which splits of nuScenes data should be sued. If set
|
||||||
|
to ['v1.0-mini', 'v1.0-trainval', 'v1.0-test'], it
|
||||||
|
will convert the full log into scenarios with 20
|
||||||
|
second episode length. If set to ['mini_train',
|
||||||
|
'mini_val', 'train', 'train_val', 'val'], it will
|
||||||
|
convert segments used for nuScenes prediction
|
||||||
|
challenge to scenarios, resulting in more converted
|
||||||
|
scenarios. Generally, you should choose this parameter
|
||||||
|
from ['v1.0-mini', 'v1.0-trainval', 'v1.0-test'] to
|
||||||
|
get complete scenarios for planning unless you want to
|
||||||
|
use the converted scenario files for prediction task.
|
||||||
|
--dataroot DATAROOT The path of nuscenes data
|
||||||
|
--map_radius MAP_RADIUS The size of map
|
||||||
|
--future FUTURE 6 seconds by default. How many future seconds to
|
||||||
|
predict. Only available if split is chosen from
|
||||||
|
['mini_train', 'mini_val', 'train', 'train_val',
|
||||||
|
'val']
|
||||||
|
--past PAST 2 seconds by default. How many past seconds are used
|
||||||
|
for prediction. Only available if split is chosen from
|
||||||
|
['mini_train', 'mini_val', 'train', 'train_val',
|
||||||
|
'val']
|
||||||
--overwrite If the database_path exists, whether to overwrite it
|
--overwrite If the database_path exists, whether to overwrite it
|
||||||
--num_workers NUM_WORKERS
|
--num_workers NUM_WORKERS
|
||||||
number of workers to use
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
This script converted the recorded nuScenes scenario into our scenario descriptions.
|
This script converted the recorded nuScenes scenario into our scenario descriptions.
|
||||||
@@ -187,7 +209,7 @@ we can aggregate them freely and enlarge the database.
|
|||||||
|
|
||||||
.. code-block:: text
|
.. code-block:: text
|
||||||
|
|
||||||
python -m scenarionet.merge [-h] --database_path DATABASE_PATH --from FROM [FROM ...]
|
python -m scenarionet.merge [-h] --to DATABASE_PATH --from FROM [FROM ...]
|
||||||
[--exist_ok] [--overwrite] [--filter_moving_dist]
|
[--exist_ok] [--overwrite] [--filter_moving_dist]
|
||||||
[--sdc_moving_dist_min SDC_MOVING_DIST_MIN]
|
[--sdc_moving_dist_min SDC_MOVING_DIST_MIN]
|
||||||
|
|
||||||
@@ -196,7 +218,7 @@ we can aggregate them freely and enlarge the database.
|
|||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--database_path DATABASE_PATH, -d DATABASE_PATH
|
--database_path DATABASE_PATH, -d DATABASE_PATH, --to DATABASE_PATH
|
||||||
The name of the new combined database. It will create
|
The name of the new combined database. It will create
|
||||||
a new directory to store dataset_summary.pkl and
|
a new directory to store dataset_summary.pkl and
|
||||||
dataset_mapping.pkl. If exists_ok=True, those two .pkl
|
dataset_mapping.pkl. If exists_ok=True, those two .pkl
|
||||||
|
|||||||
@@ -26,18 +26,17 @@ The dataset includes:
|
|||||||
- Adjusted some road edge boundary height estimates
|
- Adjusted some road edge boundary height estimates
|
||||||
|
|
||||||
|
|
||||||
1. Install Waymo Toolkit
|
1. Install Requirements
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
First of all, we have to install the waymo toolkit and tensorflow::
|
First of all, we have to install tensorflow and Protobuf::
|
||||||
|
|
||||||
pip install waymo-open-dataset-tf-2-11-0
|
|
||||||
pip install tensorflow==2.11.0
|
pip install tensorflow==2.11.0
|
||||||
|
conda install protobuf==3.20
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
This package is only supported on Linux platform.
|
You may fail to install ``protobuf`` if using ``pip install protobuf==3.20``.
|
||||||
`waymo-open-dataset` may degrade numpy, causing conflicts with cv2.
|
|
||||||
A workaround is ``pip install numpy==1.24.2``
|
|
||||||
|
|
||||||
2. Download TFRecord
|
2. Download TFRecord
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|||||||
@@ -115,17 +115,17 @@ def merge_database(
|
|||||||
return summaries, mappings
|
return summaries, mappings
|
||||||
|
|
||||||
|
|
||||||
def copy_database(
|
def copy_database(from_path, to_path, exist_ok=False, overwrite=False, copy_raw_data=False, remove_source=False):
|
||||||
from_path, to_path, exist_ok=False, overwrite=False, copy_raw_data=False, remove_source=False, force_move=False
|
|
||||||
):
|
|
||||||
if not os.path.exists(from_path):
|
if not os.path.exists(from_path):
|
||||||
raise FileNotFoundError("Can not find database: {}".format(from_path))
|
raise FileNotFoundError("Can not find database: {}".format(from_path))
|
||||||
if os.path.exists(to_path):
|
if os.path.exists(to_path):
|
||||||
assert exist_ok, "to_directory already exists. Set exists_ok to allow turning it into a database"
|
assert exist_ok, "to_directory already exists. Set exists_ok to allow turning it into a database"
|
||||||
assert not os.path.samefile(from_path, to_path), "to_directory is the same as from_directory. Abort!"
|
assert not os.path.samefile(from_path, to_path), "to_directory is the same as from_directory. Abort!"
|
||||||
files = os.listdir(from_path)
|
files = os.listdir(from_path)
|
||||||
if not force_move and (ScenarioDescription.DATASET.MAPPING_FILE in files
|
official_file_num = sum(
|
||||||
and ScenarioDescription.DATASET.SUMMARY_FILE in files and len(files) > 2):
|
[ScenarioDescription.DATASET.MAPPING_FILE in files, ScenarioDescription.DATASET.SUMMARY_FILE in files]
|
||||||
|
)
|
||||||
|
if remove_source and len(files) > official_file_num:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"The source database is not allowed to move! "
|
"The source database is not allowed to move! "
|
||||||
"This will break the relationship between this database and other database built on it."
|
"This will break the relationship between this database and other database built on it."
|
||||||
@@ -146,9 +146,16 @@ def copy_database(
|
|||||||
mappings = {key: "./" for key in summaries.keys()}
|
mappings = {key: "./" for key in summaries.keys()}
|
||||||
save_summary_anda_mapping(summary_file, mapping_file, summaries, mappings)
|
save_summary_anda_mapping(summary_file, mapping_file, summaries, mappings)
|
||||||
|
|
||||||
if remove_source and ScenarioDescription.DATASET.MAPPING_FILE in files and \
|
if remove_source:
|
||||||
ScenarioDescription.DATASET.SUMMARY_FILE in files and len(files) == 2:
|
if ScenarioDescription.DATASET.MAPPING_FILE in files and ScenarioDescription.DATASET.SUMMARY_FILE in files \
|
||||||
shutil.rmtree(from_path)
|
and len(files) == 2:
|
||||||
|
shutil.rmtree(from_path)
|
||||||
|
logger.info("Successfully remove: {}".format(from_path))
|
||||||
|
else:
|
||||||
|
logger.info(
|
||||||
|
"Failed to remove: {}, as it might contain scenario files "
|
||||||
|
"or has no summary file or mapping file".format(from_path)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def split_database(
|
def split_database(
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
desc = "Build database from nuScenes/Lyft scenarios"
|
desc = "Build database from nuScenes/Lyft scenarios"
|
||||||
|
|
||||||
if __name__ == '__main__':
|
prediction_split = ["mini_train", "mini_val", "train", "train_val", "val"]
|
||||||
|
scene_split = ["v1.0-mini", "v1.0-trainval", "v1.0-test"]
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
import pkg_resources # for suppress warning
|
import pkg_resources # for suppress warning
|
||||||
import argparse
|
import argparse
|
||||||
import os.path
|
import os.path
|
||||||
|
from functools import partial
|
||||||
from scenarionet import SCENARIONET_DATASET_PATH
|
from scenarionet import SCENARIONET_DATASET_PATH
|
||||||
from scenarionet.converter.nuscenes.utils import convert_nuscenes_scenario, get_nuscenes_scenarios
|
from scenarionet.converter.nuscenes.utils import convert_nuscenes_scenario, get_nuscenes_scenarios, \
|
||||||
|
get_nuscenes_prediction_split
|
||||||
from scenarionet.converter.utils import write_to_directory
|
from scenarionet.converter.utils import write_to_directory
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(description=desc)
|
parser = argparse.ArgumentParser(description=desc)
|
||||||
@@ -19,12 +24,29 @@ if __name__ == '__main__':
|
|||||||
"--dataset_name", "-n", default="nuscenes", help="Dataset name, will be used to generate scenario files"
|
"--dataset_name", "-n", default="nuscenes", help="Dataset name, will be used to generate scenario files"
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--version",
|
"--split",
|
||||||
"-v",
|
default="v1.0-mini",
|
||||||
default='v1.0-mini',
|
choices=scene_split + prediction_split,
|
||||||
help="version of nuscenes data, scenario of this version will be converted "
|
help="Which splits of nuScenes data should be sued. If set to {}, it will convert the full log into scenarios"
|
||||||
|
" with 20 second episode length. If set to {}, it will convert segments used for nuScenes prediction"
|
||||||
|
" challenge to scenarios, resulting in more converted scenarios. Generally, you should choose this "
|
||||||
|
" parameter from {} to get complete scenarios for planning unless you want to use the converted scenario "
|
||||||
|
" files for prediction task.".format(scene_split, prediction_split, scene_split)
|
||||||
)
|
)
|
||||||
parser.add_argument("--dataroot", default="/data/sets/nuscenes", help="The path of nuscenes data")
|
parser.add_argument("--dataroot", default="/data/sets/nuscenes", help="The path of nuscenes data")
|
||||||
|
parser.add_argument("--map_radius", default=500, type=float, help="The size of map")
|
||||||
|
parser.add_argument(
|
||||||
|
"--future",
|
||||||
|
default=6,
|
||||||
|
help="6 seconds by default. How many future seconds to predict. Only "
|
||||||
|
"available if split is chosen from {}".format(prediction_split)
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--past",
|
||||||
|
default=2,
|
||||||
|
help="2 seconds by default. How many past seconds are used for prediction."
|
||||||
|
" Only available if split is chosen from {}".format(prediction_split)
|
||||||
|
)
|
||||||
parser.add_argument("--overwrite", action="store_true", help="If the database_path exists, whether to overwrite it")
|
parser.add_argument("--overwrite", action="store_true", help="If the database_path exists, whether to overwrite it")
|
||||||
parser.add_argument("--num_workers", type=int, default=8, help="number of workers to use")
|
parser.add_argument("--num_workers", type=int, default=8, help="number of workers to use")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
@@ -32,10 +54,14 @@ if __name__ == '__main__':
|
|||||||
overwrite = args.overwrite
|
overwrite = args.overwrite
|
||||||
dataset_name = args.dataset_name
|
dataset_name = args.dataset_name
|
||||||
output_path = args.database_path
|
output_path = args.database_path
|
||||||
version = args.version
|
version = args.split
|
||||||
|
|
||||||
scenarios, nuscs = get_nuscenes_scenarios(args.dataroot, version, args.num_workers)
|
|
||||||
|
|
||||||
|
if version in scene_split:
|
||||||
|
scenarios, nuscs = get_nuscenes_scenarios(args.dataroot, version, args.num_workers)
|
||||||
|
else:
|
||||||
|
scenarios, nuscs = get_nuscenes_prediction_split(
|
||||||
|
args.dataroot, version, args.past, args.future, args.num_workers
|
||||||
|
)
|
||||||
write_to_directory(
|
write_to_directory(
|
||||||
convert_func=convert_nuscenes_scenario,
|
convert_func=convert_nuscenes_scenario,
|
||||||
scenarios=scenarios,
|
scenarios=scenarios,
|
||||||
@@ -45,4 +71,8 @@ if __name__ == '__main__':
|
|||||||
overwrite=overwrite,
|
overwrite=overwrite,
|
||||||
num_workers=args.num_workers,
|
num_workers=args.num_workers,
|
||||||
nuscenes=nuscs,
|
nuscenes=nuscs,
|
||||||
|
past=[args.past for _ in range(args.num_workers)],
|
||||||
|
future=[args.future for _ in range(args.num_workers)],
|
||||||
|
prediction=[version in prediction_split for _ in range(args.num_workers)],
|
||||||
|
map_radius=[args.map_radius for _ in range(args.num_workers)],
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ try:
|
|||||||
|
|
||||||
NUPLAN_PACKAGE_PATH = os.path.dirname(nuplan.__file__)
|
NUPLAN_PACKAGE_PATH = os.path.dirname(nuplan.__file__)
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
logger.warning("Can not import nuplan-devkit: {}".format(e))
|
raise RuntimeError(e)
|
||||||
|
|
||||||
EGO = "ego"
|
EGO = "ego"
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,16 @@ import geopandas as gpd
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from metadrive.scenario import ScenarioDescription as SD
|
from metadrive.scenario import ScenarioDescription as SD
|
||||||
from metadrive.type import MetaDriveType
|
from metadrive.type import MetaDriveType
|
||||||
|
from nuscenes.eval.prediction.splits import get_prediction_challenge_split
|
||||||
from shapely.ops import unary_union
|
from shapely.ops import unary_union
|
||||||
|
|
||||||
from scenarionet.converter.nuscenes.type import ALL_TYPE, HUMAN_TYPE, BICYCLE_TYPE, VEHICLE_TYPE
|
from scenarionet.converter.nuscenes.type import ALL_TYPE, HUMAN_TYPE, BICYCLE_TYPE, VEHICLE_TYPE
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
try:
|
try:
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logging.getLogger('shapely.geos').setLevel(logging.CRITICAL)
|
||||||
from nuscenes import NuScenes
|
from nuscenes import NuScenes
|
||||||
from nuscenes.can_bus.can_bus_api import NuScenesCanBus
|
from nuscenes.can_bus.can_bus_api import NuScenesCanBus
|
||||||
from nuscenes.eval.common.utils import quaternion_yaw
|
from nuscenes.eval.common.utils import quaternion_yaw
|
||||||
@@ -199,11 +203,16 @@ def get_tracks_from_frames(nuscenes: NuScenes, scene_info, frames, num_to_interp
|
|||||||
interpolate_tracks[id]["state"]["position"] = interpolate(
|
interpolate_tracks[id]["state"]["position"] = interpolate(
|
||||||
track["state"]["position"], track["state"]["valid"], new_valid
|
track["state"]["position"], track["state"]["valid"], new_valid
|
||||||
)
|
)
|
||||||
if id == "ego":
|
if id == "ego" and not scene_info.get("prediction", False):
|
||||||
|
assert "prediction" not in scene_info
|
||||||
# We can get it from canbus
|
# We can get it from canbus
|
||||||
canbus = NuScenesCanBus(dataroot=nuscenes.dataroot)
|
try:
|
||||||
imu_pos = np.asarray([state["pos"] for state in canbus.get_messages(scene_info["name"], "pose")[::5]])
|
canbus = NuScenesCanBus(dataroot=nuscenes.dataroot)
|
||||||
interpolate_tracks[id]["state"]["position"][:len(imu_pos)] = imu_pos
|
imu_pos = np.asarray([state["pos"] for state in canbus.get_messages(scene_info["name"], "pose")[::5]])
|
||||||
|
min_len = min(len(imu_pos), new_episode_len)
|
||||||
|
interpolate_tracks[id]["state"]["position"][:min_len] = imu_pos[:min_len]
|
||||||
|
except:
|
||||||
|
logger.info("Fail to get canbus data for {}".format(scene_info["name"]))
|
||||||
|
|
||||||
# velocity
|
# velocity
|
||||||
interpolate_tracks[id]["state"]["velocity"] = interpolate(
|
interpolate_tracks[id]["state"]["velocity"] = interpolate(
|
||||||
@@ -217,7 +226,6 @@ def get_tracks_from_frames(nuscenes: NuScenes, scene_info, frames, num_to_interp
|
|||||||
interpolate_tracks[id]["state"]["velocity"][k - 1] = np.array([0., 0.])
|
interpolate_tracks[id]["state"]["velocity"][k - 1] = np.array([0., 0.])
|
||||||
# speed outlier check
|
# speed outlier check
|
||||||
max_vel = np.max(np.linalg.norm(interpolate_tracks[id]["state"]["velocity"], axis=-1))
|
max_vel = np.max(np.linalg.norm(interpolate_tracks[id]["state"]["velocity"], axis=-1))
|
||||||
assert max_vel < 50, "Abnormal velocity!"
|
|
||||||
if max_vel > 30:
|
if max_vel > 30:
|
||||||
print("\nWARNING: Too large speed for {}: {}".format(id, max_vel))
|
print("\nWARNING: Too large speed for {}: {}".format(id, max_vel))
|
||||||
|
|
||||||
@@ -225,16 +233,21 @@ def get_tracks_from_frames(nuscenes: NuScenes, scene_info, frames, num_to_interp
|
|||||||
# then update position
|
# then update position
|
||||||
new_heading = interpolate_heading(track["state"]["heading"], track["state"]["valid"], new_valid)
|
new_heading = interpolate_heading(track["state"]["heading"], track["state"]["valid"], new_valid)
|
||||||
interpolate_tracks[id]["state"]["heading"] = new_heading
|
interpolate_tracks[id]["state"]["heading"] = new_heading
|
||||||
if id == "ego":
|
if id == "ego" and not scene_info.get("prediction", False):
|
||||||
|
assert "prediction" not in scene_info
|
||||||
# We can get it from canbus
|
# We can get it from canbus
|
||||||
canbus = NuScenesCanBus(dataroot=nuscenes.dataroot)
|
try:
|
||||||
imu_heading = np.asarray(
|
canbus = NuScenesCanBus(dataroot=nuscenes.dataroot)
|
||||||
[
|
imu_heading = np.asarray(
|
||||||
quaternion_yaw(Quaternion(state["orientation"]))
|
[
|
||||||
for state in canbus.get_messages(scene_info["name"], "pose")[::5]
|
quaternion_yaw(Quaternion(state["orientation"]))
|
||||||
]
|
for state in canbus.get_messages(scene_info["name"], "pose")[::5]
|
||||||
)
|
]
|
||||||
interpolate_tracks[id]["state"]["heading"][:len(imu_heading)] = imu_heading
|
)
|
||||||
|
min_len = min(len(imu_heading), new_episode_len)
|
||||||
|
interpolate_tracks[id]["state"]["heading"][:min_len] = imu_heading[:min_len]
|
||||||
|
except:
|
||||||
|
logger.info("Fail to get canbus data for {}".format(scene_info["name"]))
|
||||||
|
|
||||||
for k, v in track["state"].items():
|
for k, v in track["state"].items():
|
||||||
if k in ["valid", "heading", "position", "velocity"]:
|
if k in ["valid", "heading", "position", "velocity"]:
|
||||||
@@ -256,7 +269,7 @@ def get_tracks_from_frames(nuscenes: NuScenes, scene_info, frames, num_to_interp
|
|||||||
return normalized_ret, map_center
|
return normalized_ret, map_center
|
||||||
|
|
||||||
|
|
||||||
def get_map_features(scene_info, nuscenes: NuScenes, map_center, radius=500, points_distance=1):
|
def get_map_features(scene_info, nuscenes: NuScenes, map_center, radius=500, points_distance=1, only_lane=False):
|
||||||
"""
|
"""
|
||||||
Extract map features from nuscenes data. The objects in specified region will be returned. Sampling rate determines
|
Extract map features from nuscenes data. The objects in specified region will be returned. Sampling rate determines
|
||||||
the distance between 2 points when extracting lane center line.
|
the distance between 2 points when extracting lane center line.
|
||||||
@@ -286,49 +299,72 @@ def get_map_features(scene_info, nuscenes: NuScenes, map_center, radius=500, poi
|
|||||||
|
|
||||||
map_objs = map_api.get_records_in_radius(map_center[0], map_center[1], radius, layer_names)
|
map_objs = map_api.get_records_in_radius(map_center[0], map_center[1], radius, layer_names)
|
||||||
|
|
||||||
# build map boundary
|
if not only_lane:
|
||||||
polygons = []
|
# build map boundary
|
||||||
# for id in map_objs["drivable_area"]:
|
polygons = []
|
||||||
# seg_info = map_api.get("drivable_area", id)
|
for id in map_objs["drivable_area"]:
|
||||||
# assert seg_info["token"] == id
|
seg_info = map_api.get("drivable_area", id)
|
||||||
# for polygon_token in seg_info["polygon_tokens"]:
|
assert seg_info["token"] == id
|
||||||
# polygon = map_api.extract_polygon(polygon_token)
|
for polygon_token in seg_info["polygon_tokens"]:
|
||||||
# polygons.append(polygon)
|
polygon = map_api.extract_polygon(polygon_token)
|
||||||
for id in map_objs["road_segment"]:
|
polygons.append(polygon)
|
||||||
seg_info = map_api.get("road_segment", id)
|
# for id in map_objs["road_segment"]:
|
||||||
assert seg_info["token"] == id
|
# seg_info = map_api.get("road_segment", id)
|
||||||
polygon = map_api.extract_polygon(seg_info["polygon_token"])
|
# assert seg_info["token"] == id
|
||||||
polygons.append(polygon)
|
# polygon = map_api.extract_polygon(seg_info["polygon_token"])
|
||||||
for id in map_objs["road_block"]:
|
# polygons.append(polygon)
|
||||||
seg_info = map_api.get("road_block", id)
|
# for id in map_objs["road_block"]:
|
||||||
assert seg_info["token"] == id
|
# seg_info = map_api.get("road_block", id)
|
||||||
polygon = map_api.extract_polygon(seg_info["polygon_token"])
|
# assert seg_info["token"] == id
|
||||||
polygons.append(polygon)
|
# polygon = map_api.extract_polygon(seg_info["polygon_token"])
|
||||||
polygons = [geom if geom.is_valid else geom.buffer(0) for geom in polygons]
|
# polygons.append(polygon)
|
||||||
boundaries = gpd.GeoSeries(unary_union(polygons)).boundary.explode(index_parts=True)
|
polygons = [geom if geom.is_valid else geom.buffer(0) for geom in polygons]
|
||||||
for idx, boundary in enumerate(boundaries[0]):
|
boundaries = gpd.GeoSeries(unary_union(polygons)).boundary.explode(index_parts=True)
|
||||||
block_points = np.array(list(i for i in zip(boundary.coords.xy[0], boundary.coords.xy[1])))
|
for idx, boundary in enumerate(boundaries[0]):
|
||||||
id = "boundary_{}".format(idx)
|
block_points = np.array(list(i for i in zip(boundary.coords.xy[0], boundary.coords.xy[1])))
|
||||||
ret[id] = {
|
id = "boundary_{}".format(idx)
|
||||||
SD.TYPE: MetaDriveType.LINE_SOLID_SINGLE_WHITE,
|
ret[id] = {
|
||||||
SD.POLYLINE: block_points - np.asarray(map_center)[:2]
|
SD.TYPE: MetaDriveType.LINE_SOLID_SINGLE_WHITE,
|
||||||
}
|
SD.POLYLINE: block_points - np.asarray(map_center)[:2]
|
||||||
|
}
|
||||||
|
|
||||||
# broken line
|
# broken line
|
||||||
for id in map_objs["lane_divider"]:
|
for id in map_objs["lane_divider"]:
|
||||||
line_info = map_api.get("lane_divider", id)
|
line_info = map_api.get("lane_divider", id)
|
||||||
assert line_info["token"] == id
|
assert line_info["token"] == id
|
||||||
line = map_api.extract_line(line_info["line_token"]).coords.xy
|
line = map_api.extract_line(line_info["line_token"]).coords.xy
|
||||||
line = np.asarray([[line[0][i], line[1][i]] for i in range(len(line[0]))])
|
line = np.asarray([[line[0][i], line[1][i]] for i in range(len(line[0]))])
|
||||||
ret[id] = {SD.TYPE: MetaDriveType.LINE_BROKEN_SINGLE_WHITE, SD.POLYLINE: line - np.asarray(map_center)[:2]}
|
ret[id] = {SD.TYPE: MetaDriveType.LINE_BROKEN_SINGLE_WHITE, SD.POLYLINE: line - np.asarray(map_center)[:2]}
|
||||||
|
|
||||||
# solid line
|
# solid line
|
||||||
for id in map_objs["road_divider"]:
|
for id in map_objs["road_divider"]:
|
||||||
line_info = map_api.get("road_divider", id)
|
line_info = map_api.get("road_divider", id)
|
||||||
assert line_info["token"] == id
|
assert line_info["token"] == id
|
||||||
line = map_api.extract_line(line_info["line_token"]).coords.xy
|
line = map_api.extract_line(line_info["line_token"]).coords.xy
|
||||||
line = np.asarray([[line[0][i], line[1][i]] for i in range(len(line[0]))])
|
line = np.asarray([[line[0][i], line[1][i]] for i in range(len(line[0]))])
|
||||||
ret[id] = {SD.TYPE: MetaDriveType.LINE_SOLID_SINGLE_YELLOW, SD.POLYLINE: line - np.asarray(map_center)[:2]}
|
ret[id] = {SD.TYPE: MetaDriveType.LINE_SOLID_SINGLE_YELLOW, SD.POLYLINE: line - np.asarray(map_center)[:2]}
|
||||||
|
|
||||||
|
# crosswalk
|
||||||
|
for id in map_objs["ped_crossing"]:
|
||||||
|
info = map_api.get("ped_crossing", id)
|
||||||
|
assert info["token"] == id
|
||||||
|
boundary = map_api.extract_polygon(info["polygon_token"]).exterior.xy
|
||||||
|
boundary_polygon = np.asarray([[boundary[0][i], boundary[1][i]] for i in range(len(boundary[0]))])
|
||||||
|
ret[id] = {
|
||||||
|
SD.TYPE: MetaDriveType.CROSSWALK,
|
||||||
|
SD.POLYGON: boundary_polygon - np.asarray(map_center)[:2],
|
||||||
|
}
|
||||||
|
|
||||||
|
# walkway
|
||||||
|
for id in map_objs["walkway"]:
|
||||||
|
info = map_api.get("walkway", id)
|
||||||
|
assert info["token"] == id
|
||||||
|
boundary = map_api.extract_polygon(info["polygon_token"]).exterior.xy
|
||||||
|
boundary_polygon = np.asarray([[boundary[0][i], boundary[1][i]] for i in range(len(boundary[0]))])
|
||||||
|
ret[id] = {
|
||||||
|
SD.TYPE: MetaDriveType.BOUNDARY_SIDEWALK,
|
||||||
|
SD.POLYGON: boundary_polygon - np.asarray(map_center)[:2],
|
||||||
|
}
|
||||||
|
|
||||||
# normal lane
|
# normal lane
|
||||||
for id in map_objs["lane"]:
|
for id in map_objs["lane"]:
|
||||||
@@ -365,28 +401,6 @@ def get_map_features(scene_info, nuscenes: NuScenes, map_center, radius=500, poi
|
|||||||
SD.EXIT: map_api.get_outgoing_lane_ids(id)
|
SD.EXIT: map_api.get_outgoing_lane_ids(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
# crosswalk
|
|
||||||
for id in map_objs["ped_crossing"]:
|
|
||||||
info = map_api.get("ped_crossing", id)
|
|
||||||
assert info["token"] == id
|
|
||||||
boundary = map_api.extract_polygon(info["polygon_token"]).exterior.xy
|
|
||||||
boundary_polygon = np.asarray([[boundary[0][i], boundary[1][i]] for i in range(len(boundary[0]))])
|
|
||||||
ret[id] = {
|
|
||||||
SD.TYPE: MetaDriveType.CROSSWALK,
|
|
||||||
SD.POLYGON: boundary_polygon - np.asarray(map_center)[:2],
|
|
||||||
}
|
|
||||||
|
|
||||||
# walkway
|
|
||||||
for id in map_objs["walkway"]:
|
|
||||||
info = map_api.get("walkway", id)
|
|
||||||
assert info["token"] == id
|
|
||||||
boundary = map_api.extract_polygon(info["polygon_token"]).exterior.xy
|
|
||||||
boundary_polygon = np.asarray([[boundary[0][i], boundary[1][i]] for i in range(len(boundary[0]))])
|
|
||||||
ret[id] = {
|
|
||||||
SD.TYPE: MetaDriveType.BOUNDARY_SIDEWALK,
|
|
||||||
SD.POLYGON: boundary_polygon - np.asarray(map_center)[:2],
|
|
||||||
}
|
|
||||||
|
|
||||||
# # stop_line
|
# # stop_line
|
||||||
# for id in map_objs["stop_line"]:
|
# for id in map_objs["stop_line"]:
|
||||||
# info = map_api.get("stop_line", id)
|
# info = map_api.get("stop_line", id)
|
||||||
@@ -404,22 +418,41 @@ def get_map_features(scene_info, nuscenes: NuScenes, map_center, radius=500, poi
|
|||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
def convert_nuscenes_scenario(scene, version, nuscenes: NuScenes):
|
def convert_nuscenes_scenario(
|
||||||
|
token, version, nuscenes: NuScenes, map_radius=500, prediction=False, past=2, future=6, only_lane=False
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Data will be interpolated to 0.1s time interval, while the time interval of original key frames are 0.5s.
|
Data will be interpolated to 0.1s time interval, while the time interval of original key frames are 0.5s.
|
||||||
"""
|
"""
|
||||||
scene_token = scene["token"]
|
if prediction:
|
||||||
scenario_log_interval = 0.1
|
past_num = int(past / 0.5)
|
||||||
scene_info = nuscenes.get("scene", scene_token)
|
future_num = int(future / 0.5)
|
||||||
frames = []
|
nusc = nuscenes
|
||||||
current_frame = nuscenes.get("sample", scene_info["first_sample_token"])
|
instance_token, sample_token = token.split("_")
|
||||||
while current_frame["token"] != scene_info["last_sample_token"]:
|
current_sample = last_sample = next_sample = nusc.get("sample", sample_token)
|
||||||
frames.append(parse_frame(current_frame, nuscenes))
|
past_samples = []
|
||||||
current_frame = nuscenes.get("sample", current_frame["next"])
|
future_samples = []
|
||||||
frames.append(parse_frame(current_frame, nuscenes))
|
for _ in range(past_num):
|
||||||
assert current_frame["next"] == ""
|
if last_sample["prev"] == "":
|
||||||
assert len(frames) == scene_info["nbr_samples"], "Number of sample mismatches! "
|
break
|
||||||
|
last_sample = nusc.get("sample", last_sample["prev"])
|
||||||
|
past_samples.append(parse_frame(last_sample, nusc))
|
||||||
|
|
||||||
|
for _ in range(future_num):
|
||||||
|
if next_sample["next"] == "":
|
||||||
|
break
|
||||||
|
next_sample = nusc.get("sample", next_sample["next"])
|
||||||
|
future_samples.append(parse_frame(next_sample, nusc))
|
||||||
|
frames = past_samples[::-1] + [parse_frame(current_sample, nusc)] + future_samples
|
||||||
|
scene_info = copy.copy(nusc.get("scene", current_sample["scene_token"]))
|
||||||
|
scene_info["name"] = scene_info["name"] + "_" + token
|
||||||
|
scene_info["prediction"] = True
|
||||||
|
frames_scene_info = [frames, scene_info]
|
||||||
|
else:
|
||||||
|
frames_scene_info = extract_frames_scene_info(token, nuscenes)
|
||||||
|
|
||||||
|
scenario_log_interval = 0.1
|
||||||
|
frames, scene_info = frames_scene_info
|
||||||
result = SD()
|
result = SD()
|
||||||
result[SD.ID] = scene_info["name"]
|
result[SD.ID] = scene_info["name"]
|
||||||
result[SD.VERSION] = "nuscenes" + version
|
result[SD.VERSION] = "nuscenes" + version
|
||||||
@@ -430,7 +463,7 @@ def convert_nuscenes_scenario(scene, version, nuscenes: NuScenes):
|
|||||||
result[SD.METADATA]["map"] = nuscenes.get("log", scene_info["log_token"])["location"]
|
result[SD.METADATA]["map"] = nuscenes.get("log", scene_info["log_token"])["location"]
|
||||||
result[SD.METADATA]["date"] = nuscenes.get("log", scene_info["log_token"])["date_captured"]
|
result[SD.METADATA]["date"] = nuscenes.get("log", scene_info["log_token"])["date_captured"]
|
||||||
result[SD.METADATA]["coordinate"] = "right-handed"
|
result[SD.METADATA]["coordinate"] = "right-handed"
|
||||||
result[SD.METADATA]["scenario_token"] = scene_token
|
# result[SD.METADATA]["dscenario_token"] = scene_token
|
||||||
result[SD.METADATA][SD.ID] = scene_info["name"]
|
result[SD.METADATA][SD.ID] = scene_info["name"]
|
||||||
result[SD.METADATA]["scenario_id"] = scene_info["name"]
|
result[SD.METADATA]["scenario_id"] = scene_info["name"]
|
||||||
result[SD.METADATA]["sample_rate"] = scenario_log_interval
|
result[SD.METADATA]["sample_rate"] = scenario_log_interval
|
||||||
@@ -443,16 +476,39 @@ def convert_nuscenes_scenario(scene, version, nuscenes: NuScenes):
|
|||||||
result[SD.DYNAMIC_MAP_STATES] = {}
|
result[SD.DYNAMIC_MAP_STATES] = {}
|
||||||
|
|
||||||
# map
|
# map
|
||||||
result[SD.MAP_FEATURES] = get_map_features(scene_info, nuscenes, map_center, 500)
|
result[SD.MAP_FEATURES] = get_map_features(scene_info, nuscenes, map_center, map_radius, only_lane=only_lane)
|
||||||
|
del frames_scene_info
|
||||||
|
del frames
|
||||||
|
del scene_info
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def extract_frames_scene_info(scene, nuscenes):
|
||||||
|
scene_token = scene["token"]
|
||||||
|
scene_info = nuscenes.get("scene", scene_token)
|
||||||
|
frames = []
|
||||||
|
current_frame = nuscenes.get("sample", scene_info["first_sample_token"])
|
||||||
|
while current_frame["token"] != scene_info["last_sample_token"]:
|
||||||
|
frames.append(parse_frame(current_frame, nuscenes))
|
||||||
|
current_frame = nuscenes.get("sample", current_frame["next"])
|
||||||
|
frames.append(parse_frame(current_frame, nuscenes))
|
||||||
|
assert current_frame["next"] == ""
|
||||||
|
assert len(frames) == scene_info["nbr_samples"], "Number of sample mismatches! "
|
||||||
|
return frames, scene_info
|
||||||
|
|
||||||
|
|
||||||
def get_nuscenes_scenarios(dataroot, version, num_workers=2):
|
def get_nuscenes_scenarios(dataroot, version, num_workers=2):
|
||||||
nusc = NuScenes(version=version, dataroot=dataroot)
|
nusc = NuScenes(version=version, dataroot=dataroot)
|
||||||
scenarios = nusc.scene
|
|
||||||
|
|
||||||
def _get_nusc():
|
def _get_nusc():
|
||||||
return NuScenes(version=version, dataroot=dataroot)
|
return NuScenes(version=version, dataroot=dataroot)
|
||||||
|
|
||||||
return scenarios, [_get_nusc() for _ in range(num_workers)]
|
return nusc.scene, [nusc for _ in range(num_workers)]
|
||||||
|
|
||||||
|
|
||||||
|
def get_nuscenes_prediction_split(dataroot, version, past, future, num_workers=2):
|
||||||
|
def _get_nusc():
|
||||||
|
return NuScenes(version="v1.0-mini" if "mini" in version else "v1.0-trainval", dataroot=dataroot)
|
||||||
|
|
||||||
|
nusc = _get_nusc()
|
||||||
|
return get_prediction_challenge_split(version, dataroot=dataroot), [nusc for _ in range(num_workers)]
|
||||||
|
|||||||
@@ -234,6 +234,8 @@ def write_to_directory_single_worker(
|
|||||||
sd_scenario[SD.METADATA][SD.SUMMARY.NUMBER_SUMMARY] = SD.get_number_summary(sd_scenario)
|
sd_scenario[SD.METADATA][SD.SUMMARY.NUMBER_SUMMARY] = SD.get_number_summary(sd_scenario)
|
||||||
|
|
||||||
# update summary/mapping dicy
|
# update summary/mapping dicy
|
||||||
|
if export_file_name in summary:
|
||||||
|
logger.warning("Scenario {} already exists and will be overwritten!".format(export_file_name))
|
||||||
summary[export_file_name] = copy.deepcopy(sd_scenario[SD.METADATA])
|
summary[export_file_name] = copy.deepcopy(sd_scenario[SD.METADATA])
|
||||||
mapping[export_file_name] = "" # in the same dir
|
mapping[export_file_name] = "" # in the same dir
|
||||||
|
|
||||||
|
|||||||
@@ -446,10 +446,7 @@ def preprocess_waymo_scenarios(files, worker_index):
|
|||||||
:param worker_index, the index for the worker
|
:param worker_index, the index for the worker
|
||||||
:return: a list of scenario_pb2
|
:return: a list of scenario_pb2
|
||||||
"""
|
"""
|
||||||
try:
|
from scenarionet.converter.waymo.waymo_protos import scenario_pb2
|
||||||
scenario_pb2
|
|
||||||
except NameError:
|
|
||||||
raise ImportError("Please install waymo_open_dataset package: pip install waymo-open-dataset-tf-2-11-0")
|
|
||||||
|
|
||||||
for file in tqdm.tqdm(files, desc="Process Waymo scenarios for worker {}".format(worker_index)):
|
for file in tqdm.tqdm(files, desc="Process Waymo scenarios for worker {}".format(worker_index)):
|
||||||
file_path = os.path.join(file)
|
file_path = os.path.join(file)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ if __name__ == '__main__':
|
|||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--database_path",
|
"--database_path",
|
||||||
"-d",
|
"-d",
|
||||||
|
"--to",
|
||||||
required=True,
|
required=True,
|
||||||
help="The name of the new combined database. "
|
help="The name of the new combined database. "
|
||||||
"It will create a new directory to store dataset_summary.pkl and dataset_mapping.pkl. "
|
"It will create a new directory to store dataset_summary.pkl and dataset_mapping.pkl. "
|
||||||
|
|||||||
@@ -19,9 +19,16 @@ def test_copy_database():
|
|||||||
# move
|
# move
|
||||||
for k, from_path in enumerate(dataset_paths):
|
for k, from_path in enumerate(dataset_paths):
|
||||||
to = os.path.join(TMP_PATH, str(k))
|
to = os.path.join(TMP_PATH, str(k))
|
||||||
copy_database(from_path, to, force_move=True, exist_ok=True, overwrite=True)
|
copy_database(from_path, to, exist_ok=True, overwrite=True)
|
||||||
moved_path.append(to)
|
moved_path.append(to)
|
||||||
assert os.path.exists(from_path)
|
assert os.path.exists(from_path)
|
||||||
|
success = False
|
||||||
|
try:
|
||||||
|
copy_database(from_path, to, exist_ok=True, overwrite=True, remove_source=True)
|
||||||
|
except RuntimeError:
|
||||||
|
success = True
|
||||||
|
assert success
|
||||||
|
assert os.path.exists(to)
|
||||||
merge_database(output_path, *moved_path, exist_ok=True, overwrite=True, try_generate_missing_file=True)
|
merge_database(output_path, *moved_path, exist_ok=True, overwrite=True, try_generate_missing_file=True)
|
||||||
# verify
|
# verify
|
||||||
summary, sorted_scenarios, mapping = read_dataset_summary(output_path)
|
summary, sorted_scenarios, mapping = read_dataset_summary(output_path)
|
||||||
|
|||||||
@@ -88,7 +88,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"def make_GIF(frames, name=\"demo.gif\"):\n",
|
"def make_GIF(frames, name=\"demo.gif\"):\n",
|
||||||
" print(\"Generate gif...\")\n",
|
" print(\"Generate gif...\")\n",
|
||||||
" imgs = [pygame.surfarray.array3d(frame) for frame in frames]\n",
|
" imgs = [frame for frame in frames]\n",
|
||||||
" imgs = [Image.fromarray(img) for img in imgs]\n",
|
" imgs = [Image.fromarray(img) for img in imgs]\n",
|
||||||
" imgs[0].save(name, save_all=True, append_images=imgs[1:], duration=50, loop=0)"
|
" imgs[0].save(name, save_all=True, append_images=imgs[1:], duration=50, loop=0)"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -82,7 +82,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"def make_GIF(frames, name=\"demo.gif\"):\n",
|
"def make_GIF(frames, name=\"demo.gif\"):\n",
|
||||||
" print(\"Generate gif...\")\n",
|
" print(\"Generate gif...\")\n",
|
||||||
" imgs = [pygame.surfarray.array3d(frame) for frame in frames]\n",
|
" imgs = [frame for frame in frames]\n",
|
||||||
" imgs = [Image.fromarray(img) for img in imgs]\n",
|
" imgs = [Image.fromarray(img) for img in imgs]\n",
|
||||||
" imgs[0].save(name, save_all=True, append_images=imgs[1:], duration=50, loop=0)"
|
" imgs[0].save(name, save_all=True, append_images=imgs[1:], duration=50, loop=0)"
|
||||||
]
|
]
|
||||||
|
|||||||
Reference in New Issue
Block a user