savoji commited on
Commit
0ca84ad
·
verified ·
1 Parent(s): 60d1d1b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/.clang-format +85 -0
  2. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/.flake8 +9 -0
  3. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/.gitignore +21 -0
  4. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/INSTALL.md +157 -0
  5. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/LICENSE +30 -0
  6. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/README.md +183 -0
  7. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/setup.cfg +14 -0
  8. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/setup.py +181 -0
  9. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/advanced_kinematics_solver.cpython-310.pyc +0 -0
  10. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/angle_utils.cpython-310.pyc +0 -0
  11. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/data_utils.cpython-310.pyc +0 -0
  12. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/object_placement.cpython-310.pyc +0 -0
  13. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/object_placement_2.cpython-310.pyc +0 -0
  14. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/observation_wrapper.cpython-310.pyc +0 -0
  15. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/plot_utils.cpython-310.pyc +0 -0
  16. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/pointcloud_sdf.cpython-310.pyc +0 -0
  17. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/pointcloud_utils.cpython-310.pyc +0 -0
  18. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/advanced_kinematics_solver.py +277 -0
  19. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/plot_utils.py +868 -0
  20. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/pointcloud_utils.py +327 -0
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/.clang-format ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ AccessModifierOffset: -1
2
+ AlignAfterOpenBracket: AlwaysBreak
3
+ AlignConsecutiveAssignments: false
4
+ AlignConsecutiveDeclarations: false
5
+ AlignEscapedNewlinesLeft: true
6
+ AlignOperands: false
7
+ AlignTrailingComments: false
8
+ AllowAllParametersOfDeclarationOnNextLine: false
9
+ AllowShortBlocksOnASingleLine: false
10
+ AllowShortCaseLabelsOnASingleLine: false
11
+ AllowShortFunctionsOnASingleLine: Empty
12
+ AllowShortIfStatementsOnASingleLine: false
13
+ AllowShortLoopsOnASingleLine: false
14
+ AlwaysBreakAfterReturnType: None
15
+ AlwaysBreakBeforeMultilineStrings: true
16
+ AlwaysBreakTemplateDeclarations: true
17
+ BinPackArguments: false
18
+ BinPackParameters: false
19
+ BraceWrapping:
20
+ AfterClass: false
21
+ AfterControlStatement: false
22
+ AfterEnum: false
23
+ AfterFunction: false
24
+ AfterNamespace: false
25
+ AfterObjCDeclaration: false
26
+ AfterStruct: false
27
+ AfterUnion: false
28
+ BeforeCatch: false
29
+ BeforeElse: false
30
+ IndentBraces: false
31
+ BreakBeforeBinaryOperators: None
32
+ BreakBeforeBraces: Attach
33
+ BreakBeforeTernaryOperators: true
34
+ BreakConstructorInitializersBeforeComma: false
35
+ BreakAfterJavaFieldAnnotations: false
36
+ BreakStringLiterals: false
37
+ ColumnLimit: 80
38
+ CommentPragmas: '^ IWYU pragma:'
39
+ ConstructorInitializerAllOnOneLineOrOnePerLine: true
40
+ ConstructorInitializerIndentWidth: 4
41
+ ContinuationIndentWidth: 4
42
+ Cpp11BracedListStyle: true
43
+ DerivePointerAlignment: false
44
+ DisableFormat: false
45
+ ForEachMacros: [ FOR_EACH, FOR_EACH_R, FOR_EACH_RANGE, ]
46
+ IncludeCategories:
47
+ - Regex: '^<.*\.h(pp)?>'
48
+ Priority: 1
49
+ - Regex: '^<.*'
50
+ Priority: 2
51
+ - Regex: '.*'
52
+ Priority: 3
53
+ IndentCaseLabels: true
54
+ IndentWidth: 2
55
+ IndentWrappedFunctionNames: false
56
+ KeepEmptyLinesAtTheStartOfBlocks: false
57
+ MacroBlockBegin: ''
58
+ MacroBlockEnd: ''
59
+ MaxEmptyLinesToKeep: 1
60
+ NamespaceIndentation: None
61
+ ObjCBlockIndentWidth: 2
62
+ ObjCSpaceAfterProperty: false
63
+ ObjCSpaceBeforeProtocolList: false
64
+ PenaltyBreakBeforeFirstCallParameter: 1
65
+ PenaltyBreakComment: 300
66
+ PenaltyBreakFirstLessLess: 120
67
+ PenaltyBreakString: 1000
68
+ PenaltyExcessCharacter: 1000000
69
+ PenaltyReturnTypeOnItsOwnLine: 200
70
+ PointerAlignment: Left
71
+ ReflowComments: true
72
+ SortIncludes: true
73
+ SpaceAfterCStyleCast: false
74
+ SpaceBeforeAssignmentOperators: true
75
+ SpaceBeforeParens: ControlStatements
76
+ SpaceInEmptyParentheses: false
77
+ SpacesBeforeTrailingComments: 1
78
+ SpacesInAngles: false
79
+ SpacesInContainerLiterals: true
80
+ SpacesInCStyleCastParentheses: false
81
+ SpacesInParentheses: false
82
+ SpacesInSquareBrackets: false
83
+ Standard: Cpp11
84
+ TabWidth: 8
85
+ UseTab: Never
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/.flake8 ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [flake8]
2
+ # B028 No explicit stacklevel argument found.
3
+ # B907 'foo' is manually surrounded by quotes, consider using the `!r` conversion flag.
4
+ # B905 `zip()` without an explicit `strict=` parameter.
5
+ ignore = E203, E266, E501, W503, E221, B028, B905, B907
6
+ max-line-length = 88
7
+ max-complexity = 18
8
+ select = B,C,E,F,W,T4,B9
9
+ exclude = build,__init__.py
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/.gitignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ build/
2
+ dist/
3
+ *.egg-info/
4
+ **/__pycache__/
5
+ *-checkpoint.ipynb
6
+ **/.ipynb_checkpoints
7
+ **/.ipynb_checkpoints/**
8
+
9
+
10
+ # Docusaurus site
11
+ website/yarn.lock
12
+ website/build/
13
+ website/i18n/
14
+ website/node_modules/*
15
+ website/npm-debug.log
16
+
17
+ ## Generated for tutorials
18
+ website/_tutorials/
19
+ website/static/files/
20
+ website/pages/tutorials/*
21
+ !website/pages/tutorials/index.js
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/INSTALL.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installation
2
+
3
+
4
+ ## Requirements
5
+
6
+ ### Core library
7
+
8
+ The core library is written in PyTorch. Several components have underlying implementation in CUDA for improved performance. A subset of these components have CPU implementations in C++/PyTorch. It is advised to use PyTorch3D with GPU support in order to use all the features.
9
+
10
+ - Linux or macOS or Windows
11
+ - Python
12
+ - PyTorch 2.1.0, 2.1.1, 2.1.2, 2.2.0, 2.2.1, 2.2.2, 2.3.0, 2.3.1, 2.4.0 or 2.4.1.
13
+ - torchvision that matches the PyTorch installation. You can install them together as explained at pytorch.org to make sure of this.
14
+ - gcc & g++ ≥ 4.9
15
+ - [ioPath](https://github.com/facebookresearch/iopath)
16
+ - If CUDA is to be used, use a version which is supported by the corresponding pytorch version and at least version 9.2.
17
+ - If CUDA older than 11.7 is to be used and you are building from source, the CUB library must be available. We recommend version 1.10.0.
18
+
19
+ The runtime dependencies can be installed by running:
20
+ ```
21
+ conda create -n pytorch3d python=3.9
22
+ conda activate pytorch3d
23
+ conda install pytorch=1.13.0 torchvision pytorch-cuda=11.6 -c pytorch -c nvidia
24
+ conda install -c iopath iopath
25
+ ```
26
+
27
+ For the CUB build time dependency, which you only need if you have CUDA older than 11.7, if you are using conda, you can continue with
28
+ ```
29
+ conda install -c bottler nvidiacub
30
+ ```
31
+ Otherwise download the CUB library from https://github.com/NVIDIA/cub/releases and unpack it to a folder of your choice.
32
+ Define the environment variable CUB_HOME before building and point it to the directory that contains `CMakeLists.txt` for CUB.
33
+ For example on Linux/Mac,
34
+ ```
35
+ curl -LO https://github.com/NVIDIA/cub/archive/1.10.0.tar.gz
36
+ tar xzf 1.10.0.tar.gz
37
+ export CUB_HOME=$PWD/cub-1.10.0
38
+ ```
39
+
40
+ ### Tests/Linting and Demos
41
+
42
+ For developing on top of PyTorch3D or contributing, you will need to run the linter and tests. If you want to run any of the notebook tutorials as `docs/tutorials` or the examples in `docs/examples` you will also need matplotlib and OpenCV.
43
+ - scikit-image
44
+ - black
45
+ - usort
46
+ - flake8
47
+ - matplotlib
48
+ - tdqm
49
+ - jupyter
50
+ - imageio
51
+ - fvcore
52
+ - plotly
53
+ - opencv-python
54
+
55
+ These can be installed by running:
56
+ ```
57
+ # Demos and examples
58
+ conda install jupyter
59
+ pip install scikit-image matplotlib imageio plotly opencv-python
60
+
61
+ # Tests/Linting
62
+ conda install -c fvcore -c conda-forge fvcore
63
+ pip install black usort flake8 flake8-bugbear flake8-comprehensions
64
+ ```
65
+
66
+ ## Installing prebuilt binaries for PyTorch3D
67
+ After installing the above dependencies, run one of the following commands:
68
+
69
+ ### 1. Install with CUDA support from Anaconda Cloud, on Linux only
70
+
71
+ ```
72
+ # Anaconda Cloud
73
+ conda install pytorch3d -c pytorch3d
74
+ ```
75
+
76
+ Or, to install a nightly (non-official, alpha) build:
77
+ ```
78
+ # Anaconda Cloud
79
+ conda install pytorch3d -c pytorch3d-nightly
80
+ ```
81
+
82
+ ### 2. Install wheels for Linux
83
+ We have prebuilt wheels with CUDA for Linux for PyTorch 1.11.0, for each of the supported CUDA versions,
84
+ for Python 3.8 and 3.9. This is for ease of use on Google Colab.
85
+ These are installed in a special way.
86
+ For example, to install for Python 3.8, PyTorch 1.11.0 and CUDA 11.3
87
+ ```
88
+ pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/py38_cu113_pyt1110/download.html
89
+ ```
90
+
91
+ In general, from inside IPython, or in Google Colab or a jupyter notebook, you can install with
92
+ ```
93
+ import sys
94
+ import torch
95
+ pyt_version_str=torch.__version__.split("+")[0].replace(".", "")
96
+ version_str="".join([
97
+ f"py3{sys.version_info.minor}_cu",
98
+ torch.version.cuda.replace(".",""),
99
+ f"_pyt{pyt_version_str}"
100
+ ])
101
+ !pip install iopath
102
+ !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html
103
+ ```
104
+
105
+ ## Building / installing from source.
106
+ CUDA support will be included if CUDA is available in pytorch or if the environment variable
107
+ `FORCE_CUDA` is set to `1`.
108
+
109
+ ### 1. Install from GitHub
110
+ ```
111
+ pip install "git+https://github.com/facebookresearch/pytorch3d.git"
112
+ ```
113
+ To install using the code of the released version instead of from the main branch, use the following instead.
114
+ ```
115
+ pip install "git+https://github.com/facebookresearch/pytorch3d.git@stable"
116
+ ```
117
+
118
+ For CUDA builds with versions earlier than CUDA 11, set `CUB_HOME` before building as described above.
119
+
120
+ **Install from Github on macOS:**
121
+ Some environment variables should be provided, like this.
122
+ ```
123
+ MACOSX_DEPLOYMENT_TARGET=10.14 CC=clang CXX=clang++ pip install "git+https://github.com/facebookresearch/pytorch3d.git"
124
+ ```
125
+
126
+ ### 2. Install from a local clone
127
+ ```
128
+ git clone https://github.com/facebookresearch/pytorch3d.git
129
+ cd pytorch3d && pip install -e .
130
+ ```
131
+ To rebuild after installing from a local clone run, `rm -rf build/ **/*.so` then `pip install -e .`. You often need to rebuild pytorch3d after reinstalling PyTorch. For CUDA builds with versions earlier than CUDA 11, set `CUB_HOME` before building as described above.
132
+
133
+ **Install from local clone on macOS:**
134
+ ```
135
+ MACOSX_DEPLOYMENT_TARGET=10.14 CC=clang CXX=clang++ pip install -e .
136
+ ```
137
+
138
+ **Install from local clone on Windows:**
139
+
140
+ Depending on the version of PyTorch, changes to some PyTorch headers may be needed before compilation. These are often discussed in issues in this repository.
141
+
142
+ After any necessary patching, you can go to "x64 Native Tools Command Prompt for VS 2019" to compile and install
143
+ ```
144
+ cd pytorch3d
145
+ python3 setup.py install
146
+ ```
147
+
148
+ After installing, you can run **unit tests**
149
+ ```
150
+ python3 -m unittest discover -v -s tests -t .
151
+ ```
152
+
153
+ # FAQ
154
+
155
+ ### Can I use Docker?
156
+
157
+ We don't provide a docker file but see [#113](https://github.com/facebookresearch/pytorch3d/issues/113) for a docker file shared by a user (NOTE: this has not been tested by the PyTorch3D team).
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/LICENSE ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD License
2
+
3
+ For PyTorch3D software
4
+
5
+ Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without modification,
8
+ are permitted provided that the following conditions are met:
9
+
10
+ * Redistributions of source code must retain the above copyright notice, this
11
+ list of conditions and the following disclaimer.
12
+
13
+ * Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+
17
+ * Neither the name Meta nor the names of its contributors may be used to
18
+ endorse or promote products derived from this software without specific
19
+ prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
22
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
25
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
28
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/README.md ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/pytorch3dlogo.png" width="900"/>
2
+
3
+ [![CircleCI](https://circleci.com/gh/facebookresearch/pytorch3d.svg?style=svg)](https://circleci.com/gh/facebookresearch/pytorch3d)
4
+ [![Anaconda-Server Badge](https://anaconda.org/pytorch3d/pytorch3d/badges/version.svg)](https://anaconda.org/pytorch3d/pytorch3d)
5
+
6
+ # Introduction
7
+
8
+ PyTorch3D provides efficient, reusable components for 3D Computer Vision research with [PyTorch](https://pytorch.org).
9
+
10
+ Key features include:
11
+
12
+ - Data structure for storing and manipulating triangle meshes
13
+ - Efficient operations on triangle meshes (projective transformations, graph convolution, sampling, loss functions)
14
+ - A differentiable mesh renderer
15
+ - Implicitron, see [its README](projects/implicitron_trainer), a framework for new-view synthesis via implicit representations. ([blog post](https://ai.facebook.com/blog/implicitron-a-new-modular-extensible-framework-for-neural-implicit-representations-in-pytorch3d/))
16
+
17
+ PyTorch3D is designed to integrate smoothly with deep learning methods for predicting and manipulating 3D data.
18
+ For this reason, all operators in PyTorch3D:
19
+
20
+ - Are implemented using PyTorch tensors
21
+ - Can handle minibatches of hetereogenous data
22
+ - Can be differentiated
23
+ - Can utilize GPUs for acceleration
24
+
25
+ Within FAIR, PyTorch3D has been used to power research projects such as [Mesh R-CNN](https://arxiv.org/abs/1906.02739).
26
+
27
+ See our [blog post](https://ai.facebook.com/blog/-introducing-pytorch3d-an-open-source-library-for-3d-deep-learning/) to see more demos and learn about PyTorch3D.
28
+
29
+ ## Installation
30
+
31
+ For detailed instructions refer to [INSTALL.md](INSTALL.md).
32
+
33
+ ## License
34
+
35
+ PyTorch3D is released under the [BSD License](LICENSE).
36
+
37
+ ## Tutorials
38
+
39
+ Get started with PyTorch3D by trying one of the tutorial notebooks.
40
+
41
+ |<img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/dolphin_deform.gif" width="310"/>|<img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/bundle_adjust.gif" width="310"/>|
42
+ |:-----------------------------------------------------------------------------------------------------------:|:--------------------------------------------------:|
43
+ | [Deform a sphere mesh to dolphin](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/deform_source_mesh_to_target_mesh.ipynb)| [Bundle adjustment](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/bundle_adjustment.ipynb) |
44
+
45
+ | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/render_textured_mesh.gif" width="310"/> | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/camera_position_teapot.gif" width="310" height="310"/>
46
+ |:------------------------------------------------------------:|:--------------------------------------------------:|
47
+ | [Render textured meshes](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/render_textured_meshes.ipynb)| [Camera position optimization](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/camera_position_optimization_with_differentiable_rendering.ipynb)|
48
+
49
+ | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/pointcloud_render.png" width="310"/> | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/cow_deform.gif" width="310" height="310"/>
50
+ |:------------------------------------------------------------:|:--------------------------------------------------:|
51
+ | [Render textured pointclouds](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/render_colored_points.ipynb)| [Fit a mesh with texture](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/fit_textured_mesh.ipynb)|
52
+
53
+ | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/densepose_render.png" width="310"/> | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/shapenet_render.png" width="310" height="310"/>
54
+ |:------------------------------------------------------------:|:--------------------------------------------------:|
55
+ | [Render DensePose data](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/render_densepose.ipynb)| [Load & Render ShapeNet data](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/dataloaders_ShapeNetCore_R2N2.ipynb)|
56
+
57
+ | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/fit_textured_volume.gif" width="310"/> | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/fit_nerf.gif" width="310" height="310"/>
58
+ |:------------------------------------------------------------:|:--------------------------------------------------:|
59
+ | [Fit Textured Volume](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/fit_textured_volume.ipynb)| [Fit A Simple Neural Radiance Field](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/fit_simple_neural_radiance_field.ipynb)|
60
+
61
+ | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/fit_textured_volume.gif" width="310"/> | <img src="https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/.github/implicitron_config.gif" width="310" height="310"/>
62
+ |:------------------------------------------------------------:|:--------------------------------------------------:|
63
+ | [Fit Textured Volume in Implicitron](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/implicitron_volumes.ipynb)| [Implicitron Config System](https://github.com/facebookresearch/pytorch3d/blob/main/docs/tutorials/implicitron_config_system.ipynb)|
64
+
65
+
66
+
67
+
68
+
69
+ ## Documentation
70
+
71
+ Learn more about the API by reading the PyTorch3D [documentation](https://pytorch3d.readthedocs.org/).
72
+
73
+ We also have deep dive notes on several API components:
74
+
75
+ - [Heterogeneous Batching](https://github.com/facebookresearch/pytorch3d/tree/main/docs/notes/batching.md)
76
+ - [Mesh IO](https://github.com/facebookresearch/pytorch3d/tree/main/docs/notes/meshes_io.md)
77
+ - [Differentiable Rendering](https://github.com/facebookresearch/pytorch3d/tree/main/docs/notes/renderer_getting_started.md)
78
+
79
+ ### Overview Video
80
+
81
+ We have created a short (~14 min) video tutorial providing an overview of the PyTorch3D codebase including several code examples. Click on the image below to watch the video on YouTube:
82
+
83
+ <a href="http://www.youtube.com/watch?v=Pph1r-x9nyY"><img src="http://img.youtube.com/vi/Pph1r-x9nyY/0.jpg" height="225" ></a>
84
+
85
+ ## Development
86
+
87
+ We welcome new contributions to PyTorch3D and we will be actively maintaining this library! Please refer to [CONTRIBUTING.md](./.github/CONTRIBUTING.md) for full instructions on how to run the code, tests and linter, and submit your pull requests.
88
+
89
+ ## Development and Compatibility
90
+
91
+ - `main` branch: actively developed, without any guarantee, Anything can be broken at any time
92
+ - REMARK: this includes nightly builds which are built from `main`
93
+ - HINT: the commit history can help locate regressions or changes
94
+ - backward-compatibility between releases: no guarantee. Best efforts to communicate breaking changes and facilitate migration of code or data (incl. models).
95
+
96
+ ## Contributors
97
+
98
+ PyTorch3D is written and maintained by the Facebook AI Research Computer Vision Team.
99
+
100
+ In alphabetical order:
101
+
102
+ * Amitav Baruah
103
+ * Steve Branson
104
+ * Krzysztof Chalupka
105
+ * Jiali Duan
106
+ * Luya Gao
107
+ * Georgia Gkioxari
108
+ * Taylor Gordon
109
+ * Justin Johnson
110
+ * Patrick Labatut
111
+ * Christoph Lassner
112
+ * Wan-Yen Lo
113
+ * David Novotny
114
+ * Nikhila Ravi
115
+ * Jeremy Reizenstein
116
+ * Dave Schnizlein
117
+ * Roman Shapovalov
118
+ * Olivia Wiles
119
+
120
+ ## Citation
121
+
122
+ If you find PyTorch3D useful in your research, please cite our tech report:
123
+
124
+ ```bibtex
125
+ @article{ravi2020pytorch3d,
126
+ author = {Nikhila Ravi and Jeremy Reizenstein and David Novotny and Taylor Gordon
127
+ and Wan-Yen Lo and Justin Johnson and Georgia Gkioxari},
128
+ title = {Accelerating 3D Deep Learning with PyTorch3D},
129
+ journal = {arXiv:2007.08501},
130
+ year = {2020},
131
+ }
132
+ ```
133
+
134
+ If you are using the pulsar backend for sphere-rendering (the `PulsarPointRenderer` or `pytorch3d.renderer.points.pulsar.Renderer`), please cite the tech report:
135
+
136
+ ```bibtex
137
+ @article{lassner2020pulsar,
138
+ author = {Christoph Lassner and Michael Zollh\"ofer},
139
+ title = {Pulsar: Efficient Sphere-based Neural Rendering},
140
+ journal = {arXiv:2004.07484},
141
+ year = {2020},
142
+ }
143
+ ```
144
+
145
+ ## News
146
+
147
+ Please see below for a timeline of the codebase updates in reverse chronological order. We are sharing updates on the releases as well as research projects which are built with PyTorch3D. The changelogs for the releases are available under [`Releases`](https://github.com/facebookresearch/pytorch3d/releases), and the builds can be installed using `conda` as per the instructions in [INSTALL.md](INSTALL.md).
148
+
149
+ **[Oct 31st 2023]:** PyTorch3D [v0.7.5](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.7.5) released.
150
+
151
+ **[May 10th 2023]:** PyTorch3D [v0.7.4](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.7.4) released.
152
+
153
+ **[Apr 5th 2023]:** PyTorch3D [v0.7.3](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.7.3) released.
154
+
155
+ **[Dec 19th 2022]:** PyTorch3D [v0.7.2](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.7.2) released.
156
+
157
+ **[Oct 23rd 2022]:** PyTorch3D [v0.7.1](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.7.1) released.
158
+
159
+ **[Aug 10th 2022]:** PyTorch3D [v0.7.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.7.0) released with Implicitron and MeshRasterizerOpenGL.
160
+
161
+ **[Apr 28th 2022]:** PyTorch3D [v0.6.2](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.6.2) released
162
+
163
+ **[Dec 16th 2021]:** PyTorch3D [v0.6.1](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.6.1) released
164
+
165
+ **[Oct 6th 2021]:** PyTorch3D [v0.6.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.6.0) released
166
+
167
+ **[Aug 5th 2021]:** PyTorch3D [v0.5.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.5.0) released
168
+
169
+ **[Feb 9th 2021]:** PyTorch3D [v0.4.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.4.0) released with support for implicit functions, volume rendering and a [reimplementation of NeRF](https://github.com/facebookresearch/pytorch3d/tree/main/projects/nerf).
170
+
171
+ **[November 2nd 2020]:** PyTorch3D [v0.3.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.3.0) released, integrating the pulsar backend.
172
+
173
+ **[Aug 28th 2020]:** PyTorch3D [v0.2.5](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.2.5) released
174
+
175
+ **[July 17th 2020]:** PyTorch3D tech report published on ArXiv: https://arxiv.org/abs/2007.08501
176
+
177
+ **[April 24th 2020]:** PyTorch3D [v0.2.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.2.0) released
178
+
179
+ **[March 25th 2020]:** [SynSin](https://arxiv.org/abs/1912.08804) codebase released using PyTorch3D: https://github.com/facebookresearch/synsin
180
+
181
+ **[March 8th 2020]:** PyTorch3D [v0.1.1](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.1.1) bug fix release
182
+
183
+ **[Jan 23rd 2020]:** PyTorch3D [v0.1.0](https://github.com/facebookresearch/pytorch3d/releases/tag/v0.1.0) released. [Mesh R-CNN](https://arxiv.org/abs/1906.02739) codebase released: https://github.com/facebookresearch/meshrcnn
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/setup.cfg ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ [isort]
8
+ line_length = 88
9
+ multi_line_output = 3
10
+ include_trailing_comma = True
11
+ force_grid_warp = 0
12
+ default_section = THIRDPARTY
13
+ lines_after_imports = 2
14
+ combine_as_imports = True
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/setup.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import glob
9
+ import os
10
+ import runpy
11
+ import sys
12
+ import warnings
13
+ from typing import List, Optional
14
+
15
+ import torch
16
+ from setuptools import find_packages, setup
17
+ from torch.utils.cpp_extension import CppExtension, CUDA_HOME, CUDAExtension
18
+
19
+
20
+ def get_existing_ccbin(nvcc_args: List[str]) -> Optional[str]:
21
+ """
22
+ Given a list of nvcc arguments, return the compiler if specified.
23
+
24
+ Note from CUDA doc: Single value options and list options must have
25
+ arguments, which must follow the name of the option itself by either
26
+ one of more spaces or an equals character.
27
+ """
28
+ last_arg = None
29
+ for arg in reversed(nvcc_args):
30
+ if arg == "-ccbin":
31
+ return last_arg
32
+ if arg.startswith("-ccbin="):
33
+ return arg[7:]
34
+ last_arg = arg
35
+ return None
36
+
37
+
38
+ def get_extensions():
39
+ no_extension = os.getenv("PYTORCH3D_NO_EXTENSION", "0") == "1"
40
+ if no_extension:
41
+ msg = "SKIPPING EXTENSION BUILD. PYTORCH3D WILL NOT WORK!"
42
+ print(msg, file=sys.stderr)
43
+ warnings.warn(msg)
44
+ return []
45
+
46
+ this_dir = os.path.dirname(os.path.abspath(__file__))
47
+ extensions_dir = os.path.join(this_dir, "pytorch3d", "csrc")
48
+ sources = glob.glob(os.path.join(extensions_dir, "**", "*.cpp"), recursive=True)
49
+ source_cuda = glob.glob(os.path.join(extensions_dir, "**", "*.cu"), recursive=True)
50
+ extension = CppExtension
51
+
52
+ extra_compile_args = {"cxx": ["-std=c++17"]}
53
+ define_macros = []
54
+ include_dirs = [extensions_dir]
55
+
56
+ force_cuda = os.getenv("FORCE_CUDA", "0") == "1"
57
+ force_no_cuda = os.getenv("PYTORCH3D_FORCE_NO_CUDA", "0") == "1"
58
+ if (
59
+ not force_no_cuda and torch.cuda.is_available() and CUDA_HOME is not None
60
+ ) or force_cuda:
61
+ extension = CUDAExtension
62
+ sources += source_cuda
63
+ define_macros += [("WITH_CUDA", None)]
64
+ # Thrust is only used for its tuple objects.
65
+ # With CUDA 11.0 we can't use the cudatoolkit's version of cub.
66
+ # We take the risk that CUB and Thrust are incompatible, because
67
+ # we aren't using parts of Thrust which actually use CUB.
68
+ define_macros += [("THRUST_IGNORE_CUB_VERSION_CHECK", None)]
69
+ cub_home = os.environ.get("CUB_HOME", None)
70
+ nvcc_args = [
71
+ "-DCUDA_HAS_FP16=1",
72
+ "-D__CUDA_NO_HALF_OPERATORS__",
73
+ "-D__CUDA_NO_HALF_CONVERSIONS__",
74
+ "-D__CUDA_NO_HALF2_OPERATORS__",
75
+ ]
76
+ if os.name != "nt":
77
+ nvcc_args.append("-std=c++17")
78
+ if cub_home is None:
79
+ prefix = os.environ.get("CONDA_PREFIX", None)
80
+ if prefix is not None and os.path.isdir(prefix + "/include/cub"):
81
+ cub_home = prefix + "/include"
82
+
83
+ if cub_home is None:
84
+ warnings.warn(
85
+ "The environment variable `CUB_HOME` was not found. "
86
+ "NVIDIA CUB is required for compilation and can be downloaded "
87
+ "from `https://github.com/NVIDIA/cub/releases`. You can unpack "
88
+ "it to a location of your choice and set the environment variable "
89
+ "`CUB_HOME` to the folder containing the `CMakeListst.txt` file."
90
+ )
91
+ else:
92
+ include_dirs.append(os.path.realpath(cub_home).replace("\\ ", " "))
93
+ nvcc_flags_env = os.getenv("NVCC_FLAGS", "")
94
+ if nvcc_flags_env != "":
95
+ nvcc_args.extend(nvcc_flags_env.split(" "))
96
+
97
+ # This is needed for pytorch 1.6 and earlier. See e.g.
98
+ # https://github.com/facebookresearch/pytorch3d/issues/436
99
+ # It is harmless after https://github.com/pytorch/pytorch/pull/47404 .
100
+ # But it can be problematic in torch 1.7.0 and 1.7.1
101
+ if torch.__version__[:4] != "1.7.":
102
+ CC = os.environ.get("CC", None)
103
+ if CC is not None:
104
+ existing_CC = get_existing_ccbin(nvcc_args)
105
+ if existing_CC is None:
106
+ CC_arg = "-ccbin={}".format(CC)
107
+ nvcc_args.append(CC_arg)
108
+ elif existing_CC != CC:
109
+ msg = f"Inconsistent ccbins: {CC} and {existing_CC}"
110
+ raise ValueError(msg)
111
+
112
+ extra_compile_args["nvcc"] = nvcc_args
113
+
114
+ sources = [os.path.join(extensions_dir, s) for s in sources]
115
+
116
+ ext_modules = [
117
+ extension(
118
+ "pytorch3d._C",
119
+ sources,
120
+ include_dirs=include_dirs,
121
+ define_macros=define_macros,
122
+ extra_compile_args=extra_compile_args,
123
+ )
124
+ ]
125
+
126
+ return ext_modules
127
+
128
+
129
+ # Retrieve __version__ from the package.
130
+ __version__ = runpy.run_path("pytorch3d/__init__.py")["__version__"]
131
+
132
+
133
+ if os.getenv("PYTORCH3D_NO_NINJA", "0") == "1":
134
+
135
+ class BuildExtension(torch.utils.cpp_extension.BuildExtension):
136
+ def __init__(self, *args, **kwargs):
137
+ super().__init__(use_ninja=False, *args, **kwargs)
138
+
139
+ else:
140
+ BuildExtension = torch.utils.cpp_extension.BuildExtension
141
+
142
+ trainer = "pytorch3d.implicitron_trainer"
143
+
144
+ setup(
145
+ name="pytorch3d",
146
+ version=__version__,
147
+ author="FAIR",
148
+ url="https://github.com/facebookresearch/pytorch3d",
149
+ description="PyTorch3D is FAIR's library of reusable components "
150
+ "for deep Learning with 3D data.",
151
+ packages=find_packages(
152
+ exclude=("configs", "tests", "tests.*", "docs.*", "projects.*")
153
+ )
154
+ + [trainer],
155
+ package_dir={trainer: "projects/implicitron_trainer"},
156
+ install_requires=["iopath"],
157
+ extras_require={
158
+ "all": ["matplotlib", "tqdm>4.29.0", "imageio", "ipywidgets"],
159
+ "dev": ["flake8", "usort"],
160
+ "implicitron": [
161
+ "hydra-core>=1.1",
162
+ "visdom",
163
+ "lpips",
164
+ "tqdm>4.29.0",
165
+ "matplotlib",
166
+ "accelerate",
167
+ "sqlalchemy>=2.0",
168
+ ],
169
+ },
170
+ entry_points={
171
+ "console_scripts": [
172
+ f"pytorch3d_implicitron_runner={trainer}.experiment:experiment",
173
+ f"pytorch3d_implicitron_visualizer={trainer}.visualize_reconstruction:main",
174
+ ]
175
+ },
176
+ ext_modules=get_extensions(),
177
+ cmdclass={"build_ext": BuildExtension},
178
+ package_data={
179
+ "": ["*.json"],
180
+ },
181
+ )
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/advanced_kinematics_solver.cpython-310.pyc ADDED
Binary file (9.33 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/angle_utils.cpython-310.pyc ADDED
Binary file (8.59 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/data_utils.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/object_placement.cpython-310.pyc ADDED
Binary file (2.86 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/object_placement_2.cpython-310.pyc ADDED
Binary file (3.04 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/observation_wrapper.cpython-310.pyc ADDED
Binary file (6.89 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/plot_utils.cpython-310.pyc ADDED
Binary file (21.7 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/pointcloud_sdf.cpython-310.pyc ADDED
Binary file (4.98 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/__pycache__/pointcloud_utils.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/advanced_kinematics_solver.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, List, Sequence
3
+ import numpy as np
4
+ import sapien.core as sapien
5
+ import warnings
6
+ # from sapien import Articulation #for maniskill 2 only
7
+ from mani_skill.utils.structs.articulation import Articulation #for maniskill 3 only
8
+
9
+ @dataclass
10
+ class CollisionSphere:
11
+ """Represents a collision sphere on a robot link."""
12
+ link_name: str
13
+ local_pose: sapien.Pose
14
+ radius: float
15
+ class AdvancedKinematicsSolver:
16
+ """A wrapper class that extends basic kinematics to handle arbitrary points on robot links.
17
+ This class provides methods to:
18
+ 1. Calculate kinematics for arbitrary points on links (not just link centers)
19
+ 2. Compute Jacobians for these points
20
+ """
21
+ # def __init__(self, robot: sapien.Articulation) -> None:
22
+ def __init__(self, robot: Articulation) -> None:
23
+ self.robot = robot #be careful, when environment been reconfigured, this will become a null pointer...
24
+ self._collision_spheres: Dict[str, List[CollisionSphere]] = {}
25
+ self._link_name_to_id_map: Dict[str, int] = {}
26
+ self._kinematics_model = self.robot.create_pinocchio_model()
27
+
28
+ joint_names = [x.name for x in self.robot.get_active_joints()]
29
+ print("active joint names:", joint_names)
30
+ self.joint_indices = self.get_active_joint_indices(
31
+ self.robot, joint_names)
32
+
33
+ self.qmask = np.zeros(self.robot.dof, dtype=bool)
34
+ self.qmask[self.joint_indices] = 1
35
+
36
+ # Initialize spheres and link id map
37
+ self._initialize_collision_spheres()
38
+ self._initialize_link_id_map()
39
+ # Store base transform for correction
40
+ self._base_transform = None
41
+ self._initialize_base_transform()
42
+
43
+ print("link name to id map:", self._link_name_to_id_map)
44
+ self.ee_link_idx = self._link_name_to_id_map["panda_hand"]
45
+
46
+ def get_active_joint_indices(self,
47
+ articulation: Articulation, joint_names: Sequence[str]
48
+ ) -> List[int]:
49
+ all_joint_names = [x.name for x in articulation.get_active_joints()]
50
+ joint_indices = [all_joint_names.index(x) for x in joint_names]
51
+ return joint_indices
52
+
53
+ def _initialize_collision_spheres(self) -> None:
54
+ """Initialize collision spheres from the robot model."""
55
+ for link in self.robot.get_links():
56
+ link_name = link.get_name()
57
+ if link_name == "panda_hand_tcp":
58
+ continue
59
+ self._collision_spheres[link_name] = []
60
+ print("link type:", type(link))
61
+ for collision in link.get_collision_shapes():
62
+ # geometry = collision.geometry
63
+ if isinstance(collision, sapien.pysapien.physx.PhysxCollisionShapeSphere ):
64
+ radius = collision.get_radius()
65
+ local_pose = collision.get_local_pose()
66
+ self._collision_spheres[link_name].append(CollisionSphere(
67
+ link_name, local_pose, radius))
68
+
69
+ def _initialize_base_transform(self) -> None:
70
+ """Initialize the base transform correction between Pinocchio and SAPIEN."""
71
+ # Get the base link pose from both systems
72
+ base_link = self.robot.get_links()[0] # panda_link0
73
+ sapien_pose = base_link.pose
74
+
75
+ # The base transform should align Pinocchio's panda_link0 with SAPIEN's panda_link0
76
+ # We need to:
77
+ # 1. Move the base link to the origin
78
+ # 2. Align the rotation with SAPIEN's base frame
79
+ self._base_transform = sapien.Pose(
80
+ p=np.array([0.0, 0.0, 0]), # Move base link to origin
81
+ q=np.array([1.0, 0.0, 0.0, 0.0]) # Identity rotation
82
+ )
83
+
84
+ def _initialize_link_id_map(self) -> None:
85
+ """Initialize mapping between link names and their IDs."""
86
+ # Use the actual link IDs from the robot
87
+ for link in self.robot.get_links(): # THIS ID IS NOT FROM PINOCCHIO, IT IS FROM SAPIEN
88
+ link_name = link.get_name()
89
+ if link_name == "panda_hand_tcp":
90
+ continue
91
+ # Get the actual link ID from the robot
92
+ link_index = link.get_index() #get index in cpp library
93
+ self._link_name_to_id_map[link_name] = link_index
94
+ print(f"Mapping {link_name} to ID {link_index}") # Debug print
95
+
96
+ def calculate_forward_kinematics(self, qpos: np.ndarray) -> None:
97
+ """Calculate forward kinematics for the robot, reseult will be cached in self._kinematics_model"""
98
+ """cpp library check link: https://github.com/haosulab/SAPIEN/blob/ab1d9a9fa1428484a918e61185ae9df2beb7cb30/include/sapien/articulation/pinocchio_model.h"""
99
+ self._kinematics_model.compute_forward_kinematics(qpos)
100
+
101
+ def calculate_full_jacobian(self, qpos: np.ndarray) -> None:
102
+ """Calculate full jacobian for the robot, result will be cached in self._kinematics_model"""
103
+ """cpp library is same as calculate_forward_kinematics"""
104
+ """pybinding link: https://github.com/haosulab/SAPIEN/blob/ab1d9a9fa1428484a918e61185ae9df2beb7cb30/python/py_package/core/pysapien/__init__.pyi#L105 """
105
+ self._kinematics_model.compute_full_jacobian(qpos)
106
+
107
+ def compute_ik(self, target_pose, initial_qpos, max_iterations=100):
108
+ # if initial_qpos is not None:
109
+ # initial_qpos = np.array(initial_qpos)
110
+ # else:
111
+ # initial_qpos = self.get_qpos()
112
+ # print("initial qpos: ", self.articulation.get_qpos())
113
+ # print("initial qpos type: ", type(self.articulation.get_qpos()))
114
+ # Assume the target pose is defined in the base frame
115
+ if isinstance(target_pose, np.ndarray):
116
+ if target_pose.shape == (7,): # [x, y, z, qw, qx, qy, qz]
117
+ target_pose = sapien.Pose(p=target_pose[:3], q=target_pose[3:])
118
+ else:
119
+ raise ValueError(f"target_pose numpy shape should be (7,), got {target_pose.shape}")
120
+ elif not isinstance(target_pose, sapien.Pose):
121
+ raise TypeError("target_pose must be either numpy.ndarray or sapien.Pose")
122
+
123
+ result, success, error = self._kinematics_model.compute_inverse_kinematics(
124
+ self.ee_link_idx,
125
+ target_pose,
126
+ initial_qpos=initial_qpos,
127
+ active_qmask=self.qmask,
128
+ max_iterations=max_iterations,
129
+ )
130
+ if success:
131
+ return result[self.joint_indices]
132
+ else:
133
+ return None
134
+
135
+ def calculate_all_sphere_poses(self, qpos: np.ndarray = None) -> Dict[str, List[np.ndarray]]:
136
+ """Get all sphere poses for all links"""
137
+ if qpos is not None:
138
+ self.calculate_forward_kinematics(qpos)
139
+ else:
140
+ warnings.warn("qpos is not provided, using last qpos in kinematics solver", UserWarning)
141
+ # 1. get all link poses
142
+ link_poses = self.get_all_link_pose()
143
+ # 2. get all sphere poses based on the link poses and local transform
144
+ sphere_poses: Dict[str, List[sapien.Pose]] = {} # link name, list of sphere poses
145
+ for link_name, spheres in self._collision_spheres.items():
146
+ link_pose = link_poses[link_name]
147
+ sphere_poses[link_name] = []
148
+ for sphere in spheres:
149
+ sphere_pose = link_pose * sphere.local_pose
150
+ sphere_poses[link_name].append(sphere_pose)
151
+ return sphere_poses
152
+
153
+ def calculate_all_sphere_positions_and_radii(self, qpos: np.ndarray = None) -> Dict[str, List[np.ndarray]]:
154
+ """Get all sphere positions and radius for all links"""
155
+ if qpos is not None:
156
+ self.calculate_forward_kinematics(qpos)
157
+ else:
158
+ warnings.warn("qpos is not provided, using last qpos in kinematics solver", UserWarning)
159
+ # 1. get all link poses
160
+ link_poses = self.get_all_link_pose()
161
+ self._link_poses_debug = link_poses
162
+
163
+ # 2. get all sphere poses based on the link poses and local transform
164
+ sphere_poses: Dict[str, List[sapien.Pose]] = {} # link name, list of sphere poses
165
+ sphere_radii: Dict[str, List[float]] = {} # link name, list of sphere radii
166
+ for link_name, spheres in self._collision_spheres.items():
167
+ link_pose = link_poses[link_name]
168
+ sphere_poses[link_name] = []
169
+ sphere_radii[link_name] = []
170
+ for sphere in spheres:
171
+ sphere_pose = link_pose * sphere.local_pose
172
+ sphere_poses[link_name].append(sphere_pose.p)
173
+ sphere_radii[link_name].append(sphere.radius)
174
+ return sphere_poses, sphere_radii
175
+
176
+ def get_all_link_pose(self) -> Dict[str, sapien.Pose]:
177
+ """Get all link poses for all links with base transform correction."""
178
+ link_poses = {}
179
+ for link_name, link_id in self._link_name_to_id_map.items():
180
+ # Get the raw pose from Pinocchio
181
+ raw_pose = self._kinematics_model.get_link_pose(link_id)
182
+ # Apply the base transform correction
183
+ corrected_pose = self._base_transform * raw_pose
184
+ link_poses[link_name] = corrected_pose
185
+ return link_poses
186
+
187
+ def calculate_all_sphere_jacobian(self, qpos: np.ndarray = None) -> np.ndarray:
188
+ """Calculate jacobian of all spheres for all links"""
189
+ """⚠️ CRITICAL: sphere_poses MUST be generated using the same qpos as this function call to ensure correct Jacobian calculations"""
190
+ if qpos is not None:
191
+ self._kinematics_model.compute_full_jacobian(qpos)
192
+ else:
193
+ warnings.warn("qpos is not provided, using last qpos in kinematics solver", UserWarning)
194
+
195
+ link_poses = self.get_all_link_pose()
196
+
197
+ sphere_jacobians: Dict[str, List[np.ndarray]] = {}
198
+ for link_name, spheres in self._collision_spheres.items():
199
+ link_id = self._link_name_to_id_map[link_name]
200
+ link_jacobian = self._kinematics_model.get_link_jacobian(link_id, local = False)
201
+ sphere_jacobians[link_name] = []
202
+ for sphere in spheres:
203
+ link_pose = link_poses[link_name]
204
+ sphere_jacobian = self._transform_jacobian_to_point(link_jacobian, link_pose, sphere.local_pose)
205
+ sphere_jacobians[link_name].append(sphere_jacobian)
206
+ # print("sphere_jacobian shape: ", sphere_jacobian.shape)
207
+ return sphere_jacobians
208
+
209
+ def _transform_jacobian_to_point(self, link_jacobian: np.ndarray, link_pose: sapien.Pose, local_pose: sapien.Pose) -> np.ndarray:
210
+ """Transform link center Jacobian to a point offset from the link center.
211
+ Args:
212
+ link_jacobian: 6 x n_joints Jacobian at link center
213
+ link_pose: World pose of the link center
214
+ local_pose: Pose of the target point relative to the link center
215
+ Returns:
216
+ 6 x n_joints Jacobian at the offset point
217
+ """
218
+ # Get rotation and translation from local pose
219
+ R = link_pose.to_transformation_matrix()[:3, :3] #rotation of the link origin to world frame
220
+ p_local = local_pose.p #position of the sphere in the link frame
221
+
222
+ # Rotate the offset from local frame to world frame.
223
+ # it is the offset from the link origin to the sphere in the world frame
224
+ p_world = R @ p_local
225
+
226
+ # Create skew-symmetric matrix of the world offset
227
+ p_skew = np.array([
228
+ [0, -p_world[2], p_world[1]],
229
+ [p_world[2], 0, -p_world[0]],
230
+ [-p_world[1], p_world[0], 0]
231
+ ])
232
+
233
+ # Build transformation matrix
234
+ transform = np.block([
235
+ [np.eye(3), np.zeros((3, 3))],
236
+ [-p_skew, np.eye(3)]
237
+ ])
238
+
239
+ return transform @ link_jacobian
240
+
241
+ def print_link_info(self, qpos: np.ndarray = None) -> None:
242
+ """Print detailed information about all links in the robot model."""
243
+ if qpos is not None:
244
+ self.calculate_forward_kinematics(qpos)
245
+
246
+ print("\n=== Robot Link Information ===")
247
+ print("Link ID to Name mapping:")
248
+ for link_name, link_id in self._link_name_to_id_map.items():
249
+ print(f"Link ID {link_id}: {link_name}")
250
+
251
+ print("\nLink Poses (from Pinocchio):")
252
+ for link_name, link_id in self._link_name_to_id_map.items():
253
+ try:
254
+ pose = self._kinematics_model.get_link_pose(link_id)
255
+ print(f"\n{link_name} (ID: {link_id}):")
256
+ print(f" Position: {pose.p}")
257
+ print(f" Quaternion: {pose.q}")
258
+ except RuntimeError as e:
259
+ print(f"\nError getting pose for {link_name} (ID: {link_id}): {e}")
260
+
261
+ print("\nLink Poses (from SAPIEN):")
262
+ for link in self.robot.get_links():
263
+ if link.get_name() == "panda_hand_tcp":
264
+ continue
265
+ pose = link.get_pose()
266
+ print(f"\n{link.get_name()}:")
267
+ print(f" Position: {pose.p}")
268
+ print(f" Quaternion: {pose.q}")
269
+
270
+
271
+
272
+
273
+
274
+
275
+
276
+
277
+
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/plot_utils.py ADDED
@@ -0,0 +1,868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #plot trajectory
2
+ import matplotlib.pyplot as plt
3
+ import matplotlib as mpl
4
+ import numpy as np
5
+ from cfdp.utils.data_utils import transform_ortho6d_to_quat
6
+ from cfdp.utils.angle_utils import quaternion_to_euler
7
+ from typing import Dict, Any, Optional
8
+ import torch
9
+ from typing import Union, List
10
+ from mpl_toolkits.mplot3d import Axes3D
11
+ from mpl_toolkits.mplot3d.art3d import Line3DCollection # Add this import at the top
12
+ import os
13
+ import time
14
+ import math
15
+
16
+ # TODO: should extract more abstract methods from visualizer...
17
+ # such as fixed 3d scene with customized shape API
18
+ class TrajectoryVisualizer:
19
+ def __init__(self, normalizer):
20
+ self.fig = None
21
+ self.ax = None
22
+ self.normalizer = normalizer
23
+ # trajectory normalizer
24
+ self.normalizer = normalizer.normalizers['traj']
25
+
26
+ def unnormalize_numpy(self, x, eps=1e-4):
27
+ '''
28
+ Numpy version of unnormalize function. Performs same operations as torch version.
29
+ Args:
30
+ x: numpy array in range [-1, 1]
31
+ eps: tolerance for clipping check
32
+ Returns:
33
+ unnormalized numpy array
34
+ '''
35
+ if np.max(x) > 1 + eps or np.min(x) < -1 - eps:
36
+ x = np.clip(x, -1, 1)
37
+
38
+ # [ -1, 1 ] --> [ 0, 1 ]
39
+ x = (x + 1) / 2.
40
+
41
+ # Get mins and maxs from normalizer as numpy arrays
42
+ mins = self.normalizer.mins.cpu().numpy()
43
+ maxs = self.normalizer.maxs.cpu().numpy()
44
+
45
+ # Scale to original range
46
+ return x * (maxs - mins) + mins
47
+
48
+ def plot_trajectory(self,
49
+ planned_paths: torch.Tensor,
50
+ obs: Dict[str, Any],
51
+ point_cloud: Optional[np.ndarray] = None,
52
+ simplified_paths: torch.Tensor = None,
53
+ robot_executed_path: Optional[np.ndarray] = None):
54
+ """Plot the planned trajectory in 3D space, colored by rank."""
55
+ if planned_paths is None:
56
+ return
57
+
58
+ self.fig = plt.figure(figsize=(8, 6))
59
+ self.ax = self.fig.add_subplot(111, projection='3d')
60
+
61
+ if planned_paths.dim() == 2:
62
+ planned_paths = planned_paths.unsqueeze(0)
63
+
64
+ B = planned_paths.shape[0]
65
+ current_tcp = obs['extra']['tcp_pose'][:3]
66
+ target_pos = obs['extra']['goal_pose'][:3]
67
+
68
+ # Use colormap for trajectory rank (0 = best, B-1 = worst)
69
+ colormap = plt.cm.get_cmap('viridis', B)
70
+ colors = colormap(np.linspace(0, 1, B)) # [B, 4] RGBA
71
+ sm = mpl.cm.ScalarMappable(cmap=colormap, norm=plt.Normalize(vmin=0, vmax=B-1))
72
+ self.fig.colorbar(sm, ax=self.ax, label='Trajectory Rank (0 = Best)')
73
+
74
+ for i, path in enumerate(planned_paths):
75
+ path = path.clone().cpu().numpy() if torch.is_tensor(path) else np.array(path)
76
+ tcp_points = path[:, :3]
77
+ color = colors[i] # ranked color
78
+ self.ax.plot(tcp_points[:, 0], tcp_points[:, 1], tcp_points[:, 2],
79
+ color=color, linestyle='-', label=f'Rank {i}')
80
+ self.ax.scatter(tcp_points[:, 0], tcp_points[:, 1], tcp_points[:, 2],
81
+ color='black', marker='x', s=40, alpha=0.4)
82
+
83
+ self.ax.scatter(*current_tcp, color='g', marker='o', label='Current Position')
84
+ self.ax.scatter(*target_pos, color='r', marker='*', label='Target')
85
+
86
+ if point_cloud is not None:
87
+ self.ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2],
88
+ c='gray', alpha=0.3, s=1, label='Obstacles')
89
+
90
+ if simplified_paths is not None:
91
+ simplified_paths = simplified_paths.clone().cpu().numpy() if torch.is_tensor(simplified_paths) else np.array(simplified_paths)
92
+ self.ax.plot(simplified_paths[:, 0], simplified_paths[:, 1], simplified_paths[:, 2],
93
+ color='purple', linestyle='-', linewidth=3.0, label='Simplified Path')
94
+
95
+ if robot_executed_path is not None and robot_executed_path.shape[0] > 0:
96
+ self.ax.plot(robot_executed_path[:, 0], robot_executed_path[:, 1], robot_executed_path[:, 2],
97
+ color='orange', linestyle='--', linewidth=3.0, label='Executed Path')
98
+
99
+ self.ax.set_xlabel('X')
100
+ self.ax.set_ylabel('Y')
101
+ self.ax.set_zlabel('Z')
102
+ self.ax.set_title('Planned Trajectories (Ranked)')
103
+ self.ax.legend()
104
+
105
+ def plot_joint_trajectory(self, joint_trajectories, title='Joint Trajectory', save_path=None):
106
+ """
107
+ Args:
108
+ joint_trajectories: numpy array or torch.Tensor of shape [N, length, joint_dim] where:
109
+ N: number of trajectories
110
+ length: number of points per trajectory
111
+ joint_dim: number of joint dimensions
112
+ """
113
+ # Convert to numpy if torch tensor
114
+ if hasattr(joint_trajectories, 'detach'):
115
+ joint_trajectories = joint_trajectories.detach().cpu().numpy()
116
+ else:
117
+ joint_trajectories = np.asarray(joint_trajectories)
118
+
119
+ N, length, joint_dim = joint_trajectories.shape
120
+ n_rows = 3
121
+ n_cols = math.ceil(joint_dim / n_rows)
122
+ fig, axes = plt.subplots(n_rows, n_cols, figsize=(6 * n_cols, 3 * n_rows), sharex=True)
123
+ axes = axes.flatten() if joint_dim > 1 else [axes]
124
+ time_steps = np.arange(length)
125
+
126
+ for j in range(joint_dim):
127
+ ax = axes[j]
128
+ ax.cla() # Clear previous plot if reusing axes
129
+ for i in range(N):
130
+ ax.plot(time_steps, joint_trajectories[i, :, j], alpha=0.7)
131
+ ax.set_ylabel(f'Joint {j+1} Value')
132
+ ax.set_title(f'Joint {j+1}')
133
+ ax.grid(True)
134
+ axes[joint_dim-1].set_xlabel('Time Step')
135
+ fig.suptitle(title)
136
+ plt.tight_layout(rect=[0, 0, 1, 0.97])
137
+
138
+ if save_path is not None:
139
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
140
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
141
+ plt.close(fig)
142
+ else:
143
+ plt.draw()
144
+ plt.show()
145
+
146
+ def plot_path_with_guidance(self, diffusion_history,
147
+ guidance_history=None,
148
+ point_cloud=None,
149
+ save_path=None):
150
+ """Plot the diffusion path with guidance in 3D, showing dimensions 0, 1, and 2.
151
+
152
+ Args:
153
+ diffusion_history: Dictionary containing the diffusion process history
154
+ guidance_history: Optional dictionary containing guidance history
155
+ save_path: Path where to save the plot. If None, will display plot instead
156
+ """
157
+ timesteps_to_plot = [-2, -1] # Adjust these values as needed
158
+ n_plots = len(timesteps_to_plot)
159
+ fig = plt.figure(figsize=(6*n_plots, 6))
160
+
161
+ print("diffusion_history length: ", len(diffusion_history))
162
+ if guidance_history is not None:
163
+ print("guidance_history length: ", len(guidance_history))
164
+
165
+ for idx, t in enumerate(timesteps_to_plot):
166
+ ax = fig.add_subplot(1, n_plots, idx+1, projection='3d')
167
+ history_t = diffusion_history[t]
168
+
169
+ # Convert to numpy and reshape to (-1, 9)
170
+ x_t = history_t['x'].reshape(-1, 9)
171
+ noise_t = history_t['noise'].reshape(-1, 9)
172
+
173
+ # Unnormalize the full 9D positions first
174
+ x_t = self.unnormalize_numpy(x_t)
175
+ noise_t = self.unnormalize_numpy(noise_t)
176
+ # Then extract first 3 dimensions
177
+ x_t = x_t[:, :3]
178
+ noise_t = noise_t[:, :3] # Extract first 3 dims of noise
179
+
180
+ # Plot diffusion positions in 3D
181
+ ax.scatter(x_t[:, 0], x_t[:, 1], x_t[:, 2],
182
+ c='blue', alpha=0.5, label='Diffusion positions')
183
+
184
+ # Plot diffusion directions using 3D quiver
185
+ # Scale the noise vectors to have appropriate lengths
186
+ scaled_noise = noise_t * 0.06 # Scale factor to make arrows visible
187
+ ax.quiver(x_t[:, 0], x_t[:, 1], x_t[:, 2],
188
+ scaled_noise[:, 0], scaled_noise[:, 1], scaled_noise[:, 2],
189
+ color='red', alpha=0.5, label='Diffusion direction',
190
+ normalize=False) # Don't normalize to preserve relative magnitudes
191
+
192
+ # Plot guidance if available
193
+ if guidance_history is not None:
194
+ guidance_t = guidance_history[t]
195
+ # Convert and reshape full 9D data
196
+ g_x = guidance_t['x'].reshape(-1, 9)
197
+ g_noise = guidance_t['grad_scaled'].reshape(-1, 9)
198
+
199
+ # Unnormalize full 9D guidance positions first
200
+ g_x = self.unnormalize_numpy(g_x)
201
+ # Then extract first 3 dimensions
202
+ g_x = g_x[:, :3]
203
+ g_noise = g_noise[:, :3] # Extract first 3 dims of guidance
204
+ scaled_g_noise = g_noise * 1.0 # Scale factor to make arrows visible
205
+
206
+ # Plot guidance positions and directions in 3D
207
+ ax.scatter(g_x[:, 0], g_x[:, 1], g_x[:, 2],
208
+ c='green', alpha=0.5, label='Guidance positions')
209
+ ax.quiver(g_x[:, 0], g_x[:, 1], g_x[:, 2],
210
+ scaled_g_noise[:, 0], scaled_g_noise[:, 1], scaled_g_noise[:, 2],
211
+ color='orange', alpha=0.5, label='Guidance direction',
212
+ normalize=False) # Don't normalize to preserve relative magnitudes
213
+
214
+ if point_cloud is not None:
215
+ ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2],
216
+ c='gray', alpha=0.3, s=1, label='Obstacles')
217
+
218
+ ax.set_title(f'Timestep {t}')
219
+ ax.set_xlabel('X')
220
+ ax.set_ylabel('Y')
221
+ ax.set_zlabel('Z')
222
+ ax.legend()
223
+
224
+ # Optional: set consistent axis limits if needed
225
+ ax.set_xlim([0.0, 0.7])
226
+ ax.set_ylim([-0.5, 0.5])
227
+ ax.set_zlim([0.0, 0.5])
228
+
229
+ plt.tight_layout()
230
+
231
+ if save_path is not None:
232
+ # Create directory if it doesn't exist
233
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
234
+ # Generate a timestamp for the image name
235
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
236
+ # Save the figure with the timestamp in the filename
237
+ plt.savefig(f"{os.path.splitext(save_path)[0]}_{timestamp}.png", dpi=300, bbox_inches='tight')
238
+ else:
239
+ plt.show()
240
+ # plt.show()
241
+ plt.close()
242
+
243
+
244
+ def plot_trajectory_with_cost(self, sphere_trajectories, sdf_costs,
245
+ spheres_after_guidance=None, sampled_spheres=None, point_cloud=None, sphere_idx=0, time_step=0):
246
+ """
247
+ Plot the trajectory of a single sphere (sphere_idx) for all batches, coloring by total cost at each timestep.
248
+ Args:
249
+ sphere_trajectories: [batch, seq_len, num_spheres, 3]
250
+ sdf_costs: [batch, seq_len, num_spheres]
251
+ spheres_after_guidance: [batch, seq_len, num_spheres, 3] or None
252
+ point_cloud: [N, 3] or None
253
+ sphere_idx: int, which sphere to plot
254
+ """
255
+ # Convert to numpy if torch tensor
256
+ if hasattr(sphere_trajectories, 'detach'):
257
+ sphere_trajectories = sphere_trajectories.detach().cpu().numpy()
258
+ if hasattr(sdf_costs, 'detach'):
259
+ sdf_costs = sdf_costs.detach().cpu().numpy()
260
+ if spheres_after_guidance is not None and hasattr(spheres_after_guidance, 'detach'):
261
+ spheres_after_guidance = spheres_after_guidance.detach().cpu().numpy()
262
+ if sampled_spheres is not None and hasattr(sampled_spheres, 'detach'):
263
+ sampled_spheres = sampled_spheres.detach().cpu().numpy()
264
+
265
+ batch, seq_len, num_spheres, _ = sphere_trajectories.shape
266
+
267
+ # Get the trajectory for the selected sphere across all batches
268
+ xyz = sphere_trajectories[:, :, sphere_idx, :] # [batch, seq_len, 3]
269
+ # Get the total cost at each timestep for each batch
270
+ total_cost = sdf_costs.sum(axis=-1) # [batch, seq_len]
271
+ # Get the total cost for each trajectory
272
+ trajectory_cost = total_cost.sum(axis=-1) # [batch]
273
+
274
+ fig = plt.figure(figsize=(10, 8))
275
+ ax = fig.add_subplot(111, projection='3d')
276
+
277
+ # Normalize trajectory costs for colormap (for line color)
278
+ traj_norm = plt.Normalize(trajectory_cost.min(), trajectory_cost.max())
279
+ traj_cmap = plt.get_cmap('jet')
280
+
281
+ # Plot each batch as a separate trajectory
282
+ for b in range(batch):
283
+ # Color by total cost at each timestep (scatter)
284
+ p = ax.scatter(xyz[b, :, 0], xyz[b, :, 1], xyz[b, :, 2],
285
+ c=total_cost[b], cmap='jet', s=40, marker='o',
286
+ label='Before Guidance' if b == 0 else None)
287
+
288
+ # Line: color by total trajectory cost
289
+ line_color = traj_cmap(traj_norm(trajectory_cost[b]))
290
+ ax.plot(
291
+ xyz[b, :, 0], xyz[b, :, 1], xyz[b, :, 2],
292
+ color=line_color, linewidth=2, alpha=0.9,
293
+ label=f'Traj {b} (cost={trajectory_cost[b]:.2f})'
294
+ )
295
+
296
+ # Mark start and end
297
+ ax.scatter(xyz[b, 0, 0], xyz[b, 0, 1], xyz[b, 0, 2], color='green', s=80)
298
+ ax.scatter(xyz[b, -1, 0], xyz[b, -1, 1], xyz[b, -1, 2], color='red', s=80)
299
+
300
+ # Plot after guidance if provided
301
+ if spheres_after_guidance is not None:
302
+ xyz_after = spheres_after_guidance[:, :, sphere_idx, :] # [batch, seq_len, 3]
303
+ ax.plot(xyz_after[b, :, 0], xyz_after[b, :, 1], xyz_after[b, :, 2], color='orange', alpha=0.7, linewidth=2, label='After Guidance' if b == 0 else None)
304
+ ax.scatter(xyz_after[b, :, 0], xyz_after[b, :, 1], xyz_after[b, :, 2], color='black', s=30)
305
+
306
+ # if sampled_spheres is not None:
307
+ # xyz_sampled = sampled_spheres[:, :, sphere_idx, :] # [batch, seq_len, 3]
308
+ # ax.scatter(xyz_sampled[b, :, 0], xyz_sampled[b, :, 1], xyz_sampled[b, :, 2], color='purple', s=5, alpha=0.5)
309
+ # Plot point cloud if available
310
+ if point_cloud is not None:
311
+ ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2],
312
+ c='gray', alpha=0.3, s=2, label='Obstacles')
313
+
314
+ fig.colorbar(p, ax=ax, label='Total SDF Cost (sum over spheres)')
315
+ ax.set_xlabel('X')
316
+ ax.set_ylabel('Y')
317
+ ax.set_zlabel('Z')
318
+ ax.set_title(f'Sphere index {sphere_idx} at time step {time_step} Trajectories (all batches) with Total SDF Cost')
319
+ ax.legend()
320
+ plt.tight_layout()
321
+ return fig
322
+
323
+ def extract_diffusion_history(self, diffusion_history):
324
+ t = -1
325
+ history_t = diffusion_history[t]
326
+ print(history_t.keys())
327
+ # x_t = history_t['x'].reshape(-1, 4)
328
+
329
+ # return diffusion_history[0]['x'].detach().cpu().numpy()
330
+ return None
331
+
332
+ def extract_guidance_history(self, guidance_history):
333
+ return None
334
+
335
+ def plot_trajectories_list(self, trajectories_list, point_cloud=None, label_list=None):
336
+ """Plot multiple trajectories from a list.
337
+ Args:
338
+ trajectories_list: List of trajectory samples
339
+ point_cloud: Optional point cloud of obstacles
340
+ """
341
+ # Clear any existing figures to avoid accumulation
342
+ plt.close('all')
343
+
344
+ # Create a new figure
345
+ fig = plt.figure(figsize=(10, 8))
346
+ ax = fig.add_subplot(111, projection='3d')
347
+
348
+ colors = ['blue', 'orange', 'green', 'red']
349
+ # Create empty lists to store legend handles and labels
350
+ legend_handles = []
351
+ legend_labels = []
352
+
353
+ if label_list is not None:
354
+ if len(label_list) != len(trajectories_list):
355
+ raise ValueError(f"Length of label_list ({len(label_list)}) must equal length of trajectories_list ({len(trajectories_list)})")
356
+
357
+ for i, all_samples in enumerate(trajectories_list):
358
+ # Unnormalize if the data is normalized
359
+ if torch.is_tensor(all_samples):
360
+ all_samples = all_samples.detach().cpu().numpy()
361
+
362
+ # Use different colors for different trajectory sets
363
+ color = colors[i % len(colors)]
364
+
365
+ # Plot the samples using the existing figure and axis
366
+ traj_line = self._plot_samples_xyz(all_samples, ax, color=color)
367
+
368
+ # Add the trajectory line to legend handles
369
+ legend_handles.append(traj_line)
370
+ legend_labels.append(label_list[i])
371
+
372
+ # Add start and end markers to legend
373
+ start_marker = ax.scatter([], [], color='green', s=30)
374
+ end_marker = ax.scatter([], [], color='red', s=30)
375
+ legend_handles.extend([start_marker, end_marker])
376
+ legend_labels.extend(['Start', 'End'])
377
+
378
+ # Plot point cloud if available
379
+ if point_cloud is not None:
380
+ obstacles = ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2],
381
+ c='gray', alpha=0.3, s=5)
382
+ legend_handles.append(obstacles)
383
+ legend_labels.append('Obstacles')
384
+
385
+ # Set axis labels and add legend
386
+ ax.set_xlabel('X')
387
+ ax.set_ylabel('Y')
388
+ ax.set_zlabel('Z')
389
+ ax.set_title('Trajectory Comparison')
390
+
391
+ # Set consistent axis limits
392
+ ax.set_xlim(0.1, 0.8)
393
+ ax.set_ylim(-0.5, 0.5)
394
+ ax.set_zlim(0.0, 0.4)
395
+
396
+ # Add grid for better depth perception
397
+ ax.grid(True)
398
+
399
+ # Adjust viewing angle for better visualization
400
+ # ax.view_init(elev=view_angle[0], azim=view_angle[1])
401
+ # ax.view_init(elev=30, azim=-60) # Use matplotlib's default viewing angle
402
+
403
+ # Add legend with custom handles and labels
404
+ ax.legend(legend_handles, legend_labels)
405
+
406
+ plt.draw()
407
+ return fig
408
+
409
+ def _plot_samples_xyz(self, samples, ax, color='black', plot_waypoints=False):
410
+ """Plot the first 3 dimensions of each sample in a 3D plot.
411
+
412
+ Args:
413
+ samples: Numpy array or tensor of shape [N, length, dim]
414
+ ax: Matplotlib axis to plot on
415
+ color: Color to use for plotting
416
+
417
+ Returns:
418
+ Line artist for the first trajectory (for legend)
419
+ """
420
+ # Convert torch tensor to numpy if needed
421
+ if torch.is_tensor(samples):
422
+ samples = samples.detach().cpu().numpy()
423
+
424
+ # Extract the xyz coordinates (first 3 dimensions)
425
+ xyz_samples = samples[:, :, :3]
426
+
427
+ line_artist = None
428
+ # Plot each trajectory
429
+ for i in range(xyz_samples.shape[0]):
430
+ trajectory = xyz_samples[i]
431
+ line = ax.plot3D(trajectory[:, 0], trajectory[:, 1], trajectory[:, 2], color=color, alpha=0.5, linewidth=3.5)
432
+ if plot_waypoints:
433
+ ax.scatter(trajectory[:, 0], trajectory[:, 1], trajectory[:, 2], color='black', s=5, alpha = 0.3)
434
+
435
+ # Store the first trajectory's line artist for legend
436
+ if i == 0:
437
+ line_artist = line[0]
438
+
439
+ # Mark start and end points
440
+ ax.scatter(trajectory[0, 0], trajectory[0, 1], trajectory[0, 2], color='green', s=40)
441
+ ax.scatter(trajectory[-1, 0], trajectory[-1, 1], trajectory[-1, 2], color='red', s=40)
442
+
443
+ return line_artist
444
+
445
+ def _plot_samples_xy(self, samples, ax, color='black', plot_waypoints=False):
446
+ # Convert torch tensor to numpy if needed
447
+ if torch.is_tensor(samples):
448
+ samples = samples.detach().cpu().numpy()
449
+
450
+ # Extract the xyz coordinates (first 3 dimensions)
451
+ xyz_samples = samples[:, :, :2]
452
+
453
+ line_artist = None
454
+ # Plot each trajectory
455
+ for i in range(xyz_samples.shape[0]):
456
+ trajectory = xyz_samples[i]
457
+ # alpha_value = 0.2 + (0.4 * i / max(1, xyz_samples.shape[0] - 1)) # Scale from 0.2 to 0.6 based on i
458
+ # line = ax.plot(trajectory[:, 0], trajectory[:, 1], color=color, alpha=alpha_value, linewidth=3.5)
459
+ line = ax.plot(trajectory[:, 0], trajectory[:, 1], color=color, alpha=0.5, linewidth=3.5)
460
+ if plot_waypoints:
461
+ # Use a darker shade of the original color
462
+ darker_color = plt.cm.colors.to_rgba(color)
463
+ darker_color = [max(0, c * 0.7) for c in darker_color[:3]] + [darker_color[3]]
464
+ ax.scatter(trajectory[:, 0], trajectory[:, 1], color=darker_color, s=20, alpha = 0.4)
465
+
466
+ # Store the first trajectory's line artist for legend
467
+ if i == 0:
468
+ line_artist = line[0]
469
+
470
+ # Mark start and end points
471
+ ax.scatter(trajectory[0, 0], trajectory[0, 1], color='green', s=80)
472
+ ax.scatter(trajectory[-1, 0], trajectory[-1, 1], color='red', s=80)
473
+
474
+ return line_artist
475
+
476
+ def plot_trajectories_dual_view(self, trajectories_list,
477
+ point_cloud=None,
478
+ label_list=None,
479
+ color_list=None,
480
+ title=['Left View', 'Right View'],
481
+ plot_2d=False,):
482
+ """Plot trajectories from two different viewing angles in a single figure.
483
+
484
+ Args:
485
+ trajectories_list: List of trajectory samples
486
+ point_cloud: Optional point cloud of obstacles
487
+ label_list: Optional list of labels for the trajectories
488
+
489
+ Returns:
490
+ matplotlib figure object
491
+ """
492
+ # Clear any existing figures
493
+ plt.close('all')
494
+ if color_list is None:
495
+ color_list = ['blue', 'orange', 'green', 'red']
496
+
497
+ # Create a figure with two subplots
498
+ if not plot_2d:
499
+ # fig = plt.figure(figsize=(15, 6))
500
+ # # 3D plotting
501
+ # # Left view - side angle
502
+ # ax1 = fig.add_subplot(121, projection='3d')
503
+ # self._setup_trajectory_plot(ax1, trajectories_list, point_cloud, label_list, color_list, plot_2d)
504
+ # ax1.view_init(elev=90, azim=0) # Left side view
505
+ # ax1.set_title(title[0], fontsize=20)
506
+
507
+ # # Right view - different angle
508
+ # ax2 = fig.add_subplot(122, projection='3d')
509
+ # self._setup_trajectory_plot(ax2, trajectories_list, point_cloud, label_list, color_list, plot_2d)
510
+ # ax2.view_init(elev=5, azim=-20) # Right side view
511
+ # ax2.set_title(title[1], fontsize=20)
512
+
513
+ fig = plt.figure(figsize=(10, 10))
514
+ # 3D plotting
515
+ # Right view - different angle
516
+ ax2 = fig.add_subplot(111, projection='3d')
517
+ self._setup_trajectory_plot(ax2, trajectories_list, point_cloud, label_list, color_list, plot_2d)
518
+ ax2.view_init(elev=10, azim=30) # Right side view
519
+ # ax2.set_title(title[1], fontsize=20, pad=1)
520
+ else:
521
+ fig = plt.figure(figsize=(8, 8))
522
+ # 2D plotting - single view
523
+ ax1 = fig.add_subplot(111)
524
+ self._setup_trajectory_plot(ax1, trajectories_list, point_cloud, label_list, color_list, plot_2d)
525
+ # Split title into multiple lines if it's too long
526
+ if isinstance(title[0], str) and len(title[0]) > 30:
527
+ # Insert newline character every ~30 characters at space
528
+ words = title[0].split()
529
+ lines = []
530
+ current_line = []
531
+ current_length = 0
532
+
533
+ for word in words:
534
+ if current_length + len(word) > 30:
535
+ lines.append(' '.join(current_line))
536
+ current_line = [word]
537
+ current_length = len(word)
538
+ else:
539
+ current_line.append(word)
540
+ current_length += len(word) + 1 # +1 for space
541
+
542
+ if current_line:
543
+ lines.append(' '.join(current_line))
544
+
545
+ formatted_title = '\n'.join(lines)
546
+ ax1.set_title(formatted_title, fontsize=28)
547
+ else:
548
+ ax1.set_title(title[0], fontsize=20)
549
+
550
+ plt.tight_layout()
551
+ plt.draw()
552
+ return fig
553
+
554
+ def _setup_trajectory_plot(self, ax, trajectories_list, point_cloud, label_list, color_list, plot_2d):
555
+ """Helper function to set up a trajectory plot on an axis.
556
+
557
+ Args:
558
+ ax: Matplotlib 3D axis
559
+ trajectories_list: List of trajectory samples
560
+ point_cloud: Optional point cloud of obstacles
561
+ label_list: Optional list of labels for the trajectories
562
+ """
563
+ colors = color_list
564
+ # Create empty lists to store legend handles and labels
565
+ legend_handles = []
566
+ legend_labels = []
567
+
568
+ if label_list is not None:
569
+ if len(label_list) < len(trajectories_list):
570
+ raise ValueError(f"Length of label_list ({len(label_list)}) must equal or greater length of trajectories_list ({len(trajectories_list)})")
571
+
572
+ for i, all_samples in enumerate(trajectories_list):
573
+ # Unnormalize if the data is normalized
574
+ if torch.is_tensor(all_samples):
575
+ all_samples = all_samples.detach().cpu().numpy()
576
+
577
+ # Use different colors for different trajectory sets
578
+ color = colors[i % len(colors)]
579
+
580
+ plot_waypoints = False
581
+ if label_list is not None and ('prior' in label_list[i] or ('guidance' in label_list[i] and i !=0)):
582
+ plot_waypoints = True
583
+
584
+ # Check if we're plotting in 2D or 3D
585
+ if hasattr(ax, 'get_zlim'): # 3D axis has get_zlim method
586
+ # Plot the samples using the existing figure and axis (3D)
587
+ traj_line = self._plot_samples_xyz(all_samples, ax, color=color, plot_waypoints=plot_waypoints)
588
+ else:
589
+ # Plot the samples in 2D (xy only)
590
+ traj_line = self._plot_samples_xy(all_samples, ax, color=color, plot_waypoints=plot_waypoints)
591
+
592
+ # Add the trajectory line to legend handles
593
+ legend_handles.append(traj_line)
594
+ legend_labels.append(label_list[i] if label_list is not None else f"Trajectory {i+1}")
595
+
596
+ # Add start and end markers to legend
597
+ start_marker = ax.scatter([], [], color='green', s=30)
598
+ end_marker = ax.scatter([], [], color='red', s=30)
599
+ legend_handles.extend([start_marker, end_marker])
600
+ legend_labels.extend(['Start', 'End'])
601
+
602
+ # Plot point cloud if available
603
+ if point_cloud is not None:
604
+ if hasattr(ax, 'get_zlim'): # 3D axis
605
+ obstacles = ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2],
606
+ c='gray', alpha=0.3, s=2)
607
+ else: # 2D axis - xy only
608
+ obstacles = ax.scatter(point_cloud[:, 0], point_cloud[:, 1], c='gray', alpha=0.3, s=2)
609
+
610
+ legend_handles.append(obstacles)
611
+ legend_labels.append('Obstacles')
612
+
613
+ # Set axis labels
614
+ if hasattr(ax, 'get_zlim'): # 3D axis
615
+ ax.set_xlabel('X', fontsize=20)
616
+ ax.set_ylabel('Y', fontsize=20)
617
+ ax.set_zlabel('Z', fontsize=20)
618
+
619
+ # Set consistent axis limits for 3D
620
+ ax.set_xlim(0.2, 0.6)
621
+ ax.set_ylim(-0.5, 0.5)
622
+ ax.set_zlim(0.0, 0.4)
623
+ # Increase tick size
624
+ ax.tick_params(axis='both', which='major', labelsize=14, width=2, length=6)
625
+ ax.legend(legend_handles, legend_labels,
626
+ bbox_to_anchor=(0.1, 0.8), loc='upper left', fontsize=14, prop={'size': 12})
627
+
628
+ else: # 2D axis - xy only
629
+ ax.set_xlabel('X', fontsize=20)
630
+ ax.set_ylabel('Y', fontsize=20)
631
+ ax.set_xlim(0.15, 0.75)
632
+ ax.set_ylim(-0.6, 0.6)
633
+ # Increase tick size
634
+ ax.tick_params(axis='both', which='major', labelsize=16, width=2, length=8)
635
+ ax.legend(legend_handles, legend_labels,
636
+ bbox_to_anchor=(0.3, 0.95), loc='upper center', fontsize=18, prop={'size': 18})
637
+
638
+ # Add grid for better depth perception
639
+ ax.grid(False)
640
+ # Add legend with custom handles and labels
641
+
642
+ def create_trajectory_figure(trajectories, title='Trajectory'):
643
+ """Create a figure with trajectories showing both 3D position and euler angles.
644
+ Args:
645
+ trajectories: numpy array or torch.Tensor of shape [N * length * dim] where:
646
+ N: number of trajectories
647
+ length: number of points per trajectory
648
+ dim: dimensionality (7 for position+quaternion or 9 for position+rotation6d)
649
+ Returns:
650
+ matplotlib figure object
651
+ """
652
+ # # Convert torch tensor to numpy if needed
653
+ fig = plt.figure(figsize=(15, 10))
654
+ euler_labels = ['Roll', 'Pitch', 'Yaw']
655
+
656
+ # Create 3D subplot for position - using a proper grid layout
657
+ ax_pos = fig.add_subplot(2, 3, (1, 3), projection='3d') # Spans positions 1-3 in the top row
658
+
659
+ # Add legend handles for trajectory colors
660
+ legend_handles = []
661
+ added_trajectory_to_legend = False
662
+
663
+ # Create 3 subplots for euler angles
664
+ for i in range(3):
665
+ ax = fig.add_subplot(2, 3, i+4) # Position them in the bottom row
666
+
667
+ for traj_idx in range(trajectories.shape[0]):
668
+ if trajectories.shape[2] == 9:
669
+ trajectory = transform_ortho6d_to_quat(trajectories[traj_idx])
670
+ else:
671
+ trajectory = trajectories[traj_idx]
672
+
673
+ if hasattr(trajectory, 'detach'): # Check if it's a torch tensor
674
+ trajectory = trajectory.detach().cpu().numpy()
675
+ else:
676
+ trajectory = np.asarray(trajectory)
677
+ positions = trajectory[:, :3]
678
+ time_steps = np.arange(len(positions))
679
+
680
+ color = 'black' if traj_idx == 0 else 'blue'
681
+ alpha = 1.0 if traj_idx == 0 else 0.2
682
+
683
+ # Plot euler angles
684
+ euler_angles = np.array([quaternion_to_euler(q) for q in trajectory[:, 3:7]])
685
+ ax.plot(time_steps, np.rad2deg(euler_angles[:, i]),
686
+ color=color, alpha=alpha)
687
+ ax.set_xlabel('Time Step')
688
+ ax.set_ylabel(f'{euler_labels[i]} (degrees)')
689
+ ax.set_title(f'{euler_labels[i]} Angle')
690
+ ax.grid(True)
691
+
692
+ # Plot 3D trajectory
693
+ line = ax_pos.plot3D(positions[:, 0], positions[:, 1], positions[:, 2],
694
+ color=color, alpha=alpha)
695
+
696
+ # Only add to legend once for reference and once for all other trajectories
697
+ if i == 0:
698
+ if traj_idx == 0:
699
+ legend_handles.append((line[0], 'Reference'))
700
+ elif not added_trajectory_to_legend:
701
+ legend_handles.append((line[0], 'Trajectories'))
702
+ added_trajectory_to_legend = True
703
+
704
+ # Add start/end markers for each trajectory
705
+ if i == 0: # Only add markers once per trajectory
706
+ start = ax_pos.scatter(positions[0, 0], positions[0, 1], positions[0, 2],
707
+ color='green', s=50)
708
+ end = ax_pos.scatter(positions[-1, 0], positions[-1, 1], positions[-1, 2],
709
+ color='red', s=50)
710
+
711
+ # Only add start/end to legend on the first trajectory
712
+ if traj_idx == 0:
713
+ legend_handles.append((start, 'Start'))
714
+ legend_handles.append((end, 'End'))
715
+
716
+ ax_pos.set_xlabel('X Position')
717
+ ax_pos.set_ylabel('Y Position')
718
+ ax_pos.set_zlabel('Z Position')
719
+ ax_pos.set_title('3D Position Trajectory')
720
+ ax_pos.set_xlim(-1, 1)
721
+ ax_pos.set_ylim(-1, 1)
722
+ ax_pos.set_zlim(-1, 1)
723
+
724
+ # Add the legend with all handles
725
+ ax_pos.legend(*zip(*legend_handles))
726
+
727
+ plt.suptitle(title)
728
+ plt.tight_layout()
729
+ return fig
730
+
731
+ def plot_trajectories(trajectories, title='Trajectory', save_path=None):
732
+ """Plot trajectories in 3D space.
733
+ Args:
734
+ trajectories: numpy array of shape [N * length * dim] where:
735
+ N: number of trajectories
736
+ length: number of points per trajectory
737
+ dim: dimensionality (3 for 3D space)
738
+ """
739
+ fig = create_trajectory_figure(trajectories, title)
740
+ if save_path is not None:
741
+ # Create directory if it doesn't exist
742
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
743
+ # Generate a timestamp for the image name
744
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
745
+ # Save the figure with the timestamp in the filename
746
+ plt.savefig(f"{os.path.splitext(save_path)[0]}_{timestamp}.png", dpi=300, bbox_inches='tight')
747
+ else:
748
+ plt.show()
749
+ plt.close()
750
+
751
+
752
+ # def create_joint_trajectory_figure(joint_trajectories, title='Joint Trajectory'):
753
+ # """
754
+ # Args:
755
+ # joint_trajectories: numpy array or torch.Tensor of shape [N, length, joint_dim] where:
756
+ # N: number of trajectories
757
+ # length: number of points per trajectory
758
+ # joint_dim: number of joint dimensions
759
+ # Returns:
760
+ # matplotlib figure object
761
+ # """
762
+ # # Convert to numpy if torch tensor
763
+ # if hasattr(joint_trajectories, 'detach'):
764
+ # joint_trajectories = joint_trajectories.detach().cpu().numpy()
765
+ # else:
766
+ # joint_trajectories = np.asarray(joint_trajectories)
767
+
768
+ # N, length, joint_dim = joint_trajectories.shape
769
+ # fig, axes = plt.subplots(joint_dim, 1, figsize=(8, 3 * joint_dim), sharex=True)
770
+ # if joint_dim == 1:
771
+ # axes = [axes]
772
+ # time_steps = np.arange(length)
773
+
774
+ # for j in range(joint_dim):
775
+ # ax = axes[j]
776
+ # for i in range(N):
777
+ # ax.plot(time_steps, joint_trajectories[i, :, j], alpha=0.7)
778
+ # ax.set_ylabel(f'Joint {j+1} Value')
779
+ # ax.set_title(f'Joint {j+1}')
780
+ # ax.grid(True)
781
+ # axes[-1].set_xlabel('Time Step')
782
+ # fig.suptitle(title)
783
+ # plt.tight_layout(rect=[0, 0, 1, 0.97])
784
+ # return fig
785
+
786
+ # def plot_joint_trajectory(joint_trajectories, title='Joint Trajectory', save_path=None):
787
+ # """
788
+ # Args:
789
+ # joint_trajectories: numpy array of shape [N * length * dim] where:
790
+ # N: number of trajectories
791
+ # length: number of points per trajectory
792
+ # dim: dimensionality (joint dimensions)
793
+ # """
794
+ # fig = create_trajectory_figure(joint_trajectories, title)
795
+ # if save_path is not None:
796
+ # os.makedirs(os.path.dirname(save_path), exist_ok=True)
797
+ # plt.savefig(save_path, dpi=300, bbox_inches='tight')
798
+ # else:
799
+ # plt.show()
800
+ # plt.close()
801
+
802
+ def visualize_point_cloud(points, colors, camera_type=""):
803
+ """
804
+ Visualize a point cloud using matplotlib.
805
+
806
+ Args:
807
+ points (np.ndarray): Point cloud coordinates of shape (N, 3)
808
+ colors (np.ndarray): RGB colors for each point of shape (N, 3)
809
+ camera_type (str): Name of the camera view (optional)
810
+ """
811
+ # Create 3D scatter plot
812
+ fig = plt.figure(figsize=(10, 10))
813
+ ax = fig.add_subplot(111, projection='3d')
814
+
815
+ # Plot points with their colors
816
+ scatter = ax.scatter(points[:, 0], points[:, 1], points[:, 2],
817
+ c=colors, # Use RGB colors
818
+ s=1) # Point size
819
+
820
+ # Set labels and title
821
+ ax.set_xlabel('X')
822
+ ax.set_ylabel('Y')
823
+ ax.set_zlabel('Z')
824
+ ax.set_title(f'Point Cloud{" - " + camera_type if camera_type else ""}')
825
+
826
+ # Adjust the view
827
+ ax.view_init(elev=30, azim=45)
828
+
829
+ plt.show()
830
+
831
+ def visualize_rgbd_and_pointcloud(rgb, depth, points, colors, camera_type=""):
832
+ """
833
+ Visualize RGB image, depth image, and point cloud in a single figure.
834
+
835
+ Args:
836
+ rgb (np.ndarray): RGB image of shape (H, W, 3)
837
+ depth (np.ndarray): Depth image of shape (H, W)
838
+ points (np.ndarray): Point cloud coordinates of shape (N, 3)
839
+ colors (np.ndarray): RGB colors for each point of shape (N, 3)
840
+ camera_type (str): Name of the camera view (optional)
841
+ """
842
+ fig = plt.figure(figsize=(15, 5))
843
+
844
+ # RGB image
845
+ ax1 = fig.add_subplot(131)
846
+ ax1.imshow(rgb)
847
+ ax1.set_title(f'RGB Image - {camera_type}')
848
+ ax1.axis('off')
849
+
850
+ # Depth image
851
+ ax2 = fig.add_subplot(132)
852
+ depth_vis = ax2.imshow(depth, cmap='viridis')
853
+ ax2.set_title(f'Depth Image - {camera_type}')
854
+ ax2.axis('off')
855
+ plt.colorbar(depth_vis, ax=ax2)
856
+
857
+ # Point cloud
858
+ ax3 = fig.add_subplot(133, projection='3d')
859
+ ax3.scatter(points[:, 0], points[:, 1], points[:, 2],
860
+ c=colors, s=1)
861
+ ax3.set_title(f'Point Cloud - {camera_type}')
862
+ ax3.set_xlabel('X')
863
+ ax3.set_ylabel('Y')
864
+ ax3.set_zlabel('Z')
865
+ ax3.view_init(elev=30, azim=45)
866
+
867
+ plt.tight_layout()
868
+ plt.show()
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/utils/pointcloud_utils.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import open3d as o3d
3
+ import matplotlib.pyplot as plt
4
+ from mpl_toolkits.mplot3d import Axes3D
5
+ from franka_robot_wrapper.camera_calibration import calibrate_external, computeT
6
+
7
+ class CameraInfo():
8
+ """
9
+ Camera intrinsics for point cloud creation.
10
+
11
+ Attributes:
12
+ width (int): The width of the camera image.
13
+ height (int): The height of the camera image.
14
+ fx (float): The focal length of the camera in the x direction.
15
+ fy (float): The focal length of the camera in the y direction.
16
+ cx (float): The optical center of the camera in the x direction.
17
+ cy (float): The optical center of the camera in the y direction.
18
+ scale (float): The scale factor for depth values.
19
+ """
20
+ def __init__(self, width, height, fx, fy, cx, cy, scale):
21
+ self.width = width
22
+ self.height = height
23
+ self.fx = fx
24
+ self.fy = fy
25
+ self.cx = cx
26
+ self.cy = cy
27
+ self.scale = scale
28
+
29
+ def create_point_cloud_from_depth_image(depth, camera, organized=True):
30
+ """ Generate point cloud using depth image only.
31
+
32
+ Input:
33
+ depth: [numpy.ndarray, (H,W), numpy.float32]
34
+ depth image
35
+ camera: [CameraInfo]
36
+ camera intrinsics
37
+ organized: bool
38
+ whether to keep the cloud in image shape (H,W,3)
39
+
40
+ Output:
41
+ cloud: [numpy.ndarray, (H,W,3)/(H*W,3), numpy.float32]
42
+ generated cloud, (H,W,3) for organized=True, (H*W,3) for organized=False
43
+ """
44
+ assert(depth.shape[0] == camera.height and depth.shape[1] == camera.width)
45
+ xmap = np.arange(camera.width)
46
+ ymap = np.arange(camera.height)
47
+ xmap, ymap = np.meshgrid(xmap, ymap)
48
+ points_z = depth / camera.scale
49
+ points_x = (xmap - camera.cx) * points_z / camera.fx
50
+ points_y = (ymap - camera.cy) * points_z / camera.fy
51
+ cloud = np.stack([points_x, points_y, points_z], axis=-1)
52
+ if not organized:
53
+ cloud = cloud.reshape([-1, 3])
54
+ return cloud
55
+
56
+ def visualize_point_cloud(points, colors, camera_type=""):
57
+ """
58
+ Visualize a point cloud using matplotlib.
59
+
60
+ Args:
61
+ points (np.ndarray): Point cloud coordinates of shape (N, 3)
62
+ colors (np.ndarray): RGB colors for each point of shape (N, 3)
63
+ camera_type (str): Name of the camera view (optional)
64
+ """
65
+ # Create 3D scatter plot
66
+ fig = plt.figure(figsize=(10, 10))
67
+ ax = fig.add_subplot(111, projection='3d')
68
+
69
+ # Plot points with their colors
70
+ scatter = ax.scatter(points[:, 0], points[:, 1], points[:, 2],
71
+ c=colors, # Use RGB colors
72
+ s=1) # Point size
73
+
74
+ # Set labels and title
75
+ ax.set_xlabel('X')
76
+ ax.set_ylabel('Y')
77
+ ax.set_zlabel('Z')
78
+ ax.set_title(f'Point Cloud{" - " + camera_type if camera_type else ""}')
79
+
80
+ # Adjust the view
81
+ ax.view_init(elev=30, azim=45)
82
+
83
+ plt.show()
84
+
85
+ def visualize_rgbd_and_pointcloud(rgb, depth, points, colors, camera_type=""):
86
+ """
87
+ Visualize RGB image, depth image, and point cloud in a single figure.
88
+
89
+ Args:
90
+ rgb (np.ndarray): RGB image of shape (H, W, 3)
91
+ depth (np.ndarray): Depth image of shape (H, W)
92
+ points (np.ndarray): Point cloud coordinates of shape (N, 3)
93
+ colors (np.ndarray): RGB colors for each point of shape (N, 3)
94
+ camera_type (str): Name of the camera view (optional)
95
+ """
96
+ fig = plt.figure(figsize=(15, 5))
97
+
98
+ # RGB image
99
+ ax1 = fig.add_subplot(131)
100
+ ax1.imshow(rgb)
101
+ ax1.set_title(f'RGB Image - {camera_type}')
102
+ ax1.axis('off')
103
+
104
+ # Depth image
105
+ ax2 = fig.add_subplot(132)
106
+ depth_vis = ax2.imshow(depth, cmap='viridis')
107
+ ax2.set_title(f'Depth Image - {camera_type}')
108
+ ax2.axis('off')
109
+ plt.colorbar(depth_vis, ax=ax2)
110
+
111
+ # Point cloud
112
+ ax3 = fig.add_subplot(133, projection='3d')
113
+ ax3.scatter(points[:, 0], points[:, 1], points[:, 2],
114
+ c=colors, s=1)
115
+ ax3.set_title(f'Point Cloud - {camera_type}')
116
+ ax3.set_xlabel('X')
117
+ ax3.set_ylabel('Y')
118
+ ax3.set_zlabel('Z')
119
+ ax3.view_init(elev=30, azim=45)
120
+
121
+ plt.tight_layout()
122
+ plt.show()
123
+
124
+ def convertRGBD2PCD(obs, n=5000, vis=False):
125
+ """
126
+ Convert RGB-D images to point cloud data for each camera.
127
+
128
+ This function:
129
+ 1. Takes RGB and depth images from trajectory data
130
+ 2. Converts them to 3D point clouds using camera parameters
131
+ 3. Filters points based on depth thresholds
132
+ 4. Samples n points from the cloud (with replacement if needed)
133
+ 5. Stores color information for each point
134
+ 6. Removes original image data to save memory
135
+
136
+ Args:
137
+ traj_data (dict): Trajectory data containing RGB-D images and camera parameters
138
+ n (int, optional): Number of points to sample from each point cloud. Defaults to 1000.
139
+ vis (bool, optional): Visualization flag (unused). Defaults to False.
140
+
141
+ Returns:
142
+ dict: Updated trajectory data with point clouds instead of images
143
+ """
144
+ obs_pointcloud = {'base_camera': None, 'hand_camera': None}
145
+ for camera_type in obs_pointcloud.keys():
146
+ pcd = []
147
+ # Do not use the last observation, following ManiSkill2 implementation
148
+ rgb = obs['image'][camera_type]['Color'][:,:,:3]
149
+ depth = obs['image'][camera_type]['Position'][:,:,3]
150
+ K = obs['camera_param'][camera_type]['intrinsic_cv']
151
+ fx, fy = K[0,0], K[1,1]
152
+ ppx, ppy = K[0,2], K[1,2]
153
+
154
+ # TODO: Do not hardcode these values
155
+ width = 128
156
+ height = 128
157
+ factor_depth = 1000
158
+ camera = CameraInfo(width, height, fx, fy, ppx, ppy, factor_depth)
159
+
160
+ # Obtain masked cloud and color data for point cloud creation.
161
+ color = np.array(rgb, dtype=np.float32) / 255.0
162
+ cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
163
+ shape = color[:,:,0].shape
164
+ # mask = np.zeros(shape) # Creating Workspace Mask
165
+ # mask = mask.astype(bool)
166
+ # mask = ((depth > 0) & (depth < 1400)) # TODO: Do not hardcode this depth value. Somehow figure out how to do it with robot location.
167
+
168
+ mask = np.ones(shape)
169
+ mask = mask.astype(bool)
170
+ cloud_masked = cloud[mask]
171
+ color_masked = color[mask]
172
+
173
+ # Sample n points from the point cloud, with replacement if needed
174
+ if len(cloud_masked) >= n:
175
+ idxs = np.random.choice(len(cloud_masked), n, replace=False)
176
+ else:
177
+ idxs1 = np.arange(len(cloud_masked))
178
+ idxs2 = np.random.choice(len(cloud_masked), n-len(cloud_masked), replace=True)
179
+ idxs = np.concatenate([idxs1, idxs2], axis=0)
180
+ cloud_sampled = cloud_masked[idxs]
181
+ color_sampled = color_masked[idxs]
182
+
183
+ if vis: # Visualize RGB, depth, and point cloud if requested
184
+ visualize_rgbd_and_pointcloud(rgb, depth, cloud_sampled, color_sampled, camera_type)
185
+
186
+ obs_pointcloud[camera_type] = np.array(cloud_sampled)
187
+
188
+ return obs_pointcloud
189
+
190
+
191
+ ########################################################
192
+ # Real-Robot Stuff
193
+ def visualize_cloud_with_axes(cloud_sampled):
194
+ """
195
+ Visualize a point cloud using Open3D and plot the coordinate axes.
196
+
197
+ Args:
198
+ cloud_sampled: A numpy array of shape (N, 3) containing 3D points to visualize
199
+
200
+ This function creates an Open3D point cloud object from the input points,
201
+ adds a coordinate frame (axes), and displays them in an interactive 3D viewer.
202
+ """
203
+ cloud = o3d.geometry.PointCloud()
204
+ cloud.points = o3d.utility.Vector3dVector(cloud_sampled)
205
+ # Create a coordinate frame at the origin with size 0.1 (can adjust as needed)
206
+ axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.1, origin=[0, 0, 0])
207
+ o3d.visualization.draw_geometries([cloud, axis])
208
+
209
+ def visualize_cloud(cloud_sampled):
210
+ """
211
+ Visualize a point cloud using Open3D.
212
+
213
+ Args:
214
+ cloud_sampled: A numpy array of shape (N, 3) containing 3D points to visualize
215
+
216
+ This function creates an Open3D point cloud object from the input points
217
+ and displays it in an interactive 3D viewer.
218
+ """
219
+ cloud = o3d.geometry.PointCloud()
220
+ cloud.points = o3d.utility.Vector3dVector(cloud_sampled)
221
+ # cloud.colors = o3d.utility.Vector3dVector(color_sampled)
222
+ o3d.visualization.draw_geometries([cloud])
223
+
224
+ def get_and_process_data_cam(rs, n = 20000, visualize = False):
225
+ """
226
+ Process data from a RealSense camera to create a point cloud.
227
+
228
+ Args:
229
+ rs: RealSense camera object with get_intrinsics() and get_rgbd() methods
230
+ n (int): Number of points to sample from the point cloud (default: 20000)
231
+ visualize (bool): Whether to visualize the resulting point cloud (default: False)
232
+
233
+ Returns:
234
+ np.ndarray: A sampled point cloud as a numpy array of shape (n, 3)
235
+
236
+ This function:
237
+ 1. Gets camera intrinsics from the RealSense camera
238
+ 2. Captures RGBD data from the camera
239
+ 3. Creates a point cloud from the depth image
240
+ 4. Applies a depth mask to filter out invalid or distant points
241
+ 5. Samples n points from the masked point cloud
242
+ 6. Optionally visualizes the resulting point cloud
243
+ """
244
+ fx = rs.get_intrinsics()[0].fx
245
+ fy = rs.get_intrinsics()[0].fy
246
+ ppx = rs.get_intrinsics()[0].ppx
247
+ ppy = rs.get_intrinsics()[0].ppy
248
+ width = rs.get_intrinsics()[0].width
249
+ height = rs.get_intrinsics()[0].height
250
+ factor_depth = 1000
251
+
252
+ # load data
253
+ img = rs.get_rgbd()
254
+ # Image.fromarray(np.array(img[0][:,:,:3], dtype=np.uint8)).save("your_file.jpeg")
255
+ color = np.array(img[0][:,:,:3], dtype=np.float32) / 255.0
256
+ depth = np.array(img[0][:,:,3])
257
+ # workspace_mask = np.array(Image.open(os.path.join(data_dir, 'workspace_mask.png'))) #(720, 1280) # True/False -- Choose where to segment
258
+ # generate cloud
259
+ # intrinsic[0][0] = fx, intrinsic[1][1] = fy, intrinsic[0][2] = ppx = cx, intrinsic[1][2] = ppy = cy
260
+ camera = CameraInfo(width, height, fx, fy, ppx, ppy, factor_depth)
261
+ cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
262
+
263
+ # Creating Workspace Mask
264
+ # shape = color[:,:,0].shape
265
+ # mask = np.ones(shape)
266
+ # mask = mask.astype(bool)
267
+ # get valid points
268
+ mask = ((depth > 1) & (depth < 2500)) # TODO: Do not hardcode this depth value. Somehow figure out how to do it with robot location.
269
+ cloud_masked = cloud[mask]
270
+ color_masked = color[mask]
271
+
272
+
273
+ # sample points
274
+ if len(cloud_masked) >= n:
275
+ idxs = np.random.choice(len(cloud_masked), n, replace=False)
276
+ else:
277
+ idxs1 = np.arange(len(cloud_masked))
278
+ idxs2 = np.random.choice(len(cloud_masked), n-len(cloud_masked), replace=True)
279
+ idxs = np.concatenate([idxs1, idxs2], axis=0)
280
+ cloud_sampled = cloud_masked[idxs]
281
+ color_sampled = color_masked[idxs]
282
+ cloud_sampled = cloud_sampled.astype(np.float32)
283
+ color_sampled = color_sampled.astype(np.float32)
284
+
285
+ if visualize:
286
+ visualize_cloud(cloud_sampled)
287
+
288
+ return cloud_sampled
289
+
290
+ def get_point_clouds(rs_list, n=20000, visualize=False):
291
+ """
292
+ Get point clouds from multiple RealSense cameras.
293
+
294
+ Args:
295
+ rs_list: A list of RealsenseAPI() objects, each one corresponds to one RealSense camera
296
+ n: Number of points to sample from each point cloud (default: 20000)
297
+ visualize: Whether to visualize the point clouds (default: False)
298
+
299
+ Returns:
300
+ clouds: A list of numpy arrays, each with shape (N, 3) representing a point cloud
301
+ from one of the cameras
302
+ """
303
+ clouds = []
304
+ for rs in rs_list:
305
+ clouds.append(get_and_process_data_cam(rs, n, visualize))
306
+ return clouds # a list of (N, 3) numpy array
307
+
308
+ def get_pcd_obs(rs_list, calibration_list, ee_pose):
309
+ clouds_list = get_point_clouds(rs_list, n=10000, visualize=False)
310
+
311
+ transformed_point_clouds = []
312
+ for cloud, calib in zip(clouds_list, calibration_list):
313
+ point_cloud_xyz = np.concatenate([cloud, np.ones((cloud.shape[0], 1))], axis=1) # (N, 4)
314
+ if type(calib) is tuple:
315
+ ee_T_cam = calib[0]
316
+ r_T_ee, _ = computeT(ee_pose)
317
+ current_point_cloud = r_T_ee @ ee_T_cam @ point_cloud_xyz.T
318
+ else:
319
+ current_point_cloud = calib @ point_cloud_xyz.T
320
+ current_point_cloud = current_point_cloud.T[:, :3]
321
+ transformed_point_clouds.append(current_point_cloud)
322
+ # Merge all transformed point clouds into a single array
323
+ if len(transformed_point_clouds) > 0:
324
+ merged_cloud = np.vstack(transformed_point_clouds)
325
+ else:
326
+ merged_cloud = np.empty((0, 3))
327
+ return merged_cloud