yayalong commited on
Commit
dec6959
·
verified ·
1 Parent(s): da4143a

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. WORKSPACE_MEMORY.md +0 -0
  2. third_party/tuntunclaw/graspnet-baseline/doc/example_data/meta.mat +0 -0
  3. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/about.rst +28 -0
  4. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/conf.py +58 -0
  5. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_check_data.rst +8 -0
  6. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_convert.rst +62 -0
  7. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_eval.rst +73 -0
  8. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_generate_rectangle_labels.rst +26 -0
  9. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_loadGrasp.rst +30 -0
  10. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_nms.rst +112 -0
  11. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_vis.rst +39 -0
  12. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/grasp_format.rst +178 -0
  13. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.rst +46 -0
  14. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.dexnet.grasping.meshpy.rst +54 -0
  15. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.dexnet.grasping.rst +70 -0
  16. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.dexnet.rst +38 -0
  17. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.rst +86 -0
  18. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/index.rst +48 -0
  19. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/install.rst +61 -0
  20. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/modules.rst +7 -0
  21. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/__init__.py +0 -0
  22. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/config.py +18 -0
  23. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/LICENSE +18 -0
  24. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/__init__.py +24 -0
  25. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/abstractstatic.py +30 -0
  26. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/constants.py +44 -0
  27. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/__init__.py +20 -0
  28. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/contacts.py +703 -0
  29. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/grasp.py +1127 -0
  30. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/grasp_quality_config.py +201 -0
  31. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/grasp_quality_function.py +226 -0
  32. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/graspable_object.py +232 -0
  33. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/LICENSE +201 -0
  34. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/__init__.py +26 -0
  35. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/mesh.py +1957 -0
  36. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/obj_file.py +150 -0
  37. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/sdf.py +773 -0
  38. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/sdf_file.py +127 -0
  39. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/stable_pose.py +86 -0
  40. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/quality.py +819 -0
  41. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/eval_utils.py +389 -0
  42. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/pose.py +94 -0
  43. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/rotation.py +142 -0
  44. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/trans3d.py +62 -0
  45. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/utils.py +807 -0
  46. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/vis.py +383 -0
  47. third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/xmlhandler.py +158 -0
  48. third_party/tuntunclaw/manipulator_grasp/arm/__init__.py +0 -0
  49. third_party/tuntunclaw/manipulator_grasp/utils/__init__.py +0 -0
  50. third_party/tuntunclaw/manipulator_grasp/utils/mj.py +96 -0
WORKSPACE_MEMORY.md ADDED
The diff for this file is too large to render. See raw diff
 
third_party/tuntunclaw/graspnet-baseline/doc/example_data/meta.mat ADDED
Binary file (881 Bytes). View file
 
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/about.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ About graspnetAPI
2
+ =================
3
+
4
+ .. image:: _static/graspnetlogo1-blue.png
5
+
6
+ GraspNet is an open project for general object grasping that is continuously enriched. Currently we release GraspNet-1Billion, a large-scale benchmark for general object grasping, as well as other related areas (e.g. 6D pose estimation, unseen object segmentation, etc.). graspnetAPI is a Python API that assists in loading, parsing and visualizing the annotations in GraspNet. Please visit graspnet website_ for more information on GraspNet, including for the data, paper, and tutorials. The exact format of the annotations is also described on the GraspNet website. In addition to this API, please download both the GraspNet images and annotations in order to run the demo.
7
+
8
+ .. _website: https://graspnet.net/
9
+
10
+
11
+ Resources
12
+ ---------
13
+ - Documentations_
14
+ - PDF_Documentations_
15
+ - Website_
16
+ - Code_
17
+
18
+ .. _Code: https://github.com/graspnet/graspnetapi
19
+
20
+ .. _Documentations: https://graspnetapi.readthedocs.io/en/latest/
21
+
22
+ .. _PDF_Documentations: https://graspnetapi.readthedocs.io/_/downloads/en/latest/pdf/
23
+
24
+ .. _Website: https://graspnet.net/
25
+
26
+ License
27
+ -------
28
+ graspnetAPI is licensed under the none commercial CC4.0 license [see https://graspnet.net/about]
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/conf.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # This file only contains a selection of the most common options. For a full
4
+ # list see the documentation:
5
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
6
+
7
+ # -- Path setup --------------------------------------------------------------
8
+
9
+ # If extensions (or modules to document with autodoc) are in another directory,
10
+ # add these directories to sys.path here. If the directory is relative to the
11
+ # documentation root, use os.path.abspath to make it absolute, like shown here.
12
+ #
13
+ import os
14
+ import sys
15
+ sys.path.insert(0, os.path.abspath('../../graspnetAPI'))
16
+
17
+
18
+ # -- Project information -----------------------------------------------------
19
+
20
+ project = 'graspnetAPI'
21
+ copyright = '2021, MVIG, Shanghai Jiao Tong University'
22
+ author = 'graspnet'
23
+
24
+ # The full version, including alpha/beta/rc tags
25
+ release = '1.2.11'
26
+
27
+
28
+ # -- General configuration ---------------------------------------------------
29
+
30
+ # Add any Sphinx extension module names here, as strings. They can be
31
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
32
+ # ones.
33
+ extensions = ['sphinx.ext.autodoc',
34
+ 'sphinx.ext.todo',
35
+ 'sphinx.ext.viewcode'
36
+ ]
37
+
38
+ # Add any paths that contain templates here, relative to this directory.
39
+ templates_path = ['_templates']
40
+
41
+ # List of patterns, relative to source directory, that match files and
42
+ # directories to ignore when looking for source files.
43
+ # This pattern also affects html_static_path and html_extra_path.
44
+ exclude_patterns = []
45
+
46
+
47
+ # -- Options for HTML output -------------------------------------------------
48
+
49
+ # The theme to use for HTML and HTML Help pages. See the documentation for
50
+ # a list of builtin themes.
51
+ #
52
+ html_theme = 'sphinx_rtd_theme'
53
+
54
+ # Add any paths that contain custom static files (such as style sheets) here,
55
+ # relative to this directory. They are copied after the builtin static files,
56
+ # so a file named "default.css" will overwrite the builtin "default.css".
57
+ html_static_path = ['_static']
58
+ master_doc = 'index'
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_check_data.rst ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .. _example_check_data:
2
+
3
+ Check Dataset Files
4
+ ===================
5
+
6
+ You can check if there is any missing file in the dataset by the following code.
7
+
8
+ .. literalinclude:: ../../examples/exam_check_data.py
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_convert.rst ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _example_vis:
2
+
3
+ Convert Labels between rectangle format and 6d format
4
+ =====================================================
5
+
6
+ Get a GraspNet instance.
7
+
8
+ .. literalinclude:: ../../examples/exam_convert.py
9
+ :lines: 4-22
10
+
11
+ Convert rectangle format to 6d format
12
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
13
+
14
+ First, load rectangle labels from dataset.
15
+
16
+ .. literalinclude:: ../../examples/exam_convert.py
17
+ :lines: 24-25
18
+
19
+ **Convert a single RectGrasp to Grasp.**
20
+
21
+ .. note:: This conversion may fail due to invalid depth information.
22
+
23
+ .. literalinclude:: ../../examples/exam_convert.py
24
+ :lines: 27-42
25
+
26
+ Before Conversion:
27
+
28
+ .. image:: _static/convert_single_before.png
29
+
30
+ After Conversion:
31
+
32
+ .. image:: _static/convert_single_after.png
33
+
34
+ **Convert RectGraspGroup to GraspGroup.**
35
+
36
+ .. literalinclude:: ../../examples/exam_convert.py
37
+ :lines: 44-56
38
+
39
+ Before Conversion:
40
+
41
+ .. image:: _static/convert_rect_before.png
42
+
43
+ After Conversion:
44
+
45
+ .. image:: _static/convert_rect_after.png
46
+
47
+ Convert 6d format to rectangle format
48
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
49
+
50
+ .. note:: Grasp to RectGrasp conversion is not applicable as only very few 6d grasp can be converted to rectangle grasp.
51
+
52
+ .. literalinclude:: ../../examples/exam_convert.py
53
+ :lines: 58-
54
+
55
+ Before Conversion:
56
+
57
+ .. image:: _static/convert_6d_before.png
58
+
59
+ After Conversion:
60
+
61
+ .. image:: _static/convert_6d_after.png
62
+
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_eval.rst ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _example_eval:
2
+
3
+ Evaluation
4
+ ==========
5
+
6
+ Data Preparation
7
+ ^^^^^^^^^^^^^^^^
8
+
9
+ The first step of evaluation is to prepare your own results.
10
+ You need to run your code and generate a `GraspGroup` for each image in each scene.
11
+ Then call the `save_npy` function of `GraspGroup` to dump the results.
12
+
13
+ To generate a `GraspGroup` and save it, you can directly input a 2D numpy array for the `GraspGroup` class:
14
+ ::
15
+
16
+ gg=GraspGroup(np.array([[score_1, width_1, height_1, depth_1, rotation_matrix_1(9), translation_1(3), object_id_1],
17
+ [score_2, width_2, height_2, depth_2, rotation_matrix_2(9), translation_2(3), object_id_2],
18
+ ...,
19
+ [score_N, width_N, height_N, depth_N, rotation_matrix_N(9), translation_N(3), object_id_N]]
20
+ ))
21
+ gg.save_npy(save_path)
22
+
23
+ where your algorithm predicts N grasp poses for an image. For the `object_id`, you can simply input `0`. For the meaning of other entries, you should refer to the doc for Grasp Label Format-API Loaded Labels
24
+
25
+ The file structure of dump folder should be as follows:
26
+
27
+ ::
28
+
29
+ |-- dump_folder
30
+ |-- scene_0100
31
+ | |-- kinect
32
+ | | |
33
+ | | --- 0000.npy to 0255.npy
34
+ | |
35
+ | --- realsense
36
+ | |
37
+ | --- 0000.npy to 0255.npy
38
+ |
39
+ |-- scene_0101
40
+ |
41
+ ...
42
+ |
43
+ --- scene_0189
44
+
45
+ You can choose to generate dump files for only one camera, there will be no error for doing that.
46
+
47
+ Evaluation API
48
+ ^^^^^^^^^^^^^^
49
+
50
+ Get GraspNetEval instances.
51
+
52
+ .. literalinclude:: ../../examples/exam_eval.py
53
+ :lines: 4-17
54
+
55
+ Evaluate A Single Scene
56
+ -----------------------
57
+
58
+ .. literalinclude:: ../../examples/exam_eval.py
59
+ :lines: 19-23
60
+
61
+ Evaluate All Scenes
62
+ -------------------
63
+
64
+ .. literalinclude:: ../../examples/exam_eval.py
65
+ :lines: 25-27
66
+
67
+ Evaluate 'Seen' Split
68
+ ---------------------
69
+
70
+ .. literalinclude:: ../../examples/exam_eval.py
71
+ :lines: 29-31
72
+
73
+
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_generate_rectangle_labels.rst ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _example_generate_rectangle_labels:
2
+
3
+ Generating Rectangle Grasp Labels
4
+ =================================
5
+
6
+ You can generate the rectangle grasp labels by yourself.
7
+
8
+ Import necessary libs:
9
+
10
+ .. literalinclude:: ../../examples/exam_generate_rectangle_grasp.py
11
+ :lines: 4-11
12
+
13
+ Setup how many processes to use in generating the labels.
14
+
15
+ .. literalinclude:: ../../examples/exam_generate_rectangle_grasp.py
16
+ :lines: 13-15
17
+
18
+ The function to generate labels.
19
+
20
+ .. literalinclude:: ../../examples/exam_generate_rectangle_grasp.py
21
+ :lines: 17-31
22
+
23
+ Run the function for each scene and camera.
24
+
25
+ .. literalinclude:: ../../examples/exam_generate_rectangle_grasp.py
26
+ :lines: 33-52
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_loadGrasp.rst ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _example_loadGrasp:
2
+
3
+ Loading Grasp Labels
4
+ ====================
5
+
6
+ Both `6d` and `rect` format labels can be loaded.
7
+
8
+ First, import relative libs.
9
+
10
+ .. literalinclude:: ../../examples/exam_loadGrasp.py
11
+ :lines: 4-7
12
+
13
+ Then, get a GraspNet instance and setup parameters.
14
+
15
+ .. literalinclude:: ../../examples/exam_loadGrasp.py
16
+ :lines: 11-19
17
+
18
+ Load GraspLabel in `6d` format and visulize the result.
19
+
20
+ .. literalinclude:: ../../examples/exam_loadGrasp.py
21
+ :lines: 21-29
22
+
23
+ .. image:: _static/6d_example.png
24
+
25
+ Load GraspLabel in `rect` format and visulize the result.
26
+
27
+ .. literalinclude:: ../../examples/exam_loadGrasp.py
28
+ :lines: 31-40
29
+
30
+ .. image:: _static/rect_example.png
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_nms.rst ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _example_nms:
2
+
3
+ Apply NMS on Grasps
4
+ ===================
5
+
6
+
7
+ Get a GraspNet instance.
8
+
9
+ .. literalinclude:: ../../examples/exam_nms.py
10
+ :lines: 4-19
11
+
12
+ Loading and visualizing grasp lables before NMS.
13
+
14
+ .. literalinclude:: ../../examples/exam_nms.py
15
+ :lines: 21-29
16
+
17
+ ::
18
+
19
+ 6d grasp:
20
+ ----------
21
+ Grasp Group, Number=90332:
22
+ Grasp: score:0.9000000357627869, width:0.11247877031564713, height:0.019999999552965164, depth:0.029999999329447746, translation:[-0.09166837 -0.16910084 0.39480919]
23
+ rotation:
24
+ [[-0.81045675 -0.57493848 0.11227506]
25
+ [ 0.49874267 -0.77775514 -0.38256073]
26
+ [ 0.30727136 -0.25405255 0.91708326]]
27
+ object id:66
28
+ Grasp: score:0.9000000357627869, width:0.10030215978622437, height:0.019999999552965164, depth:0.019999999552965164, translation:[-0.09166837 -0.16910084 0.39480919]
29
+ rotation:
30
+ [[-0.73440629 -0.67870212 0.0033038 ]
31
+ [ 0.64608938 -0.70059127 -0.3028869 ]
32
+ [ 0.20788456 -0.22030747 0.95302087]]
33
+ object id:66
34
+ Grasp: score:0.9000000357627869, width:0.08487851172685623, height:0.019999999552965164, depth:0.019999999552965164, translation:[-0.10412319 -0.13797761 0.38312319]
35
+ rotation:
36
+ [[ 0.03316294 0.78667939 -0.61647028]
37
+ [-0.47164679 0.55612743 0.68430364]
38
+ [ 0.88116372 0.26806271 0.38947764]]
39
+ object id:66
40
+ ......
41
+ Grasp: score:0.9000000357627869, width:0.11909123510122299, height:0.019999999552965164, depth:0.019999999552965164, translation:[-0.05140382 0.11790846 0.48782501]
42
+ rotation:
43
+ [[-0.71453273 0.63476181 -0.2941435 ]
44
+ [-0.07400083 0.3495101 0.93400562]
45
+ [ 0.69567728 0.68914449 -0.20276351]]
46
+ object id:14
47
+ Grasp: score:0.9000000357627869, width:0.10943549126386642, height:0.019999999552965164, depth:0.019999999552965164, translation:[-0.05140382 0.11790846 0.48782501]
48
+ rotation:
49
+ [[ 0.08162415 0.4604325 -0.88393396]
50
+ [-0.52200603 0.77526748 0.3556262 ]
51
+ [ 0.84902728 0.4323912 0.30362913]]
52
+ object id:14
53
+ Grasp: score:0.9000000357627869, width:0.11654743552207947, height:0.019999999552965164, depth:0.009999999776482582, translation:[-0.05140382 0.11790846 0.48782501]
54
+ rotation:
55
+ [[-0.18380146 0.39686993 -0.89928377]
56
+ [-0.61254776 0.66926688 0.42055583]
57
+ [ 0.76876676 0.62815309 0.12008961]]
58
+ object id:14
59
+ ------------
60
+
61
+ .. image:: _static/before_nms.png
62
+
63
+ Apply nms to GraspGroup and visualizing the result.
64
+
65
+ .. literalinclude:: ../../examples/exam_nms.py
66
+ :lines: 31-38
67
+
68
+ ::
69
+
70
+ grasp after nms:
71
+ ----------
72
+ Grasp Group, Number=358:
73
+ Grasp: score:1.0, width:0.11948642134666443, height:0.019999999552965164, depth:0.03999999910593033, translation:[-0.00363996 0.03692623 0.3311775 ]
74
+ rotation:
75
+ [[ 0.32641056 -0.8457799 0.42203382]
76
+ [-0.68102902 -0.52005678 -0.51550031]
77
+ [ 0.65548128 -0.11915252 -0.74575269]]
78
+ object id:0
79
+ Grasp: score:1.0, width:0.12185929715633392, height:0.019999999552965164, depth:0.009999999776482582, translation:[-0.03486454 0.08384828 0.35117128]
80
+ rotation:
81
+ [[-0.00487804 -0.8475557 0.53068405]
82
+ [-0.27290785 -0.50941664 -0.81609803]
83
+ [ 0.96202785 -0.14880882 -0.22881967]]
84
+ object id:0
85
+ Grasp: score:1.0, width:0.04842342436313629, height:0.019999999552965164, depth:0.019999999552965164, translation:[0.10816982 0.10254505 0.50272578]
86
+ rotation:
87
+ [[-0.98109186 -0.01696888 -0.19279723]
88
+ [-0.1817532 0.42313483 0.88765001]
89
+ [ 0.06651681 0.90590769 -0.41821831]]
90
+ object id:20
91
+ ......
92
+ Grasp: score:0.9000000357627869, width:0.006192661356180906, height:0.019999999552965164, depth:0.009999999776482582, translation:[0.0122985 0.29616502 0.53319722]
93
+ rotation:
94
+ [[-0.26423979 0.39734706 0.87880182]
95
+ [-0.95826042 -0.00504095 -0.28585231]
96
+ [-0.10915259 -0.91765451 0.38209397]]
97
+ object id:46
98
+ Grasp: score:0.9000000357627869, width:0.024634981527924538, height:0.019999999552965164, depth:0.009999999776482582, translation:[0.11430283 0.18761221 0.51991153]
99
+ rotation:
100
+ [[-0.17379239 -0.96953499 0.17262182]
101
+ [-0.9434278 0.11365268 -0.31149188]
102
+ [ 0.28238329 -0.2169912 -0.93443805]]
103
+ object id:70
104
+ Grasp: score:0.9000000357627869, width:0.03459500893950462, height:0.019999999552965164, depth:0.009999999776482582, translation:[0.02079188 0.11184558 0.50796509]
105
+ rotation:
106
+ [[ 0.38108557 -0.27480939 0.88275337]
107
+ [-0.92043257 -0.20266907 0.33425891]
108
+ [ 0.08704928 -0.93989623 -0.33017775]]
109
+ object id:20
110
+ ----------
111
+
112
+ .. image:: _static/after_nms.png
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/example_vis.rst ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _example_vis:
2
+
3
+ Visualization of Dataset
4
+ ========================
5
+
6
+
7
+ Get a GraspNet instance.
8
+
9
+ .. literalinclude:: ../../examples/exam_vis.py
10
+ :lines: 7-14
11
+
12
+
13
+ Show grasp labels on a object.
14
+
15
+ .. literalinclude:: ../../examples/exam_vis.py
16
+ :lines: 16-17
17
+
18
+ .. image:: _static/vis_single.png
19
+
20
+ Show 6D poses of objects in a scene.
21
+
22
+ .. literalinclude:: ../../examples/exam_vis.py
23
+ :lines: 19-20
24
+
25
+ .. image:: _static/vis_6d.png
26
+
27
+ Show Rectangle grasp labels in a scene.
28
+
29
+ .. literalinclude:: ../../examples/exam_vis.py
30
+ :lines: 22-23
31
+
32
+ .. image:: _static/vis_rect.png
33
+
34
+ Show 6D grasp labels in a scene.
35
+
36
+ .. literalinclude:: ../../examples/exam_vis.py
37
+ :lines: 25-26
38
+
39
+ .. image:: _static/vis_grasp.png
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/grasp_format.rst ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. grasp_format:
2
+
3
+ Grasp Label Format
4
+ ==================
5
+
6
+ Raw Label Format
7
+ ----------------
8
+ The raw label is composed of two parts, i.e. labels for all grasp candidates on each object and collision masks for each scene.
9
+
10
+
11
+
12
+ Labels on Objects
13
+ ^^^^^^^^^^^^^^^^^
14
+ The raw label on each object is a list of numpy arrays.
15
+
16
+ ::
17
+
18
+ >>> import numpy as np
19
+ >>> l = np.load('000_labels.npz') # GRASPNET_ROOT/grasp_label/000_labels.npz
20
+ >>> l.files
21
+ ['points', 'offsets', 'collision', 'scores']
22
+ >>> l['points'].shape
23
+ (3459, 3)
24
+ >>> l['offsets'].shape
25
+ (3459, 300, 12, 4, 3)
26
+ >>> l['collision'].shape
27
+ (3459, 300, 12, 4)
28
+ >>> l['collision'].dtype
29
+ dtype('bool')
30
+ >>> l['scores'].shape
31
+ (3459, 300, 12, 4)
32
+ >>> l['scores'][0][0][0][0]
33
+ -1.0
34
+
35
+ - 'points' records the grasp center point coordinates in model frame.
36
+
37
+ - 'offsets' records the in-plane rotation, depth and width of the gripper respectively in the last dimension.
38
+
39
+ - 'collision' records the bool mask for if the grasp pose collides with the model.
40
+
41
+ - 'scores' records the minimum coefficient of friction between the gripper and object to achieve a stable grasp.
42
+
43
+ .. note::
44
+
45
+ In the raw label, the **lower** score the grasp has, the **better** it is. However, -1.0 score means the grasp pose is totally not acceptable.
46
+
47
+ 300, 12, 4 denote view id, in-plane rotation id and depth id respectively. The views are defined here in graspnetAPI/utils/utils.py.
48
+
49
+ .. literalinclude:: ../../graspnetAPI/utils/utils.py
50
+ :lines: 51-58
51
+ :linenos:
52
+
53
+ Collision Masks on Each Scene
54
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
55
+
56
+ Collision mask on each scene is a list of numpy arrays.
57
+
58
+ ::
59
+
60
+ >>> import numpy as np
61
+ >>> c = np.load('collision_labels.npz') # GRASPNET_ROOT/collision_label/scene_0000/collision_labels.npz
62
+ >>> c.files
63
+ ['arr_0', 'arr_4', 'arr_5', 'arr_2', 'arr_3', 'arr_7', 'arr_1', 'arr_8', 'arr_6']
64
+ >>> c['arr_0'].shape
65
+ (487, 300, 12, 4)
66
+ >>> c['arr_0'].dtype
67
+ dtype('bool')
68
+ >>> c['arr_0'][10][20][3]
69
+ array([ True, True, True, True])
70
+
71
+ 'arr_i' is the collision mask for the `i` th object in the `object_id_list.txt` for each scene whose shape is (num_points, 300, 12, 4).
72
+ num_points, 300, 12, 4 denote the number of points in the object, view id, in-plane rotation id and depth id respectively.
73
+
74
+ Users can refer to :py:func:`graspnetAPI.GraspNet.loadGrasp` for more details of how to use the labels.
75
+
76
+ API Loaded Labels
77
+ -----------------
78
+
79
+ Dealing with the raw labels are time-consuming and need high familiarity with graspnet.
80
+ So the API also provides an easy access to the labels.
81
+
82
+ By calling :py:func:`graspnetAPI.GraspNet.loadGrasp`, users can get all the positive grasp labels in a scene with their parameters and scores.
83
+
84
+ There are totally four kinds of data structures for loaded grasp labels: **Grasp**, **GraspGroup**, **RectGrasp** and **RectGraspGroup**.
85
+ The internal data format of each class is a numpy array which is more efficient than the Python list.
86
+ Their definitions are given in grasp.py
87
+
88
+ Example Labels
89
+ ^^^^^^^^^^^^^^
90
+
91
+ Before looking into the details, an example is given below.
92
+
93
+ Loading a GraspGroup instance.
94
+
95
+ .. literalinclude:: ../../examples/exam_grasp_format.py
96
+ :lines: 1-27
97
+
98
+ Users can access elements by index or slice.
99
+
100
+ .. literalinclude:: ../../examples/exam_grasp_format.py
101
+ :lines: 29-35
102
+
103
+ Each element of GraspGroup is a Grasp instance.
104
+ The properties of Grasp can be accessed via provided methods.
105
+
106
+ .. literalinclude:: ../../examples/exam_grasp_format.py
107
+ :lines: 37-46
108
+
109
+ RectGrasp is the class for rectangle grasps. The format is different from Grasp.
110
+ But the provided APIs are similar.
111
+
112
+ .. literalinclude:: ../../examples/exam_grasp_format.py
113
+ :lines: 49-65
114
+
115
+ 6D Grasp
116
+ ^^^^^^^^
117
+ Actually, 17 float numbers are used to define a general 6d grasp.
118
+ The width, height, depth, score and attached object id are also part of the definition.
119
+
120
+ .. note::
121
+
122
+ In the loaded label, the **higher** score the grasp has, the **better** it is which is different from raw labels. Actually, score = 1.1 - raw_score (which is the coefficient of friction)
123
+
124
+ .. literalinclude:: ../../graspnetAPI/graspnet.py
125
+ :lines: 635-637
126
+ :emphasize-lines: 2
127
+
128
+ The detailed defition of each parameter is shown in the figure.
129
+
130
+ .. image:: _static/grasp_definition.png
131
+
132
+ .. literalinclude:: ../../graspnetAPI/grasp.py
133
+ :lines: 14-36
134
+
135
+ 6D Grasp Group
136
+ ^^^^^^^^^^^^^^
137
+
138
+ Usually, there are a lot of grasps in a scene, :py:class:`GraspGroup` is a class for these grasps.
139
+ Compared with :py:class:`Grasp`, :py:class:`GraspGroup` contains a 2D numpy array, the additional dimension is the index for each grasp.
140
+
141
+ .. literalinclude:: ../../graspnetAPI/grasp.py
142
+ :lines: 201-218
143
+
144
+ Common operations on a list such as indexing, slicing and sorting are implemented.
145
+ Besides, one important function is that users can **dump** a GraspGroup into a numpy file and **load** it in another program by calling :py:func:`GraspGroup.save_npy` and :py:func:`GraspGroup.from_npy`.
146
+
147
+ Rectangle Grasp
148
+ ^^^^^^^^^^^^^^^
149
+ 7 float numbers are used to define a general rectangle grasp, i.e. the center point, the open point, height, score and the attached object id.
150
+ The detailed definition of each parameter is shown in the figure above and below and the coordinates for center point and open point are in the pixel frame.
151
+
152
+ .. image:: _static/rect_grasp_definition.png
153
+
154
+ .. literalinclude:: ../../graspnetAPI/grasp.py
155
+ :lines: 553-572
156
+
157
+ Rectangle Grasp Group
158
+ ^^^^^^^^^^^^^^^^^^^^^
159
+
160
+ The format for :py:class:`RectGraspGroup` is similar to that of :py:class:`RectGrasp` and :py:class:`GraspGroup`.
161
+
162
+ .. literalinclude:: ../../graspnetAPI/grasp.py
163
+ :lines: 752-769
164
+
165
+ .. note::
166
+
167
+ We recommend users to access and modify the labels by provided functions although users can also manipulate the data directly but it is **Not Recommended**.
168
+ Please refer to the Python API for more details.
169
+
170
+ Grasp and GraspGroup Transformation
171
+ -----------------------------------
172
+
173
+ Users can transform a Grasp or GraspGroup giving a 4x4 matrix.
174
+
175
+ .. literalinclude:: ../../examples/exam_grasp_format.py
176
+ :lines: 67-95
177
+
178
+ .. image:: _static/transformation.png
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.rst ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ graspnetAPI package
2
+ ===================
3
+
4
+ Subpackages
5
+ -----------
6
+
7
+ .. toctree::
8
+ :maxdepth: 4
9
+
10
+ graspnetAPI.utils
11
+
12
+ Submodules
13
+ ----------
14
+
15
+ graspnetAPI.grasp module
16
+ ------------------------
17
+
18
+ .. automodule:: graspnetAPI.grasp
19
+ :members:
20
+ :undoc-members:
21
+ :show-inheritance:
22
+
23
+ graspnetAPI.graspnet module
24
+ ---------------------------
25
+
26
+ .. automodule:: graspnetAPI.graspnet
27
+ :members:
28
+ :undoc-members:
29
+ :show-inheritance:
30
+
31
+ graspnetAPI.graspnet\_eval module
32
+ ---------------------------------
33
+
34
+ .. automodule:: graspnetAPI.graspnet_eval
35
+ :members:
36
+ :undoc-members:
37
+ :show-inheritance:
38
+
39
+
40
+ Module contents
41
+ ---------------
42
+
43
+ .. automodule:: graspnetAPI
44
+ :members:
45
+ :undoc-members:
46
+ :show-inheritance:
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.dexnet.grasping.meshpy.rst ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ graspnetAPI.utils.dexnet.grasping.meshpy package
2
+ ================================================
3
+
4
+ Submodules
5
+ ----------
6
+
7
+ graspnetAPI.utils.dexnet.grasping.meshpy.mesh module
8
+ ----------------------------------------------------
9
+
10
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.meshpy.mesh
11
+ :members:
12
+ :undoc-members:
13
+ :show-inheritance:
14
+
15
+ graspnetAPI.utils.dexnet.grasping.meshpy.obj\_file module
16
+ ---------------------------------------------------------
17
+
18
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.meshpy.obj_file
19
+ :members:
20
+ :undoc-members:
21
+ :show-inheritance:
22
+
23
+ graspnetAPI.utils.dexnet.grasping.meshpy.sdf module
24
+ ---------------------------------------------------
25
+
26
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.meshpy.sdf
27
+ :members:
28
+ :undoc-members:
29
+ :show-inheritance:
30
+
31
+ graspnetAPI.utils.dexnet.grasping.meshpy.sdf\_file module
32
+ ---------------------------------------------------------
33
+
34
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.meshpy.sdf_file
35
+ :members:
36
+ :undoc-members:
37
+ :show-inheritance:
38
+
39
+ graspnetAPI.utils.dexnet.grasping.meshpy.stable\_pose module
40
+ ------------------------------------------------------------
41
+
42
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.meshpy.stable_pose
43
+ :members:
44
+ :undoc-members:
45
+ :show-inheritance:
46
+
47
+
48
+ Module contents
49
+ ---------------
50
+
51
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.meshpy
52
+ :members:
53
+ :undoc-members:
54
+ :show-inheritance:
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.dexnet.grasping.rst ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ graspnetAPI.utils.dexnet.grasping package
2
+ =========================================
3
+
4
+ Subpackages
5
+ -----------
6
+
7
+ .. toctree::
8
+ :maxdepth: 4
9
+
10
+ graspnetAPI.utils.dexnet.grasping.meshpy
11
+
12
+ Submodules
13
+ ----------
14
+
15
+ graspnetAPI.utils.dexnet.grasping.contacts module
16
+ -------------------------------------------------
17
+
18
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.contacts
19
+ :members:
20
+ :undoc-members:
21
+ :show-inheritance:
22
+
23
+ graspnetAPI.utils.dexnet.grasping.grasp module
24
+ ----------------------------------------------
25
+
26
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.grasp
27
+ :members:
28
+ :undoc-members:
29
+ :show-inheritance:
30
+
31
+ graspnetAPI.utils.dexnet.grasping.grasp\_quality\_config module
32
+ ---------------------------------------------------------------
33
+
34
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.grasp_quality_config
35
+ :members:
36
+ :undoc-members:
37
+ :show-inheritance:
38
+
39
+ graspnetAPI.utils.dexnet.grasping.grasp\_quality\_function module
40
+ -----------------------------------------------------------------
41
+
42
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.grasp_quality_function
43
+ :members:
44
+ :undoc-members:
45
+ :show-inheritance:
46
+
47
+ graspnetAPI.utils.dexnet.grasping.graspable\_object module
48
+ ----------------------------------------------------------
49
+
50
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.graspable_object
51
+ :members:
52
+ :undoc-members:
53
+ :show-inheritance:
54
+
55
+ graspnetAPI.utils.dexnet.grasping.quality module
56
+ ------------------------------------------------
57
+
58
+ .. automodule:: graspnetAPI.utils.dexnet.grasping.quality
59
+ :members:
60
+ :undoc-members:
61
+ :show-inheritance:
62
+
63
+
64
+ Module contents
65
+ ---------------
66
+
67
+ .. automodule:: graspnetAPI.utils.dexnet.grasping
68
+ :members:
69
+ :undoc-members:
70
+ :show-inheritance:
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.dexnet.rst ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ graspnetAPI.utils.dexnet package
2
+ ================================
3
+
4
+ Subpackages
5
+ -----------
6
+
7
+ .. toctree::
8
+ :maxdepth: 4
9
+
10
+ graspnetAPI.utils.dexnet.grasping
11
+
12
+ Submodules
13
+ ----------
14
+
15
+ graspnetAPI.utils.dexnet.abstractstatic module
16
+ ----------------------------------------------
17
+
18
+ .. automodule:: graspnetAPI.utils.dexnet.abstractstatic
19
+ :members:
20
+ :undoc-members:
21
+ :show-inheritance:
22
+
23
+ graspnetAPI.utils.dexnet.constants module
24
+ -----------------------------------------
25
+
26
+ .. automodule:: graspnetAPI.utils.dexnet.constants
27
+ :members:
28
+ :undoc-members:
29
+ :show-inheritance:
30
+
31
+
32
+ Module contents
33
+ ---------------
34
+
35
+ .. automodule:: graspnetAPI.utils.dexnet
36
+ :members:
37
+ :undoc-members:
38
+ :show-inheritance:
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/graspnetAPI.utils.rst ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ graspnetAPI.utils package
2
+ =========================
3
+
4
+ Subpackages
5
+ -----------
6
+
7
+ .. toctree::
8
+ :maxdepth: 4
9
+
10
+ graspnetAPI.utils.dexnet
11
+
12
+ Submodules
13
+ ----------
14
+
15
+ graspnetAPI.utils.config module
16
+ -------------------------------
17
+
18
+ .. automodule:: graspnetAPI.utils.config
19
+ :members:
20
+ :undoc-members:
21
+ :show-inheritance:
22
+
23
+ graspnetAPI.utils.eval\_utils module
24
+ ------------------------------------
25
+
26
+ .. automodule:: graspnetAPI.utils.eval_utils
27
+ :members:
28
+ :undoc-members:
29
+ :show-inheritance:
30
+
31
+ graspnetAPI.utils.pose module
32
+ -----------------------------
33
+
34
+ .. automodule:: graspnetAPI.utils.pose
35
+ :members:
36
+ :undoc-members:
37
+ :show-inheritance:
38
+
39
+ graspnetAPI.utils.rotation module
40
+ ---------------------------------
41
+
42
+ .. automodule:: graspnetAPI.utils.rotation
43
+ :members:
44
+ :undoc-members:
45
+ :show-inheritance:
46
+
47
+ graspnetAPI.utils.trans3d module
48
+ --------------------------------
49
+
50
+ .. automodule:: graspnetAPI.utils.trans3d
51
+ :members:
52
+ :undoc-members:
53
+ :show-inheritance:
54
+
55
+ graspnetAPI.utils.utils module
56
+ ------------------------------
57
+
58
+ .. automodule:: graspnetAPI.utils.utils
59
+ :members:
60
+ :undoc-members:
61
+ :show-inheritance:
62
+
63
+ graspnetAPI.utils.vis module
64
+ ----------------------------
65
+
66
+ .. automodule:: graspnetAPI.utils.vis
67
+ :members:
68
+ :undoc-members:
69
+ :show-inheritance:
70
+
71
+ graspnetAPI.utils.xmlhandler module
72
+ -----------------------------------
73
+
74
+ .. automodule:: graspnetAPI.utils.xmlhandler
75
+ :members:
76
+ :undoc-members:
77
+ :show-inheritance:
78
+
79
+
80
+ Module contents
81
+ ---------------
82
+
83
+ .. automodule:: graspnetAPI.utils
84
+ :members:
85
+ :undoc-members:
86
+ :show-inheritance:
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/index.rst ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. graspnetAPI documentation master file, created by
2
+ sphinx-quickstart on Tue Nov 3 13:04:51 2020.
3
+ You can adapt this file completely to your liking, but it should at least
4
+ contain the root `toctree` directive.
5
+
6
+ Welcome to graspnetAPI's documentation!
7
+ =======================================
8
+
9
+ .. toctree::
10
+ :maxdepth: 2
11
+ :caption: Contents:
12
+
13
+ about
14
+ install
15
+ grasp_format
16
+
17
+ Examples
18
+ =========
19
+
20
+ .. toctree::
21
+ :maxdepth: 1
22
+ :caption: Examples
23
+
24
+ example_check_data
25
+ example_generate_rectangle_labels
26
+ example_loadGrasp
27
+ example_vis
28
+ example_nms
29
+ example_convert
30
+ example_eval
31
+
32
+
33
+ Python API
34
+ ==========
35
+
36
+ .. toctree::
37
+ :maxdepth: 1
38
+ :caption: Modules
39
+
40
+ graspnetAPI
41
+ graspnetAPI.utils
42
+
43
+ Indices and tables
44
+ ==================
45
+
46
+ * :ref:`genindex`
47
+ * :ref:`modindex`
48
+ * :ref:`search`
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/install.rst ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Installation
2
+ ============
3
+
4
+ .. note::
5
+
6
+ Only Python 3 on Linux is supported.
7
+
8
+ Prerequisites
9
+ ^^^^^^^^^^^^^
10
+
11
+ Python version under 3.6 is not tested.
12
+
13
+ Dataset
14
+ ^^^^^^^
15
+
16
+ Download
17
+ --------
18
+
19
+ Download the dataset at https://graspnet.net/datasets.html
20
+
21
+ Unzip
22
+ -----
23
+
24
+ Unzip the files as shown in https://graspnet.net/datasets.html.
25
+
26
+ Rectangle Grasp Labels
27
+ ----------------------
28
+ Rectangle grasp labels are optional if you need labels in this format.
29
+ You can both generate the labels or download the file_.
30
+
31
+ If you want to generate the labels by yourself, you may refer to :ref:`example_generate_rectangle_labels`.
32
+
33
+ .. note::
34
+
35
+ Generating rectangle grasp labels may take a long time.
36
+
37
+ After generating the labels or unzipping the labels, you need to run copy_rect_labels.py_ to copy rectangle grasp labels to corresponding folders.
38
+
39
+ .. _copy_rect_labels.py: https://github.com/graspnet/graspnetAPI/blob/master/copy_rect_labels.py
40
+
41
+ .. _file: https://graspnet.net/datasets.html
42
+
43
+ Dexnet Model Cache
44
+ ------------------
45
+
46
+ Dexnet model cache is optional without which the evaluation will be much slower(about 10x time slower).
47
+ You can both download the file or generate it by yourself by running gen_pickle_dexmodel.py_(recommended).
48
+
49
+ .. _gen_pickle_dexmodel.py: https://github.com/graspnet/graspnetAPI/blob/master/gen_pickle_dexmodel.py
50
+
51
+ Install API
52
+ ^^^^^^^^^^^
53
+ You may install using pip::
54
+
55
+ pip install graspnetAPI
56
+
57
+ You can also install from source::
58
+
59
+ git clone https://github.com/graspnet/graspnetAPI.git
60
+ cd graspnetAPI/
61
+ pip install .
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/docs/source/modules.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ graspnetAPI
2
+ ===========
3
+
4
+ .. toctree::
5
+ :maxdepth: 4
6
+
7
+ graspnetAPI
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/__init__.py ADDED
File without changes
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/config.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def get_config():
2
+ '''
3
+ - return the config dict
4
+ '''
5
+ config = dict()
6
+ force_closure = dict()
7
+ force_closure['quality_method'] = 'force_closure'
8
+ force_closure['num_cone_faces'] = 8
9
+ force_closure['soft_fingers'] = 1
10
+ force_closure['quality_type'] = 'quasi_static'
11
+ force_closure['all_contacts_required']= 1
12
+ force_closure['check_approach'] = False
13
+ force_closure['torque_scaling'] = 0.01
14
+ force_closure['wrench_norm_thresh'] = 0.001
15
+ force_closure['wrench_regularizer'] = 0.0000000001
16
+ config['metrics'] = dict()
17
+ config['metrics']['force_closure'] = force_closure
18
+ return config
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/LICENSE ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
2
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
3
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
4
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
5
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
6
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
7
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
8
+
9
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
10
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
11
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
12
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13
+
14
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
17
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
18
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # -*- coding: utf-8 -*-
2
+ # """
3
+ # Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ # Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ # research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ # hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ # paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ # Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ # 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ # IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ # INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ # THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ # REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ # PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ # HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ # MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ # """
22
+ # # from .constants import *
23
+ # # from .abstractstatic import abstractstatic
24
+ # # from .api import DexNet
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/abstractstatic.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ """
22
+ # Abstact static methods
23
+ # Source: https://stackoverflow.com/questions/4474395/staticmethod-and-abc-abstractmethod-will-it-blend
24
+
25
+ class abstractstatic(staticmethod):
26
+ __slots__ = ()
27
+ def __init__(self, function):
28
+ super(abstractstatic, self).__init__(function)
29
+ function.__isabstractmethod__ = True
30
+ __isabstractmethod__ = True
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/constants.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ """
22
+ # Grasp contact params
23
+ NO_CONTACT_DIST = 0.2 # distance to points that are not in contact for window extraction
24
+ WIN_DIST_LIM = 0.02 # limits for window plotting
25
+
26
+ # File extensions
27
+ HDF5_EXT = '.hdf5'
28
+ OBJ_EXT = '.obj'
29
+ OFF_EXT = '.off'
30
+ STL_EXT = '.stl'
31
+ SDF_EXT = '.sdf'
32
+ URDF_EXT = '.urdf'
33
+
34
+ # Tags for intermediate files
35
+ DEC_TAG = '_dec'
36
+ PROC_TAG = '_proc'
37
+
38
+ # Solver default max iterations
39
+ DEF_MAX_ITER = 100
40
+
41
+ # Access levels for db
42
+ READ_ONLY_ACCESS = 'READ_ONLY'
43
+ READ_WRITE_ACCESS = 'READ_WRITE'
44
+ WRITE_ACCESS = 'WRITE'
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
3
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
4
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
5
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
6
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
7
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
8
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
9
+
10
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
11
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
12
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
13
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
+
15
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
18
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
19
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
20
+ """
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/contacts.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ """
22
+ """
23
+ Contact class that encapsulates friction cone and surface window computation.
24
+ Authors: Brian Hou and Jeff Mahler
25
+ """
26
+
27
+ from abc import ABCMeta, abstractmethod
28
+ import itertools as it
29
+ import logging
30
+ import numpy as np
31
+ from skimage.restoration import denoise_bilateral
32
+
33
+ from autolab_core import RigidTransform
34
+
35
+ from ..constants import NO_CONTACT_DIST
36
+ from ..constants import WIN_DIST_LIM
37
+
38
+ import IPython
39
+ import matplotlib.pyplot as plt
40
+ from sklearn.decomposition import PCA
41
+
42
+
43
+ # class Contact(metaclass=ABCMeta): # for python3
44
+ class Contact:
45
+ """ Abstract class for contact models. """
46
+ __metaclass__ = ABCMeta
47
+
48
+ class Contact3D(Contact):
49
+ """ 3D contact points.
50
+
51
+ Attributes
52
+ ----------
53
+ graspable : :obj:`GraspableObject3D`
54
+ object to use to get contact information
55
+ contact_point : 3x1 :obj:`numpy.ndarray`
56
+ point of contact on the object
57
+ in_direction : 3x1 :obj:`numpy.ndarray`
58
+ direction along which contact was made
59
+ normal : normalized 3x1 :obj:`numpy.ndarray`
60
+ surface normal at the contact point
61
+ """
62
+
63
+ def __init__(self, graspable, contact_point, in_direction=None):
64
+ self.graspable_ = graspable
65
+ self.point_ = contact_point # in world coordinates
66
+
67
+ # cached attributes
68
+ self.in_direction_ = in_direction # inward facing grasp axis
69
+ self.friction_cone_ = None
70
+ self.normal_ = None # outward facing normal
71
+ self.surface_info_ = None
72
+
73
+ self._compute_normal()
74
+
75
+ @property
76
+ def graspable(self):
77
+ return self.graspable_
78
+
79
+ @property
80
+ def point(self):
81
+ return self.point_
82
+
83
+ @property
84
+ def normal(self):
85
+ return self.normal_
86
+
87
+ @normal.setter
88
+ def normal(self, normal):
89
+ self.normal_ = normal
90
+
91
+ @property
92
+ def in_direction(self):
93
+ return self.in_direction_
94
+
95
+ def _compute_normal(self):
96
+ """Compute outward facing normal at contact, according to in_direction.
97
+ Indexes into the SDF grid coordinates to lookup the normal info.
98
+ """
99
+ # tf to grid
100
+ as_grid = self.graspable.sdf.transform_pt_obj_to_grid(self.point)
101
+ on_surface, _ = self.graspable.sdf.on_surface(as_grid)
102
+ if not on_surface:
103
+ logging.debug('Contact point not on surface')
104
+ return None
105
+
106
+ # compute outward facing normal from SDF
107
+ normal = self.graspable.sdf.surface_normal(as_grid)
108
+
109
+ # flip normal to point outward if in_direction is defined
110
+ if self.in_direction_ is not None and np.dot(self.in_direction_, normal) > 0:
111
+ normal = -normal
112
+
113
+ # transform to world frame
114
+ normal = self.graspable.sdf.transform_pt_grid_to_obj(normal, direction=True)
115
+ self.normal_ = normal
116
+
117
+ def tangents(self, direction=None, align_axes=True, max_samples=1000):
118
+ """Returns the direction vector and tangent vectors at a contact point.
119
+ The direction vector defaults to the *inward-facing* normal vector at
120
+ this contact.
121
+ The direction and tangent vectors for a right handed coordinate frame.
122
+
123
+ Parameters
124
+ ----------
125
+ direction : 3x1 :obj:`numpy.ndarray`
126
+ direction to find orthogonal plane for
127
+ align_axes : bool
128
+ whether or not to align the tangent plane to the object reference frame
129
+ max_samples : int
130
+ number of samples to use in discrete optimization for alignment of reference frame
131
+
132
+ Returns
133
+ -------
134
+ direction : normalized 3x1 :obj:`numpy.ndarray`
135
+ direction to find orthogonal plane for
136
+ t1 : normalized 3x1 :obj:`numpy.ndarray`
137
+ first tangent vector, x axis
138
+ t2 : normalized 3x1 :obj:`numpy.ndarray`
139
+ second tangent vector, y axis
140
+ """
141
+ # illegal contact, cannot return tangents
142
+ if self.normal_ is None:
143
+ return None, None, None
144
+
145
+ # default to inward pointing normal
146
+ if direction is None:
147
+ direction = -self.normal_
148
+
149
+ # force direction to face inward
150
+ if np.dot(self.normal_, direction) > 0:
151
+ direction = -direction
152
+
153
+ # transform to
154
+ direction = direction.reshape((3, 1)) # make 2D for SVD
155
+
156
+ # get orthogonal plane
157
+ U, _, _ = np.linalg.svd(direction)
158
+
159
+ # U[:, 1:] spans the tanget plane at the contact
160
+ x, y = U[:, 1], U[:, 2]
161
+
162
+ # make sure t1 and t2 obey right hand rule
163
+ z_hat = np.cross(x, y)
164
+ if z_hat.dot(direction) < 0:
165
+ y = -y
166
+ v = x
167
+ w = y
168
+
169
+ # redefine tangent x axis to automatically align with the object x axis
170
+ if align_axes:
171
+ max_ip = 0
172
+ max_theta = 0
173
+ target = np.array([1, 0, 0])
174
+ theta = 0
175
+ d_theta = 2 * np.pi / float(max_samples)
176
+ for i in range(max_samples):
177
+ v = np.cos(theta) * x + np.sin(theta) * y
178
+ if v.dot(target) > max_ip:
179
+ max_ip = v.dot(target)
180
+ max_theta = theta
181
+ theta = theta + d_theta
182
+
183
+ v = np.cos(max_theta) * x + np.sin(max_theta) * y
184
+ w = np.cross(direction.ravel(), v)
185
+ return np.squeeze(direction), v, w
186
+
187
+ def reference_frame(self, align_axes=True):
188
+ """Returns the local reference frame of the contact.
189
+ Z axis in the in direction (or surface normal if not specified)
190
+ X and Y axes in the tangent plane to the direction
191
+
192
+ Parameters
193
+ ----------
194
+ align_axes : bool
195
+ whether or not to align to the object axes
196
+
197
+ Returns
198
+ -------
199
+ :obj:`RigidTransform`
200
+ rigid transformation from contact frame to object frame
201
+ """
202
+ t_obj_contact = self.point
203
+ rz, rx, ry = self.tangents(self.in_direction_, align_axes=align_axes)
204
+ R_obj_contact = np.array([rx, ry, rz]).T
205
+ T_contact_obj = RigidTransform(rotation=R_obj_contact,
206
+ translation=t_obj_contact,
207
+ from_frame='contact', to_frame='obj')
208
+ return T_contact_obj
209
+
210
+ def normal_force_magnitude(self):
211
+ """ Returns the component of the force that the contact would apply along the normal direction.
212
+
213
+ Returns
214
+ -------
215
+ float
216
+ magnitude of force along object surface normal
217
+ """
218
+ normal_force_mag = 1.0
219
+ if self.in_direction_ is not None and self.normal_ is not None:
220
+ in_normal = -self.normal_
221
+ in_direction_norm = self.in_direction_ / np.linalg.norm(self.in_direction_)
222
+ normal_force_mag = np.dot(in_direction_norm, in_normal)
223
+ return max(normal_force_mag, 0.0)
224
+
225
+ def friction_cone(self, num_cone_faces=8, friction_coef=0.5):
226
+ """ Computes the friction cone and normal for a contact point.
227
+
228
+ Parameters
229
+ ----------
230
+ num_cone_faces : int
231
+ number of cone faces to use in discretization
232
+ friction_coef : float
233
+ coefficient of friction at contact point
234
+
235
+ Returns
236
+ -------
237
+ success : bool
238
+ False when cone can't be computed
239
+ cone_support : :obj:`numpy.ndarray`
240
+ array where each column is a vector on the boundary of the cone
241
+ normal : normalized 3x1 :obj:`numpy.ndarray`
242
+ outward facing surface normal
243
+ """
244
+ if self.friction_cone_ is not None and self.normal_ is not None:
245
+ return True, self.friction_cone_, self.normal_
246
+
247
+ # get normal and tangents
248
+ in_normal, t1, t2 = self.tangents()
249
+ if in_normal is None:
250
+ return False, self.friction_cone_, self.normal_
251
+
252
+ friction_cone_valid = True
253
+
254
+ # check whether contact would slip, which is whether or not the tangent force is always
255
+ # greater than the frictional force
256
+ if self.in_direction_ is not None:
257
+ in_direction_norm = self.in_direction_ / np.linalg.norm(self.in_direction_)
258
+ normal_force_mag = self.normal_force_magnitude()
259
+ tan_force_x = np.dot(in_direction_norm, t1)
260
+ tan_force_y = np.dot(in_direction_norm, t2)
261
+ tan_force_mag = np.sqrt(tan_force_x ** 2 + tan_force_y ** 2)
262
+ friction_force_mag = friction_coef * normal_force_mag
263
+
264
+ if friction_force_mag < tan_force_mag:
265
+ logging.debug('Contact would slip')
266
+ return False, self.friction_cone_, self.normal_
267
+
268
+ # set up friction cone
269
+ tan_len = friction_coef
270
+ force = in_normal
271
+ cone_support = np.zeros((3, num_cone_faces))
272
+
273
+ # find convex combinations of tangent vectors
274
+ for j in range(num_cone_faces):
275
+ tan_vec = t1 * np.cos(2 * np.pi * (float(j) / num_cone_faces)) + t2 * np.sin(
276
+ 2 * np.pi * (float(j) / num_cone_faces))
277
+ cone_support[:, j] = force + friction_coef * tan_vec
278
+
279
+ self.friction_cone_ = cone_support
280
+ return True, self.friction_cone_, self.normal_
281
+
282
+ def torques(self, forces):
283
+ """
284
+ Get the torques that can be applied by a set of force vectors at the contact point.
285
+
286
+ Parameters
287
+ ----------
288
+ forces : 3xN :obj:`numpy.ndarray`
289
+ the forces applied at the contact
290
+
291
+ Returns
292
+ -------
293
+ success : bool
294
+ whether or not computation was successful
295
+ torques : 3xN :obj:`numpy.ndarray`
296
+ the torques that can be applied by given forces at the contact
297
+ """
298
+ as_grid = self.graspable.sdf.transform_pt_obj_to_grid(self.point)
299
+ on_surface, _ = self.graspable.sdf.on_surface(as_grid)
300
+ if not on_surface:
301
+ logging.debug('Contact point not on surface')
302
+ return False, None
303
+
304
+ num_forces = forces.shape[1]
305
+ torques = np.zeros([3, num_forces])
306
+ moment_arm = self.graspable.moment_arm(self.point)
307
+ for i in range(num_forces):
308
+ torques[:, i] = np.cross(moment_arm, forces[:, i])
309
+
310
+ return True, torques
311
+
312
+ def surface_window_sdf(self, width=1e-2, num_steps=21):
313
+ """Returns a window of SDF values on the tangent plane at a contact point.
314
+ Used for patch computation.
315
+
316
+ Parameters
317
+ ----------
318
+ width : float
319
+ width of the window in obj frame
320
+ num_steps : int
321
+ number of steps to use along the contact in direction
322
+
323
+ Returns
324
+ -------
325
+ window : NUM_STEPSxNUM_STEPS :obj:`numpy.ndarray`
326
+ array of distances from tangent plane to obj along in direction, False if surface window can't be computed
327
+ """
328
+ in_normal, t1, t2 = self.tangents()
329
+ if in_normal is None: # normal and tangents not found
330
+ return False
331
+
332
+ scales = np.linspace(-width / 2.0, width / 2.0, num_steps)
333
+ window = np.zeros(num_steps ** 2)
334
+ for i, (c1, c2) in enumerate(it.product(scales, repeat=2)):
335
+ curr_loc = self.point + c1 * t1 + c2 * t2
336
+ curr_loc_grid = self.graspable.sdf.transform_pt_obj_to_grid(curr_loc)
337
+ if self.graspable.sdf.is_out_of_bounds(curr_loc_grid):
338
+ window[i] = -1e-2
339
+ continue
340
+
341
+ window[i] = self.graspable.sdf[curr_loc_grid]
342
+ return window.reshape((num_steps, num_steps))
343
+
344
+ def _compute_surface_window_projection(self, u1=None, u2=None, width=1e-2,
345
+ num_steps=21, max_projection=0.1, back_up=0, samples_per_grid=2.0,
346
+ sigma_range=0.1, sigma_spatial=1, direction=None, vis=False,
347
+ compute_weighted_covariance=False,
348
+ disc=False, num_radial_steps=5, debug_objs=None):
349
+ """Compute the projection window onto the basis defined by u1 and u2.
350
+ Params:
351
+ u1, u2 - orthogonal numpy 3 arrays
352
+
353
+ width - float width of the window in obj frame
354
+ num_steps - int number of steps
355
+ max_projection - float maximum amount to search forward for a
356
+ contact (meters)
357
+
358
+ back_up - amount in meters to back up before projecting
359
+ samples_per_grid - float number of samples per grid when finding contacts
360
+ sigma - bandwidth of gaussian filter on window
361
+ direction - dir to do the projection along
362
+ compute_weighted_covariance - whether to return the weighted
363
+ covariance matrix, along with the window
364
+ Returns:
365
+ window - numpy NUM_STEPSxNUM_STEPS array of distances from tangent
366
+ plane to obj, False if surface window can't be computed
367
+ """
368
+ direction, t1, t2 = self.tangents(direction)
369
+ if direction is None: # normal and tangents not found
370
+ raise ValueError('Direction could not be computed')
371
+ if u1 is not None and u2 is not None: # use given basis
372
+ t1, t2 = u1, u2
373
+
374
+ # number of samples used when looking for contacts
375
+ no_contact = NO_CONTACT_DIST
376
+ num_samples = int(samples_per_grid * (max_projection + back_up) / self.graspable.sdf.resolution)
377
+ window = np.zeros(num_steps ** 2)
378
+
379
+ res = width / num_steps
380
+ scales = np.linspace(-width / 2.0 + res / 2.0, width / 2.0 - res / 2.0, num_steps)
381
+ scales_it = it.product(scales, repeat=2)
382
+ if disc:
383
+ scales_it = []
384
+ for i in range(num_steps):
385
+ theta = 2.0 * np.pi / i
386
+ for j in range(num_radial_steps):
387
+ r = (j + 1) * width / num_radial_steps
388
+ p = (r * np.cos(theta), r * np.sin(theta))
389
+ scales_it.append(p)
390
+
391
+ # start computing weighted covariance matrix
392
+ if compute_weighted_covariance:
393
+ cov = np.zeros((3, 3))
394
+ cov_weight = 0
395
+
396
+ if vis:
397
+ ax = plt.gca(projection='3d')
398
+ self.graspable_.sdf.scatter()
399
+
400
+ for i, (c1, c2) in enumerate(scales_it):
401
+ curr_loc = self.point + c1 * t1 + c2 * t2
402
+ curr_loc_grid = self.graspable.sdf.transform_pt_obj_to_grid(curr_loc)
403
+ if self.graspable.sdf.is_out_of_bounds(curr_loc_grid):
404
+ window[i] = no_contact
405
+ continue
406
+
407
+ if vis:
408
+ ax.scatter(curr_loc_grid[0], curr_loc_grid[1], curr_loc_grid[2], s=130, c='y')
409
+
410
+ found, projection_contact = self.graspable._find_projection(
411
+ curr_loc, direction, max_projection, back_up, num_samples, vis=vis)
412
+
413
+ if found:
414
+ # logging.debug('%d found.' %(i))
415
+ sign = direction.dot(projection_contact.point - curr_loc)
416
+ projection = (sign / abs(sign)) * np.linalg.norm(projection_contact.point - curr_loc)
417
+ projection = min(projection, max_projection)
418
+
419
+ if compute_weighted_covariance:
420
+ # weight according to SHOT: R - d_i
421
+ weight = width / np.sqrt(2) - np.sqrt(c1 ** 2 + c2 ** 2)
422
+ diff = (projection_contact.point - self.point).reshape((3, 1))
423
+ cov += weight * np.dot(diff, diff.T)
424
+ cov_weight += weight
425
+ else:
426
+ logging.debug('%d not found.' % (i))
427
+ projection = no_contact
428
+
429
+ window[i] = projection
430
+
431
+ if vis:
432
+ plt.show()
433
+
434
+ if not disc:
435
+ window = window.reshape((num_steps, num_steps)).T # transpose to make x-axis along columns
436
+ if debug_objs is not None:
437
+ debug_objs.append(window)
438
+ # apply bilateral filter
439
+ if sigma_range > 0.0 and sigma_spatial > 0.0:
440
+ window_min_val = np.min(window)
441
+ window_pos = window - window_min_val
442
+ window_pos_blur = denoise_bilateral(window_pos, sigma_range=sigma_range, sigma_spatial=sigma_spatial,
443
+ mode='nearest')
444
+ window = window_pos_blur + window_min_val
445
+ if compute_weighted_covariance:
446
+ if cov_weight > 0:
447
+ return window, cov / cov_weight
448
+ return window, cov
449
+ return window
450
+
451
+ def surface_window_projection_unaligned(self, width=1e-2, num_steps=21,
452
+ max_projection=0.1, back_up=0.0, samples_per_grid=2.0,
453
+ sigma=1.5, direction=None, vis=False):
454
+ """Projects the local surface onto the tangent plane at a contact point. Deprecated.
455
+ """
456
+ return self._compute_surface_window_projection(width=width,
457
+ num_steps=num_steps, max_projection=max_projection,
458
+ back_up=back_up, samples_per_grid=samples_per_grid,
459
+ sigma=sigma, direction=direction, vis=vis)
460
+
461
+ def surface_window_projection(self, width=1e-2, num_steps=21,
462
+ max_projection=0.1, back_up=0.0, samples_per_grid=2.0,
463
+ sigma_range=0.1, sigma_spatial=1, direction=None, compute_pca=False, vis=False,
464
+ debug_objs=None):
465
+ """Projects the local surface onto the tangent plane at a contact point.
466
+
467
+ Parameters
468
+ ----------
469
+ width : float
470
+ width of the window in obj frame
471
+ num_steps : int
472
+ number of steps to use along the in direction
473
+ max_projection : float
474
+ maximum amount to search forward for a contact (meters)
475
+ back_up : float
476
+ amount to back up before finding a contact in meters
477
+ samples_per_grid : float
478
+ number of samples per grid when finding contacts
479
+ sigma_range : float
480
+ bandwidth of bilateral range filter on window
481
+ sigma_spatial : float
482
+ bandwidth of gaussian spatial filter of bilateral filter
483
+ direction : 3x1 :obj:`numpy.ndarray`
484
+ dir to do the projection along
485
+
486
+ Returns
487
+ -------
488
+ window : NUM_STEPSxNUM_STEPS :obj:`numpy.ndarray`
489
+ array of distances from tangent plane to obj, False if surface window can't be computed
490
+ """
491
+ # get initial projection
492
+ direction, t1, t2 = self.tangents(direction)
493
+ window, cov = self._compute_surface_window_projection(t1, t2,
494
+ width=width, num_steps=num_steps,
495
+ max_projection=max_projection,
496
+ back_up=back_up, samples_per_grid=samples_per_grid,
497
+ sigma_range=sigma_range, sigma_spatial=sigma_spatial,
498
+ direction=direction,
499
+ vis=False, compute_weighted_covariance=True,
500
+ debug_objs=debug_objs)
501
+
502
+ if not compute_pca:
503
+ return window
504
+
505
+ # compute principal axis
506
+ pca = PCA()
507
+ pca.fit(cov)
508
+ R = pca.components_
509
+ principal_axis = R[0, :]
510
+ if np.isclose(abs(np.dot(principal_axis, direction)), 1):
511
+ # principal axis is aligned with direction of projection, use secondary axis
512
+ principal_axis = R[1, :]
513
+
514
+ if vis:
515
+ # reshape window
516
+ window = window.reshape((num_steps, num_steps))
517
+
518
+ # project principal axis onto tangent plane (t1, t2) to get u1
519
+ u1t = np.array([np.dot(principal_axis, t1), np.dot(principal_axis, t2)])
520
+ u2t = np.array([-u1t[1], u1t[0]])
521
+ if sigma > 0:
522
+ window = spfilt.gaussian_filter(window, sigma)
523
+ plt.figure()
524
+ plt.title('Principal Axis')
525
+ plt.imshow(window, extent=[0, num_steps - 1, num_steps - 1, 0],
526
+ interpolation='none', cmap=plt.cm.binary)
527
+ plt.colorbar()
528
+ plt.clim(-WIN_DIST_LIM, WIN_DIST_LIM) # fixing color range for visual comparisons
529
+ center = num_steps // 2
530
+ plt.scatter([center, center * u1t[0] + center], [center, -center * u1t[1] + center], color='blue')
531
+ plt.scatter([center, center * u2t[0] + center], [center, -center * u2t[1] + center], color='green')
532
+
533
+ u1 = np.dot(principal_axis, t1) * t1 + np.dot(principal_axis, t2) * t2
534
+ u2 = np.cross(direction, u1) # u2 must be orthogonal to u1 on plane
535
+ u1 = u1 / np.linalg.norm(u1)
536
+ u2 = u2 / np.linalg.norm(u2)
537
+
538
+ window = self._compute_surface_window_projection(u1, u2,
539
+ width=width, num_steps=num_steps,
540
+ max_projection=max_projection,
541
+ back_up=back_up, samples_per_grid=samples_per_grid,
542
+ sigma=sigma, direction=direction, vis=False)
543
+
544
+ # arbitrarily require that right_avg > left_avg (inspired by SHOT)
545
+ left_avg = np.average(window[:, :num_steps // 2])
546
+ right_avg = np.average(window[:, num_steps // 2:])
547
+ if left_avg > right_avg:
548
+ # need to flip both u1 and u2, i.e. rotate 180 degrees
549
+ window = np.rot90(window, k=2)
550
+
551
+ if vis:
552
+ if sigma > 0:
553
+ window = spfilt.gaussian_filter(window, sigma)
554
+ plt.figure()
555
+ plt.title('Tfd')
556
+ plt.imshow(window, extent=[0, num_steps - 1, num_steps - 1, 0],
557
+ interpolation='none', cmap=plt.cm.binary)
558
+ plt.colorbar()
559
+ plt.clim(-WIN_DIST_LIM, WIN_DIST_LIM) # fixing color range for visual comparisons
560
+ plt.show()
561
+
562
+ return window
563
+
564
+ def surface_information(self, width, num_steps, sigma_range=0.1, sigma_spatial=1,
565
+ back_up=0.0, max_projection=0.1, direction=None, debug_objs=None, samples_per_grid=2):
566
+ """
567
+ Returns the local surface window, gradient, and curvature for a single contact.
568
+
569
+ Parameters
570
+ ----------
571
+ width : float
572
+ width of surface window in object frame
573
+ num_steps : int
574
+ number of steps to use along the in direction
575
+ sigma_range : float
576
+ bandwidth of bilateral range filter on window
577
+ sigma_spatial : float
578
+ bandwidth of gaussian spatial filter of bilateral filter
579
+ back_up : float
580
+ amount to back up before finding a contact in meters
581
+ max_projection : float
582
+ maximum amount to search forward for a contact (meters)
583
+ direction : 3x1 :obj:`numpy.ndarray`
584
+ direction along width to render the window
585
+ debug_objs : :obj:`list`
586
+ list to put debugging info into
587
+ samples_per_grid : float
588
+ number of samples per grid when finding contacts
589
+
590
+ Returns
591
+ -------
592
+ surface_window : :obj:`SurfaceWindow`
593
+ window information for local surface patch of contact on the given object
594
+ """
595
+ if self.surface_info_ is not None:
596
+ return self.surface_info_
597
+
598
+ if direction is None:
599
+ direction = self.in_direction_
600
+
601
+ proj_window = self.surface_window_projection(width, num_steps,
602
+ sigma_range=sigma_range, sigma_spatial=sigma_spatial,
603
+ back_up=back_up, max_projection=max_projection,
604
+ samples_per_grid=samples_per_grid,
605
+ direction=direction, vis=False, debug_objs=debug_objs)
606
+
607
+ if proj_window is None:
608
+ raise ValueError('Surface window could not be computed')
609
+
610
+ grad_win = np.gradient(proj_window)
611
+ hess_x = np.gradient(grad_win[0])
612
+ hess_y = np.gradient(grad_win[1])
613
+
614
+ gauss_curvature = np.zeros(proj_window.shape)
615
+ for i in range(num_steps):
616
+ for j in range(num_steps):
617
+ local_hess = np.array([[hess_x[0][i, j], hess_x[1][i, j]],
618
+ [hess_y[0][i, j], hess_y[1][i, j]]])
619
+ # symmetrize
620
+ local_hess = (local_hess + local_hess.T) / 2.0
621
+ # curvature
622
+ gauss_curvature[i, j] = np.linalg.det(local_hess)
623
+
624
+ return SurfaceWindow(proj_window, grad_win, hess_x, hess_y, gauss_curvature)
625
+
626
+ def plot_friction_cone(self, color='y', scale=1.0):
627
+ success, cone, in_normal = self.friction_cone()
628
+
629
+ ax = plt.gca(projection='3d')
630
+ self.graspable.sdf.scatter() # object
631
+ x, y, z = self.graspable.sdf.transform_pt_obj_to_grid(self.point)
632
+ nx, ny, nz = self.graspable.sdf.transform_pt_obj_to_grid(in_normal, direction=True)
633
+ ax.scatter([x], [y], [z], c=color, s=60) # contact
634
+ ax.scatter([x - nx], [y - ny], [z - nz], c=color, s=60) # normal
635
+ if success:
636
+ ax.scatter(x + scale * cone[0], y + scale * cone[1], z + scale * cone[2], c=color, s=40) # cone
637
+
638
+ ax.set_xlim3d(0, self.graspable.sdf.dims_[0])
639
+ ax.set_ylim3d(0, self.graspable.sdf.dims_[1])
640
+ ax.set_zlim3d(0, self.graspable.sdf.dims_[2])
641
+
642
+ return plt.Rectangle((0, 0), 1, 1, fc=color) # return a proxy for legend
643
+
644
+
645
+ class SurfaceWindow:
646
+ """Struct for encapsulating local surface window features.
647
+
648
+ Attributes
649
+ ----------
650
+ proj_win : NxN :obj:`numpy.ndarray`
651
+ the window of distances to a surface (depth image created by orthographic projection)
652
+ grad : NxN :obj:`numpy.ndarray`
653
+ X and Y gradients of the projection window
654
+ hess_x : NxN :obj:`numpy.ndarray`
655
+ hessian, partial derivatives of the X gradient window
656
+ hess_y : NxN :obj:`numpy.ndarray`
657
+ hessian, partial derivatives of the Y gradient window
658
+ gauss_curvature : NxN :obj:`numpy.ndarray`
659
+ gauss curvature at each point (function of hessian determinant)
660
+ """
661
+
662
+ def __init__(self, proj_win, grad, hess_x, hess_y, gauss_curvature):
663
+ self.proj_win_ = proj_win
664
+ self.grad_ = grad
665
+ self.hess_x_ = hess_x
666
+ self.hess_y_ = hess_y
667
+ self.gauss_curvature_ = gauss_curvature
668
+
669
+ @property
670
+ def proj_win_2d(self):
671
+ return self.proj_win_
672
+
673
+ @property
674
+ def proj_win(self):
675
+ return self.proj_win_.flatten()
676
+
677
+ @property
678
+ def grad_x(self):
679
+ return self.grad_[0].flatten()
680
+
681
+ @property
682
+ def grad_y(self):
683
+ return self.grad_[1].flatten()
684
+
685
+ @property
686
+ def grad_x_2d(self):
687
+ return self.grad_[0]
688
+
689
+ @property
690
+ def grad_y_2d(self):
691
+ return self.grad_[1]
692
+
693
+ @property
694
+ def curvature(self):
695
+ return self.gauss_curvature_.flatten()
696
+
697
+ def asarray(self, proj_win_weight=0.0, grad_x_weight=0.0,
698
+ grad_y_weight=0.0, curvature_weight=0.0):
699
+ proj_win = proj_win_weight * self.proj_win
700
+ grad_x = grad_x_weight * self.grad_x
701
+ grad_y = grad_y_weight * self.grad_y
702
+ curvature = curvature_weight * self.gauss_curvature
703
+ return np.append([], [proj_win, grad_x, grad_y, curvature])
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/grasp.py ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # """
3
+ # Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ # Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ # research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ # hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ # paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ # Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ # 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+ #
11
+ # IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ # INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ # THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+ #
16
+ # REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ # PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ # HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ # MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ # """
22
+ # """
23
+ # Grasp class that implements gripper endpoints and grasp functions
24
+ # Authors: Jeff Mahler, with contributions from Jacky Liang and Nikhil Sharma
25
+ # """
26
+ from abc import ABCMeta, abstractmethod
27
+ from copy import deepcopy
28
+ import IPython
29
+ import logging
30
+ import matplotlib.pyplot as plt
31
+ import numpy as np
32
+ from numpy.linalg import inv, norm
33
+ import time
34
+
35
+ from autolab_core import Point, RigidTransform
36
+ from .meshpy import Sdf3D, StablePose
37
+
38
+
39
+ from ..abstractstatic import abstractstatic
40
+ from .contacts import Contact3D
41
+ from .graspable_object import GraspableObject3D
42
+
43
+
44
+ # class Grasp(object, metaclass=ABCMeta):
45
+ class Grasp(object):
46
+ """ Abstract grasp class.
47
+
48
+ Attributes
49
+ ----------
50
+ configuration : :obj:`numpy.ndarray`
51
+ vector specifying the parameters of the grasp (e.g. hand pose, opening width, joint angles, etc)
52
+ frame : :obj:`str`
53
+ string name of grasp reference frame (defaults to obj)
54
+ """
55
+ __metaclass__ = ABCMeta
56
+ samples_per_grid = 2 # global resolution for line of action
57
+
58
+ @abstractmethod
59
+ def close_fingers(self, obj):
60
+ """ Finds the contact points by closing on the given object.
61
+
62
+ Parameters
63
+ ----------
64
+ obj : :obj:`GraspableObject3D`
65
+ object to find contacts on
66
+ """
67
+ pass
68
+
69
+ @abstractmethod
70
+ def configuration(self):
71
+ """ Returns the numpy array representing the hand configuration """
72
+ pass
73
+
74
+ @abstractmethod
75
+ def frame(self):
76
+ """ Returns the string name of the grasp reference frame """
77
+ pass
78
+
79
+ @abstractstatic
80
+ def params_from_configuration(configuration):
81
+ """ Convert configuration vector to a set of params for the class """
82
+ pass
83
+
84
+ @abstractstatic
85
+ def configuration_from_params(*params):
86
+ """ Convert param list to a configuration vector for the class """
87
+ pass
88
+
89
+
90
+ # class PointGrasp(Grasp, metaclass=ABCMeta):
91
+ class PointGrasp(Grasp):
92
+ """ Abstract grasp class for grasps with a point contact model.
93
+
94
+ Attributes
95
+ ----------
96
+ configuration : :obj:`numpy.ndarray`
97
+ vector specifying the parameters of the grasp (e.g. hand pose, opening width, joint angles, etc)
98
+ frame : :obj:`str`
99
+ string name of grasp reference frame (defaults to obj)
100
+ """
101
+ __metaclass__ = ABCMeta
102
+
103
+ @abstractmethod
104
+ def create_line_of_action(g, axis, width, obj, num_samples):
105
+ """ Creates a line of action, or the points in space that the grasp traces out, from a point g in world coordinates on an object.
106
+
107
+ Returns
108
+ -------
109
+ bool
110
+ whether or not successful
111
+ :obj:`list` of :obj:`numpy.ndarray`
112
+ points in 3D space along the line of action
113
+ """
114
+ pass
115
+
116
+ # NOTE: implementation of close_fingers must return success, array of contacts (one per column)
117
+
118
+
119
+ class ParallelJawPtGrasp3D(PointGrasp):
120
+ """ Parallel Jaw point grasps in 3D space.
121
+ """
122
+
123
+ def __init__(self, configuration, max_grasp_depth=0, frame='object', grasp_id=None):
124
+ # get parameters from configuration array
125
+ grasp_center, grasp_axis, grasp_width, grasp_angle, jaw_width, min_grasp_width = \
126
+ ParallelJawPtGrasp3D.params_from_configuration(configuration)
127
+
128
+ self.center_ = grasp_center
129
+ self.axis_ = grasp_axis / np.linalg.norm(grasp_axis)
130
+ self.max_grasp_width_ = grasp_width
131
+ self.jaw_width_ = jaw_width
132
+ self.min_grasp_width_ = min_grasp_width
133
+ self.approach_angle_ = grasp_angle
134
+ self.frame_ = frame
135
+ self.grasp_id_ = grasp_id
136
+ self.max_grasp_depth = max_grasp_depth
137
+
138
+ @property
139
+ def center(self):
140
+ """ :obj:`numpy.ndarray` : 3-vector specifying the center of the jaws """
141
+ return self.center_
142
+
143
+ @center.setter
144
+ def center(self, x):
145
+ self.center_ = x
146
+
147
+ @property
148
+ def axis(self):
149
+ """ :obj:`numpy.ndarray` : normalized 3-vector specifying the line between the jaws """
150
+ return self.axis_
151
+
152
+ @property
153
+ def open_width(self):
154
+ """ float : maximum opening width of the jaws """
155
+ return self.max_grasp_width_
156
+
157
+ @property
158
+ def close_width(self):
159
+ """ float : minimum opening width of the jaws """
160
+ return self.min_grasp_width_
161
+
162
+ @property
163
+ def jaw_width(self):
164
+ """ float : width of the jaws in the tangent plane to the grasp axis """
165
+ return self.jaw_width_
166
+
167
+ @property
168
+ def approach_angle(self):
169
+ """ float : approach angle of the grasp """
170
+ return self.approach_angle_
171
+
172
+ @property
173
+ def configuration(self):
174
+ """ :obj:`numpy.ndarray` : vector specifying the parameters of the grasp as follows
175
+ (grasp_center, grasp_axis, grasp_angle, grasp_width, jaw_width) """
176
+ return ParallelJawPtGrasp3D.configuration_from_params(self.center_, self.axis_, self.max_grasp_width_,
177
+ self.approach_angle_, self.jaw_width_,
178
+ self.min_grasp_width_)
179
+
180
+ @property
181
+ def frame(self):
182
+ """ :obj:`str` : name of grasp reference frame """
183
+ return self.frame_
184
+
185
+ @property
186
+ def id(self):
187
+ """ int : id of grasp """
188
+ return self.grasp_id_
189
+
190
+ @frame.setter
191
+ def frame(self, f):
192
+ self.frame_ = f
193
+
194
+ @approach_angle.setter
195
+ def approach_angle(self, angle):
196
+ """ Set the grasp approach angle """
197
+ self.approach_angle_ = angle
198
+
199
+ @property
200
+ def endpoints(self):
201
+ """
202
+ Returns
203
+ -------
204
+ :obj:`numpy.ndarray`
205
+ location of jaws in 3D space at max opening width """
206
+ return self.center_ - (self.max_grasp_width_ / 2.0) * self.axis_, self.center_ + (
207
+ self.max_grasp_width_ / 2.0) * self.axis_,
208
+
209
+ @staticmethod
210
+ def distance(g1, g2, alpha=0.05):
211
+ """ Evaluates the distance between two grasps.
212
+
213
+ Parameters
214
+ ----------
215
+ g1 : :obj:`ParallelJawPtGrasp3D`
216
+ the first grasp to use
217
+ g2 : :obj:`ParallelJawPtGrasp3D`
218
+ the second grasp to use
219
+ alpha : float
220
+ parameter weighting rotational versus spatial distance
221
+
222
+ Returns
223
+ -------
224
+ float
225
+ distance between grasps g1 and g2
226
+ """
227
+ center_dist = np.linalg.norm(g1.center - g2.center)
228
+ axis_dist = (2.0 / np.pi) * np.arccos(np.abs(g1.axis.dot(g2.axis)))
229
+ return center_dist + alpha * axis_dist
230
+
231
+ @staticmethod
232
+ def configuration_from_params(center, axis, width, angle=0, jaw_width=0, min_width=0):
233
+ """ Converts grasp parameters to a configuration vector. """
234
+ if np.abs(np.linalg.norm(axis) - 1.0) > 1e-5:
235
+ raise ValueError('Illegal grasp axis. Must be norm one')
236
+ configuration = np.zeros(10)
237
+ configuration[0:3] = center
238
+ configuration[3:6] = axis
239
+ configuration[6] = width
240
+ configuration[7] = angle
241
+ configuration[8] = jaw_width
242
+ configuration[9] = min_width
243
+ return configuration
244
+
245
+ @staticmethod
246
+ def params_from_configuration(configuration):
247
+ """ Converts configuration vector into grasp parameters.
248
+
249
+ Returns
250
+ -------
251
+ grasp_center : :obj:`numpy.ndarray`
252
+ center of grasp in 3D space
253
+ grasp_axis : :obj:`numpy.ndarray`
254
+ normalized axis of grasp in 3D space
255
+ max_width : float
256
+ maximum opening width of jaws
257
+ angle : float
258
+ approach angle
259
+ jaw_width : float
260
+ width of jaws
261
+ min_width : float
262
+ minimum closing width of jaws
263
+ """
264
+ if not isinstance(configuration, np.ndarray) or (configuration.shape[0] != 9 and configuration.shape[0] != 10):
265
+ raise ValueError('Configuration must be numpy ndarray of size 9 or 10')
266
+ if configuration.shape[0] == 9:
267
+ min_grasp_width = 0
268
+ else:
269
+ min_grasp_width = configuration[9]
270
+ if np.abs(np.linalg.norm(configuration[3:6]) - 1.0) > 1e-5:
271
+ raise ValueError('Illegal grasp axis. Must be norm one')
272
+ return configuration[0:3], configuration[3:6], configuration[6], configuration[7], configuration[
273
+ 8], min_grasp_width
274
+
275
+ @staticmethod
276
+ def center_from_endpoints(g1, g2):
277
+ """ Grasp center from endpoints as np 3-arrays """
278
+ grasp_center = (g1 + g2) / 2
279
+ return grasp_center
280
+
281
+ @staticmethod
282
+ def axis_from_endpoints(g1, g2):
283
+ """ Normalized axis of grasp from endpoints as np 3-arrays """
284
+ grasp_axis = g2 - g1
285
+ if np.linalg.norm(grasp_axis) == 0:
286
+ return grasp_axis
287
+ return grasp_axis / np.linalg.norm(grasp_axis)
288
+
289
+ @staticmethod
290
+ def width_from_endpoints(g1, g2):
291
+ """ Width of grasp from endpoints """
292
+ grasp_axis = g2 - g1
293
+ return np.linalg.norm(grasp_axis)
294
+
295
+ @staticmethod
296
+ def grasp_from_endpoints(g1, g2, width=None, approach_angle=0, close_width=0):
297
+ """ Create a grasp from given endpoints in 3D space, making the axis the line between the points.
298
+
299
+ Parameters
300
+ ---------
301
+ g1 : :obj:`numpy.ndarray`
302
+ location of the first jaw
303
+ g2 : :obj:`numpy.ndarray`
304
+ location of the second jaw
305
+ width : float
306
+ maximum opening width of jaws
307
+ approach_angle : float
308
+ approach angle of grasp
309
+ close_width : float
310
+ width of gripper when fully closed
311
+ """
312
+ x = ParallelJawPtGrasp3D.center_from_endpoints(g1, g2)
313
+ v = ParallelJawPtGrasp3D.axis_from_endpoints(g1, g2)
314
+ if width is None:
315
+ width = ParallelJawPtGrasp3D.width_from_endpoints(g1, g2)
316
+ return ParallelJawPtGrasp3D(
317
+ ParallelJawPtGrasp3D.configuration_from_params(x, v, width, min_width=close_width, angle=approach_angle))
318
+
319
+ @property
320
+ def unrotated_full_axis(self):
321
+ """ Rotation matrix from canonical grasp reference frame to object reference frame. X axis points out of the
322
+ gripper palm along the 0-degree approach direction, Y axis points between the jaws, and the Z axs is orthogonal.
323
+
324
+ Returns
325
+ -------
326
+ :obj:`numpy.ndarray`
327
+ rotation matrix of grasp
328
+ """
329
+ grasp_axis_y = self.axis
330
+ grasp_axis_x = np.array([grasp_axis_y[1], -grasp_axis_y[0], 0])
331
+ if np.linalg.norm(grasp_axis_x) == 0:
332
+ grasp_axis_x = np.array([1, 0, 0])
333
+ grasp_axis_x = grasp_axis_x / norm(grasp_axis_x)
334
+ grasp_axis_z = np.cross(grasp_axis_x, grasp_axis_y)
335
+
336
+ R = np.c_[grasp_axis_x, np.c_[grasp_axis_y, grasp_axis_z]]
337
+ return R
338
+
339
+ @property
340
+ def rotated_full_axis(self):
341
+ """ Rotation matrix from canonical grasp reference frame to object reference frame. X axis points out of the
342
+ gripper palm along the grasp approach angle, Y axis points between the jaws, and the Z axs is orthogonal.
343
+
344
+ Returns
345
+ -------
346
+ :obj:`numpy.ndarray`
347
+ rotation matrix of grasp
348
+ """
349
+ R = ParallelJawPtGrasp3D._get_rotation_matrix_y(self.approach_angle)
350
+ R = self.unrotated_full_axis.dot(R)
351
+ return R
352
+
353
+ @property
354
+ def T_grasp_obj(self):
355
+ """ Rigid transformation from grasp frame to object frame.
356
+ Rotation matrix is X-axis along approach direction, Y axis pointing between the jaws, and Z-axis orthogonal.
357
+ Translation vector is the grasp center.
358
+
359
+ Returns
360
+ -------
361
+ :obj:`RigidTransform`
362
+ transformation from grasp to object coordinates
363
+ """
364
+ T_grasp_obj = RigidTransform(self.rotated_full_axis, self.center, from_frame='grasp', to_frame='obj')
365
+ return T_grasp_obj
366
+
367
+ @staticmethod
368
+ def _get_rotation_matrix_y(theta):
369
+ cos_t = np.cos(theta)
370
+ sin_t = np.sin(theta)
371
+ R = np.c_[[cos_t, 0, sin_t], np.c_[[0, 1, 0], [-sin_t, 0, cos_t]]]
372
+ return R
373
+
374
+ def gripper_pose(self, gripper=None):
375
+ """ Returns the RigidTransformation from the gripper frame to the object frame when the gripper is executing the
376
+ given grasp.
377
+ Differs from the grasp reference frame because different robots use different conventions for the gripper
378
+ reference frame.
379
+
380
+ Parameters
381
+ ----------
382
+ gripper : :obj:`RobotGripper`
383
+ gripper to get the pose for
384
+
385
+ Returns
386
+ -------
387
+ :obj:`RigidTransform`
388
+ transformation from gripper frame to object frame
389
+ """
390
+ if gripper is None:
391
+ T_gripper_grasp = RigidTransform(from_frame='gripper', to_frame='grasp')
392
+ else:
393
+ T_gripper_grasp = gripper.T_grasp_gripper
394
+
395
+ T_gripper_obj = self.T_grasp_obj * T_gripper_grasp
396
+ return T_gripper_obj
397
+
398
+ def grasp_angles_from_stp_z(self, stable_pose):
399
+ """ Get angles of the the grasp from the table plane:
400
+ 1) the angle between the grasp axis and table normal
401
+ 2) the angle between the grasp approach axis and the table normal
402
+
403
+ Parameters
404
+ ----------
405
+ stable_pose : :obj:`StablePose` or :obj:`RigidTransform`
406
+ the stable pose to compute the angles for
407
+
408
+ Returns
409
+ -------
410
+ psi : float
411
+ grasp y axis rotation from z axis in stable pose
412
+ phi : float
413
+ grasp x axis rotation from z axis in stable pose
414
+ """
415
+ T_grasp_obj = self.T_grasp_obj
416
+
417
+ if isinstance(stable_pose, StablePose):
418
+ R_stp_obj = stable_pose.r
419
+ else:
420
+ R_stp_obj = stable_pose.rotation
421
+ T_stp_obj = RigidTransform(R_stp_obj, from_frame='obj', to_frame='stp')
422
+
423
+ T_stp_grasp = T_stp_obj * T_grasp_obj
424
+
425
+ stp_z = np.array([0, 0, 1])
426
+ grasp_axis_angle = np.arccos(stp_z.dot(T_stp_grasp.y_axis))
427
+ grasp_approach_angle = np.arccos(abs(stp_z.dot(T_stp_grasp.x_axis)))
428
+ nu = stp_z.dot(T_stp_grasp.z_axis)
429
+
430
+ return grasp_axis_angle, grasp_approach_angle, nu
431
+
432
+ def close_fingers(self, obj, vis=False, check_approach=True, approach_dist=1.0):
433
+ """ Steps along grasp axis to find the locations of contact with an object
434
+
435
+ Parameters
436
+ ----------
437
+ obj : :obj:`GraspableObject3D`
438
+ object to close fingers on
439
+ vis : bool
440
+ whether or not to plot the line of action and contact points
441
+ check_approach : bool
442
+ whether or not to check if the contact points can be reached
443
+ approach_dist : float
444
+ how far back to check the approach distance, only if checking the approach is set
445
+
446
+ Returns
447
+ -------
448
+ success : bool
449
+ whether or not contacts were found
450
+ c1 : :obj:`Contact3D`
451
+ the contact point for jaw 1
452
+ c2 : :obj:`Contact3D`
453
+ the contact point for jaw 2
454
+ """
455
+ if vis:
456
+ plt.figure()
457
+ plt.clf()
458
+ h = plt.gcf()
459
+ plt.ion()
460
+ # compute num samples to use based on sdf resolution
461
+ grasp_width_grid = obj.sdf.transform_pt_obj_to_grid(self.max_grasp_width_)
462
+ num_samples = int(Grasp.samples_per_grid * float(grasp_width_grid) / 2) # at least 1 sample per grid
463
+
464
+ # get grasp endpoints in sdf frame
465
+ g1_world, g2_world = self.endpoints
466
+
467
+ # check for contact along approach
468
+ if check_approach:
469
+ approach_dist_grid = obj.sdf.transform_pt_obj_to_grid(approach_dist)
470
+ num_approach_samples = int(Grasp.samples_per_grid * approach_dist_grid / 2) # at least 1 sample per grid
471
+ approach_axis = self.rotated_full_axis[:, 0]
472
+ approach_loa1 = ParallelJawPtGrasp3D.create_line_of_action(g1_world, -approach_axis, approach_dist, obj,
473
+ num_approach_samples, min_width=0)
474
+ approach_loa2 = ParallelJawPtGrasp3D.create_line_of_action(g2_world, -approach_axis, approach_dist, obj,
475
+ num_approach_samples, min_width=0)
476
+ c1_found, _ = ParallelJawPtGrasp3D.find_contact(approach_loa1, obj, vis=vis, strict=True)
477
+ c2_found, _ = ParallelJawPtGrasp3D.find_contact(approach_loa2, obj, vis=vis, strict=True)
478
+ approach_collision = c1_found or c2_found
479
+ if approach_collision:
480
+ plt.clf()
481
+ return False, None
482
+
483
+ # get line of action
484
+ line_of_action1 = ParallelJawPtGrasp3D.create_line_of_action(g1_world, self.axis_, self.open_width, obj,
485
+ num_samples, min_width=self.close_width)
486
+ line_of_action2 = ParallelJawPtGrasp3D.create_line_of_action(g2_world, -self.axis_, self.open_width, obj,
487
+ num_samples, min_width=self.close_width)
488
+
489
+ if vis:
490
+ ax = plt.gca(projection='3d')
491
+ surface = obj.sdf.surface_points()[0]
492
+ surface = surface[np.random.choice(surface.shape[0], 1000, replace=False)]
493
+ ax.scatter(surface[:, 0], surface[:, 1], surface[:, 2], '.',
494
+ s=np.ones_like(surface[:, 0]) * 0.3, c='b')
495
+
496
+ # find contacts
497
+ c1_found, c1 = ParallelJawPtGrasp3D.find_contact(line_of_action1, obj, vis=vis)
498
+ c2_found, c2 = ParallelJawPtGrasp3D.find_contact(line_of_action2, obj, vis=vis)
499
+
500
+ if vis:
501
+ ax = plt.gca(projection='3d')
502
+ ax.set_xlim3d(0, obj.sdf.dims_[0])
503
+ ax.set_ylim3d(0, obj.sdf.dims_[1])
504
+ ax.set_zlim3d(0, obj.sdf.dims_[2])
505
+ plt.draw()
506
+
507
+ contacts_found = c1_found and c2_found
508
+ return contacts_found, [c1, c2]
509
+
510
+ def close_fingers_with_contacts(self, obj, contacts, vis=False, check_approach=True, approach_dist=0.5):
511
+ """ Steps along grasp axis to find the locations of contact with an object
512
+
513
+ Parameters
514
+ ----------
515
+ obj : :obj:`GraspableObject3D`
516
+ object to close fingers on
517
+ vis : bool
518
+ whether or not to plot the line of action and contact points
519
+ check_approach : bool
520
+ whether or not to check if the contact points can be reached
521
+ approach_dist : float
522
+ how far back to check the approach distance, only if checking the approach is set
523
+
524
+ Returns
525
+ -------
526
+ success : bool
527
+ whether or not contacts were found
528
+ c1 : :obj:`Contact3D`
529
+ the contact point for jaw 1
530
+ c2 : :obj:`Contact3D`
531
+ the contact point for jaw 2
532
+ """
533
+ if vis:
534
+ plt.figure()
535
+ plt.clf()
536
+ h = plt.gcf()
537
+ plt.ion()
538
+ # compute num samples to use based on sdf resolution
539
+ grasp_width_grid = obj.sdf.transform_pt_obj_to_grid(self.max_grasp_width_)
540
+ num_samples = int(Grasp.samples_per_grid * float(grasp_width_grid) / 2) # at least 1 sample per grid
541
+
542
+ # get grasp endpoints in sdf frame
543
+ g1_world, g2_world = self.endpoints
544
+ c1_world, c2_world = contacts
545
+ # print(g1_world, g2_world)
546
+ # print(c1_world, c2_world)
547
+ c1_world = c1_world - 0.01 * self.axis_
548
+ c2_world = c2_world + 0.01 * self.axis_
549
+
550
+ # check for contact along approach
551
+ if check_approach:
552
+ approach_dist_grid = obj.sdf.transform_pt_obj_to_grid(approach_dist)
553
+ num_approach_samples = int(Grasp.samples_per_grid * approach_dist_grid / 2) # at least 1 sample per grid
554
+ approach_axis = self.rotated_full_axis[:, 0]
555
+ approach_loa1 = ParallelJawPtGrasp3D.create_line_of_action(g1_world, -approach_axis, approach_dist, obj,
556
+ num_approach_samples, min_width=0)
557
+ approach_loa2 = ParallelJawPtGrasp3D.create_line_of_action(g2_world, -approach_axis, approach_dist, obj,
558
+ num_approach_samples, min_width=0)
559
+ c1_found, _ = ParallelJawPtGrasp3D.find_contact(approach_loa1, obj, vis=vis, strict=True)
560
+ c2_found, _ = ParallelJawPtGrasp3D.find_contact(approach_loa2, obj, vis=vis, strict=True)
561
+ approach_collision = c1_found or c2_found
562
+ if approach_collision:
563
+ # print('collision')
564
+ plt.clf()
565
+ return False, None
566
+
567
+ # get line of action
568
+ line_of_action1 = ParallelJawPtGrasp3D.create_line_of_action(c1_world, self.axis_, self.open_width + 0.01, obj,
569
+ num_samples, min_width=self.close_width,
570
+ convert_grid=False)
571
+ line_of_action2 = ParallelJawPtGrasp3D.create_line_of_action(c2_world, -self.axis_, self.open_width + 0.01, obj,
572
+ num_samples, min_width=self.close_width,
573
+ convert_grid=False)
574
+
575
+ if vis:
576
+ ax = plt.gca(projection='3d')
577
+ surface = obj.sdf.surface_points()[0]
578
+ surface = surface[np.random.choice(surface.shape[0], 1000, replace=False)]
579
+ ax.scatter(surface[:, 0], surface[:, 1], surface[:, 2], '.',
580
+ s=np.ones_like(surface[:, 0]) * 0.3, c='b')
581
+
582
+ # find contacts
583
+
584
+ c1_found, c1 = ParallelJawPtGrasp3D.find_contact(line_of_action1, obj, vis=vis)
585
+ c2_found, c2 = ParallelJawPtGrasp3D.find_contact(line_of_action2, obj, vis=vis)
586
+ '''
587
+ for loa1_point in line_of_action1:
588
+ approach_dist_grid = obj.sdf.transform_pt_obj_to_grid(self.max_grasp_depth)
589
+ num_approach_samples = int(Grasp.samples_per_grid * approach_dist_grid / 2) # at least 1 sample per grid
590
+ approach_axis = self.rotated_full_axis[:, 0]
591
+ approach_loa1 = ParallelJawPtGrasp3D.create_line_of_action(loa1_point, -approach_axis, self.max_grasp_depth, obj,
592
+ num_approach_samples, min_width=0)
593
+ c1_found, c1 = ParallelJawPtGrasp3D.find_contact(approach_loa1, obj, vis=vis, strict=False)
594
+ if c1_found:
595
+ break
596
+ for loa2_point in line_of_action2:
597
+ approach_dist_grid = obj.sdf.transform_pt_obj_to_grid(self.max_grasp_depth)
598
+ num_approach_samples = int(Grasp.samples_per_grid * approach_dist_grid / 2) # at least 1 sample per grid
599
+ approach_axis = self.rotated_full_axis[:, 0]
600
+ approach_loa1 = ParallelJawPtGrasp3D.create_line_of_action(loa2_point, -approach_axis, self.max_grasp_depth, obj,
601
+ num_approach_samples, min_width=0)
602
+ c2_found, c2 = ParallelJawPtGrasp3D.find_contact(approach_loa1, obj, vis=vis, strict=False)
603
+ if c2_found:
604
+ break
605
+ '''
606
+ # if c1_found and c2_found:
607
+ # print('yes')
608
+ # else:
609
+ # print('no')
610
+ if vis:
611
+ ax = plt.gca(projection='3d')
612
+ ax.set_xlim3d(0, obj.sdf.dims_[0])
613
+ ax.set_ylim3d(0, obj.sdf.dims_[1])
614
+ ax.set_zlim3d(0, obj.sdf.dims_[2])
615
+ plt.draw()
616
+
617
+ contacts_found = c1_found and c2_found
618
+ return contacts_found, [c1, c2]
619
+
620
+ def vis_grasp(self, obj, *args, **kwargs):
621
+ if 'keep' not in kwargs or not kwargs['keep']:
622
+ plt.clf()
623
+
624
+ ax = plt.gca(projection='3d')
625
+ if 'show_obj' in kwargs and kwargs['show_obj']:
626
+ # plot the obj
627
+ surface = obj.sdf.surface_points()[0]
628
+ surface = surface[np.random.choice(surface.shape[0], 1000, replace=False)]
629
+ ax.scatter(surface[:, 0], surface[:, 1], surface[:, 2], '.',
630
+ s=np.ones_like(surface[:, 0]) * 0.3, c='b')
631
+
632
+ # plot the center of grasp using grid
633
+ grasp_center_grid = obj.sdf.transform_pt_obj_to_grid(self.center)
634
+ ax.scatter(grasp_center_grid[0], grasp_center_grid[1], grasp_center_grid[2], marker='x', c='r')
635
+
636
+ # compute num samples to use based on sdf resolution
637
+ grasp_width_grid = obj.sdf.transform_pt_obj_to_grid(self.max_grasp_width_)
638
+ num_samples = int(Grasp.samples_per_grid * float(grasp_width_grid) / 2) # at least 1 sample per grid
639
+
640
+ # get grasp endpoints in sdf frame
641
+ g1_world, g2_world = self.endpoints
642
+
643
+ # check for contact along approach
644
+ approach_dist = 0.1
645
+ approach_dist_grid = obj.sdf.transform_pt_obj_to_grid(approach_dist)
646
+ num_approach_samples = int(approach_dist_grid / 2) # at least 1 sample per grid
647
+ approach_axis = self.rotated_full_axis[:, 0]
648
+ approach_loa1 = ParallelJawPtGrasp3D.create_line_of_action(g1_world, -approach_axis, approach_dist, obj,
649
+ num_approach_samples, min_width=0)
650
+ approach_loa2 = ParallelJawPtGrasp3D.create_line_of_action(g2_world, -approach_axis, approach_dist, obj,
651
+ num_approach_samples, min_width=0)
652
+ end1, end2 = approach_loa1[-1], approach_loa2[-1]
653
+ begin1, begin2 = approach_loa1[0], approach_loa2[0]
654
+ ax.plot([end1[0], end2[0]], [end1[1], end2[1]], [end1[2], end2[2]], 'r-', linewidth=5)
655
+ ax.plot([end1[0], begin1[0]], [end1[1], begin1[1]], [end1[2], begin1[2]], 'r-', linewidth=5)
656
+ ax.plot([begin2[0], end2[0]], [begin2[1], end2[1]], [begin2[2], end2[2]], 'r-', linewidth=5)
657
+ c1_found, _ = ParallelJawPtGrasp3D.find_contact(approach_loa1, obj, vis=False, strict=True)
658
+ c2_found, _ = ParallelJawPtGrasp3D.find_contact(approach_loa2, obj, vis=False, strict=True)
659
+ approach_collision = c1_found or c2_found
660
+ if approach_collision:
661
+ plt.clf()
662
+ return False
663
+
664
+ # get line of action
665
+ line_of_action1 = ParallelJawPtGrasp3D.create_line_of_action(g1_world, self.axis_, self.open_width, obj,
666
+ num_samples, min_width=self.close_width)
667
+ line_of_action2 = ParallelJawPtGrasp3D.create_line_of_action(g2_world, -self.axis_, self.open_width, obj,
668
+ num_samples, min_width=self.close_width)
669
+
670
+ # find contacts
671
+ c1_found, c1 = ParallelJawPtGrasp3D.find_contact(line_of_action1, obj, vis=False)
672
+ c2_found, c2 = ParallelJawPtGrasp3D.find_contact(line_of_action2, obj, vis=False)
673
+ begin1, begin2 = line_of_action1[0], line_of_action2[0]
674
+ end1, end2 = obj.sdf.transform_pt_obj_to_grid(c1.point), obj.sdf.transform_pt_obj_to_grid(c2.point)
675
+ print(end1, end2)
676
+ ax.plot([end1[0], begin1[0]], [end1[1], begin1[1]], [end1[2], begin1[2]], 'r-', linewidth=5)
677
+ ax.plot([begin2[0], end2[0]], [begin2[1], end2[1]], [begin2[2], end2[2]], 'r-', linewidth=5)
678
+ ax.scatter(end1[0], end1[1], end1[2], s=80, c='g')
679
+ ax.scatter(end2[0], end2[1], end2[2], s=80, c='g')
680
+
681
+ ax.set_xlim3d(0, obj.sdf.dims_[0])
682
+ ax.set_ylim3d(0, obj.sdf.dims_[1])
683
+ ax.set_zlim3d(0, obj.sdf.dims_[2])
684
+ plt.title(','.join([str(i) for i in args]))
685
+ plt.draw()
686
+
687
+ contacts_found = c1_found and c2_found
688
+ return contacts_found
689
+
690
+ @staticmethod
691
+ def create_line_of_action(g, axis, width, obj, num_samples, min_width=0, convert_grid=True):
692
+ """
693
+ Creates a straight line of action, or list of grid points, from a given point and direction in world or grid coords
694
+
695
+ Parameters
696
+ ----------
697
+ g : 3x1 :obj:`numpy.ndarray`
698
+ start point to create the line of action
699
+ axis : normalized 3x1 :obj:`numpy.ndarray`
700
+ normalized numpy 3 array of grasp direction
701
+ width : float
702
+ the grasp width
703
+ num_samples : int
704
+ number of discrete points along the line of action
705
+ convert_grid : bool
706
+ whether or not the points are specified in world coords
707
+
708
+ Returns
709
+ -------
710
+ line_of_action : :obj:`list` of 3x1 :obj:`numpy.ndarrays`
711
+ coordinates to pass through in 3D space for contact checking
712
+ """
713
+ num_samples = max(num_samples, 3) # always at least 3 samples
714
+ line_of_action = [g + t * axis for t in
715
+ np.linspace(0, float(width) / 2 - float(min_width) / 2, num=num_samples)]
716
+ if convert_grid:
717
+ as_array = np.array(line_of_action).T
718
+ transformed = obj.sdf.transform_pt_obj_to_grid(as_array)
719
+ line_of_action = list(transformed.T)
720
+ return line_of_action
721
+
722
+ @staticmethod
723
+ def find_contact(line_of_action, obj, vis=False, strict=False):
724
+ """
725
+ Find the point at which a point traveling along a given line of action hits a surface.
726
+
727
+ Parameters
728
+ ----------
729
+ line_of_action : :obj:`list` of 3x1 :obj:`numpy.ndarray`
730
+ the points visited as the fingers close (grid coords)
731
+ obj : :obj:`GraspableObject3D`
732
+ to check contacts on
733
+ vis : bool
734
+ whether or not to display the contact check (for debugging)
735
+
736
+ Returns
737
+ -------
738
+ contact_found : bool
739
+ whether or not the point contacts the object surface
740
+ contact : :obj:`Contact3D`
741
+ found along line of action (None if contact not found)
742
+ """
743
+ contact_found = False
744
+ pt_zc = None
745
+ pt_zc_world = None
746
+ contact = None
747
+ num_pts = len(line_of_action)
748
+ sdf_here = 0
749
+ sdf_before = 0
750
+ pt_grid = None
751
+ pt_before = None
752
+
753
+ # step along line of action, get points on surface when possible
754
+ i = 0
755
+ while i < num_pts and not contact_found:
756
+ # update loop vars
757
+ pt_before_before = pt_before
758
+ pt_before = pt_grid
759
+ sdf_before_before = sdf_before
760
+ sdf_before = sdf_here
761
+ pt_grid = line_of_action[i]
762
+
763
+ # visualize
764
+ if vis:
765
+ ax = plt.gca(projection='3d')
766
+ ax.scatter(pt_grid[0], pt_grid[1], pt_grid[2], c='r')
767
+
768
+ # check surface point
769
+ on_surface, sdf_here = obj.sdf.on_surface(pt_grid)
770
+ if on_surface:
771
+ contact_found = True
772
+ if strict:
773
+ return contact_found, None
774
+
775
+ # quadratic approximation to find actual zero crossing
776
+ if i == 0:
777
+ pt_after = line_of_action[i + 1]
778
+ sdf_after = obj.sdf[pt_after]
779
+ pt_after_after = line_of_action[i + 2]
780
+ sdf_after_after = obj.sdf[pt_after_after]
781
+
782
+ pt_zc = Sdf3D.find_zero_crossing_quadratic(pt_grid, sdf_here, pt_after, sdf_after, pt_after_after,
783
+ sdf_after_after)
784
+
785
+ # contact not yet found if next sdf value is smaller
786
+ if pt_zc is None or np.abs(sdf_after) < np.abs(sdf_here):
787
+ contact_found = False
788
+
789
+ elif i == len(line_of_action) - 1:
790
+ pt_zc = Sdf3D.find_zero_crossing_quadratic(pt_before_before, sdf_before_before, pt_before,
791
+ sdf_before, pt_grid, sdf_here)
792
+
793
+ if pt_zc is None:
794
+ contact_found = False
795
+
796
+ else:
797
+ pt_after = line_of_action[i + 1]
798
+ sdf_after = obj.sdf[pt_after]
799
+ pt_zc = Sdf3D.find_zero_crossing_quadratic(pt_before, sdf_before, pt_grid, sdf_here, pt_after,
800
+ sdf_after)
801
+
802
+ # contact not yet found if next sdf value is smaller
803
+ if pt_zc is None or np.abs(sdf_after) < np.abs(sdf_here):
804
+ contact_found = False
805
+ i = i + 1
806
+
807
+ # visualization
808
+ if vis and contact_found:
809
+ ax = plt.gca(projection='3d')
810
+ ax.scatter(pt_zc[0], pt_zc[1], pt_zc[2], s=80, c='g')
811
+
812
+ if contact_found:
813
+ pt_zc_world = obj.sdf.transform_pt_grid_to_obj(pt_zc)
814
+ in_direction_grid = line_of_action[-1] - line_of_action[0]
815
+ in_direction_grid = in_direction_grid / np.linalg.norm(in_direction_grid)
816
+ in_direction = obj.sdf.transform_pt_grid_to_obj(in_direction_grid, direction=True)
817
+ contact = Contact3D(obj, pt_zc_world, in_direction=in_direction)
818
+ if contact.normal is None:
819
+ contact_found = False
820
+ return contact_found, contact
821
+
822
+ def _angle_aligned_with_stable_pose(self, stable_pose):
823
+ """
824
+ Returns the y-axis rotation angle that'd allow the current pose to align with stable pose.
825
+ """
826
+
827
+ def _argmin(f, a, b, n):
828
+ # finds the argmax x of f(x) in the range [a, b) with n samples
829
+ delta = (b - a) / n
830
+ min_y = f(a)
831
+ min_x = a
832
+ for i in range(1, n):
833
+ x = i * delta
834
+ y = f(x)
835
+ if y <= min_y:
836
+ min_y = y
837
+ min_x = x
838
+ return min_x
839
+
840
+ def _get_matrix_product_x_axis(grasp_axis, normal):
841
+ def matrix_product(theta):
842
+ R = ParallelJawPtGrasp3D._get_rotation_matrix_y(theta)
843
+ grasp_axis_rotated = np.dot(R, grasp_axis)
844
+ return abs(np.dot(normal, grasp_axis_rotated))
845
+
846
+ return matrix_product
847
+
848
+ stable_pose_normal = stable_pose.r[2, :]
849
+
850
+ theta = _argmin(
851
+ _get_matrix_product_x_axis(np.array([1, 0, 0]), np.dot(inv(self.unrotated_full_axis), stable_pose_normal)),
852
+ 0, 2 * np.pi, 1000)
853
+ return theta
854
+
855
+ def grasp_y_axis_offset(self, theta):
856
+ """ Return a new grasp with the given approach angle.
857
+
858
+ Parameters
859
+ ----------
860
+ theta : float
861
+ approach angle for the new grasp
862
+
863
+ Returns
864
+ -------
865
+ :obj:`ParallelJawPtGrasp3D`
866
+ grasp with the given approach angle
867
+ """
868
+ new_grasp = deepcopy(self)
869
+ new_grasp.approach_angle = theta + self.approach_angle
870
+ return new_grasp
871
+
872
+ def parallel_table(self, stable_pose):
873
+ """
874
+ Returns a grasp with approach_angle set to be perpendicular to the table normal specified in the given stable pose.
875
+
876
+ Parameters
877
+ ----------
878
+ stable_pose : :obj:`StablePose`
879
+ the pose specifying the table
880
+
881
+ Returns
882
+ -------
883
+ :obj:`ParallelJawPtGrasp3D`
884
+ aligned grasp
885
+ """
886
+ theta = self._angle_aligned_with_stable_pose(stable_pose)
887
+ new_grasp = deepcopy(self)
888
+ new_grasp.approach_angle = theta
889
+ return new_grasp
890
+
891
+ def _angle_aligned_with_table(self, table_normal):
892
+ """
893
+ Returns the y-axis rotation angle that'd allow the current pose to align with the table normal.
894
+ """
895
+
896
+ def _argmax(f, a, b, n):
897
+ # finds the argmax x of f(x) in the range [a, b) with n samples
898
+ delta = (b - a) / n
899
+ max_y = f(a)
900
+ max_x = a
901
+ for i in range(1, n):
902
+ x = i * delta
903
+ y = f(x)
904
+ if y >= max_y:
905
+ max_y = y
906
+ max_x = x
907
+ return max_x
908
+
909
+ def _get_matrix_product_x_axis(grasp_axis, normal):
910
+ def matrix_product(theta):
911
+ R = ParallelJawPtGrasp3D._get_rotation_matrix_y(theta)
912
+ grasp_axis_rotated = np.dot(R, grasp_axis)
913
+ return np.dot(normal, grasp_axis_rotated)
914
+
915
+ return matrix_product
916
+
917
+ theta = _argmax(
918
+ _get_matrix_product_x_axis(np.array([1, 0, 0]), np.dot(inv(self.unrotated_full_axis), -table_normal)), 0,
919
+ 2 * np.pi, 64)
920
+ return theta
921
+
922
+ def perpendicular_table(self, stable_pose):
923
+ """
924
+ Returns a grasp with approach_angle set to be aligned width the table normal specified in the given stable pose.
925
+
926
+ Parameters
927
+ ----------
928
+ stable_pose : :obj:`StablePose` or :obj:`RigidTransform`
929
+ the pose specifying the orientation of the table
930
+
931
+ Returns
932
+ -------
933
+ :obj:`ParallelJawPtGrasp3D`
934
+ aligned grasp
935
+ """
936
+ if isinstance(stable_pose, StablePose):
937
+ table_normal = stable_pose.r[2, :]
938
+ else:
939
+ table_normal = stable_pose.rotation[2, :]
940
+ theta = self._angle_aligned_with_table(table_normal)
941
+ new_grasp = deepcopy(self)
942
+ new_grasp.approach_angle = theta
943
+ return new_grasp
944
+
945
+ def project_camera(self, T_obj_camera, camera_intr):
946
+ """ Project a grasp for a given gripper into the camera specified by a set of intrinsics.
947
+
948
+ Parameters
949
+ ----------
950
+ T_obj_camera : :obj:`autolab_core.RigidTransform`
951
+ rigid transformation from the object frame to the camera frame
952
+ camera_intr : :obj:`perception.CameraIntrinsics`
953
+ intrinsics of the camera to use
954
+ """
955
+ # compute pose of grasp in camera frame
956
+ T_grasp_camera = T_obj_camera * self.T_grasp_obj
957
+ y_axis_camera = T_grasp_camera.y_axis[:2]
958
+ if np.linalg.norm(y_axis_camera) > 0:
959
+ y_axis_camera = y_axis_camera / np.linalg.norm(y_axis_camera)
960
+
961
+ # compute grasp axis rotation in image space
962
+ rot_z = np.arccos(y_axis_camera[0])
963
+ if y_axis_camera[1] < 0:
964
+ rot_z = -rot_z
965
+ while rot_z < 0:
966
+ rot_z += 2 * np.pi
967
+ while rot_z > 2 * np.pi:
968
+ rot_z -= 2 * np.pi
969
+
970
+ # compute grasp center in image space
971
+ t_grasp_camera = T_grasp_camera.translation
972
+ p_grasp_camera = Point(t_grasp_camera, frame=camera_intr.frame)
973
+ u_grasp_camera = camera_intr.project(p_grasp_camera)
974
+ d_grasp_camera = t_grasp_camera[2]
975
+ return Grasp2D(u_grasp_camera, rot_z, d_grasp_camera,
976
+ width=self.open_width,
977
+ camera_intr=camera_intr)
978
+
979
+ @staticmethod
980
+ def grasp_from_contact_and_axis_on_grid(obj, grasp_c1_world, grasp_axis_world, grasp_width_world, grasp_angle=0,
981
+ jaw_width_world=0,
982
+ min_grasp_width_world=0, vis=False, backup=0.5):
983
+ """
984
+ Creates a grasp from a single contact point in grid coordinates and direction in grid coordinates.
985
+
986
+ Parameters
987
+ ----------
988
+ obj : :obj:`GraspableObject3D`
989
+ object to create grasp for
990
+ grasp_c1_grid : 3x1 :obj:`numpy.ndarray`
991
+ contact point 1 in world
992
+ grasp_axis : normalized 3x1 :obj:`numpy.ndarray`
993
+ normalized direction of the grasp in world
994
+ grasp_width_world : float
995
+ grasp_width in world coords
996
+ jaw_width_world : float
997
+ width of jaws in world coords
998
+ min_grasp_width_world : float
999
+ min closing width of jaws
1000
+ vis : bool
1001
+ whether or not to visualize the grasp
1002
+
1003
+ Returns
1004
+ -------
1005
+ g : :obj:`ParallelJawGrasp3D`
1006
+ grasp created by finding the second contact
1007
+ c1 : :obj:`Contact3D`
1008
+ first contact point on the object
1009
+ c2 : :obj:`Contact3D`
1010
+ second contact point on the object
1011
+ """
1012
+ # transform to grid basis
1013
+ grasp_axis_world = grasp_axis_world / np.linalg.norm(grasp_axis_world)
1014
+ grasp_axis_grid = obj.sdf.transform_pt_obj_to_grid(grasp_axis_world, direction=True)
1015
+ grasp_width_grid = obj.sdf.transform_pt_obj_to_grid(grasp_width_world)
1016
+ min_grasp_width_grid = obj.sdf.transform_pt_obj_to_grid(min_grasp_width_world)
1017
+ grasp_c1_grid = obj.sdf.transform_pt_obj_to_grid(
1018
+ grasp_c1_world) - backup * grasp_axis_grid # subtract to find true point
1019
+ num_samples = int(2 * grasp_width_grid) # at least 2 samples per grid
1020
+ g2 = grasp_c1_grid + (grasp_width_grid - backup) * grasp_axis_grid
1021
+
1022
+ # get line of action
1023
+ line_of_action1 = ParallelJawPtGrasp3D.create_line_of_action(grasp_c1_grid, grasp_axis_grid, grasp_width_grid,
1024
+ obj, num_samples,
1025
+ min_width=min_grasp_width_grid, convert_grid=False)
1026
+ line_of_action2 = ParallelJawPtGrasp3D.create_line_of_action(g2, -grasp_axis_grid, 2 * grasp_width_grid, obj,
1027
+ num_samples,
1028
+ min_width=0, convert_grid=False)
1029
+ if vis:
1030
+ obj.sdf.scatter()
1031
+ ax = plt.gca(projection='3d')
1032
+ ax.scatter(grasp_c1_grid[0] - grasp_axis_grid[0], grasp_c1_grid[1] - grasp_axis_grid[1],
1033
+ grasp_c1_grid[2] - grasp_axis_grid[2], c='r')
1034
+ ax.scatter(grasp_c1_grid[0], grasp_c1_grid[1], grasp_c1_grid[2], s=80, c='b')
1035
+
1036
+ # compute the contact points on the object
1037
+ contact1_found, c1 = ParallelJawPtGrasp3D.find_contact(line_of_action1, obj, vis=vis)
1038
+ contact2_found, c2 = ParallelJawPtGrasp3D.find_contact(line_of_action2, obj, vis=vis)
1039
+
1040
+ if vis:
1041
+ ax.set_xlim3d(0, obj.sdf.dims_[0])
1042
+ ax.set_ylim3d(0, obj.sdf.dims_[1])
1043
+ ax.set_zlim3d(0, obj.sdf.dims_[2])
1044
+ plt.draw()
1045
+ if not contact1_found or not contact2_found or np.linalg.norm(c1.point - c2.point) <= min_grasp_width_world:
1046
+ logging.debug('No contacts found for grasp')
1047
+ return None, None, None
1048
+
1049
+ # create grasp
1050
+ grasp_center = ParallelJawPtGrasp3D.center_from_endpoints(c1.point, c2.point)
1051
+ grasp_axis = ParallelJawPtGrasp3D.axis_from_endpoints(c1.point, c2.point)
1052
+ configuration = ParallelJawPtGrasp3D.configuration_from_params(grasp_center, grasp_axis, grasp_width_world,
1053
+ grasp_angle, jaw_width_world)
1054
+ return ParallelJawPtGrasp3D(configuration), c1, c2 # relative to object
1055
+
1056
+ def surface_information(self, graspable, width=2e-2, num_steps=21, direction=None):
1057
+ """ Return the patch surface information at the contacts that this grasp makes on a graspable.
1058
+
1059
+ Parameters
1060
+ ----------
1061
+ graspable : :obj:`GraspableObject3D`
1062
+ object to get surface information for
1063
+ width : float
1064
+ width of the window in obj frame
1065
+ num_steps : int
1066
+ number of steps
1067
+
1068
+ Returns
1069
+ -------
1070
+ :obj:`list` of :obj:`SurfaceWindow`
1071
+ surface patches, one for each contact
1072
+ """
1073
+ return graspable.surface_information(self, width, num_steps, direction1=self.axis_, direction2=-self.axis_)
1074
+
1075
+
1076
+ class VacuumPoint(Grasp):
1077
+ """ Defines a vacuum target point and axis in 3D space (5 DOF)
1078
+ """
1079
+
1080
+ def __init__(self, configuration, frame='object', grasp_id=None):
1081
+ center, axis = VacuumPoint.params_from_configuration(configuration)
1082
+ self._center = center
1083
+ self._axis = axis
1084
+ self.frame_ = frame
1085
+
1086
+ @property
1087
+ def center(self):
1088
+ return self._center
1089
+
1090
+ @property
1091
+ def axis(self):
1092
+ return self._axis
1093
+
1094
+ @property
1095
+ def frame(self):
1096
+ return self._frame
1097
+
1098
+ @property
1099
+ def configuration(self):
1100
+ return VacuumPoint.configuration_from_params(self._center, self._axis)
1101
+
1102
+ @staticmethod
1103
+ def configuration_from_params(center, axis):
1104
+ """ Converts grasp parameters to a configuration vector. """
1105
+ if np.abs(np.linalg.norm(axis) - 1.0) > 1e-5:
1106
+ raise ValueError('Illegal vacuum axis. Must be norm one')
1107
+ configuration = np.zeros(6)
1108
+ configuration[0:3] = center
1109
+ configuration[3:6] = axis
1110
+ return configuration
1111
+
1112
+ @staticmethod
1113
+ def params_from_configuration(configuration):
1114
+ """ Converts configuration vector into vacuum grasp parameters.
1115
+
1116
+ Returns
1117
+ -------
1118
+ center : :obj:`numpy.ndarray`
1119
+ center of grasp in 3D space
1120
+ axis : :obj:`numpy.ndarray`
1121
+ normalized axis of grasp in 3D space
1122
+ """
1123
+ if not isinstance(configuration, np.ndarray) or configuration.shape[0] != 6:
1124
+ raise ValueError('Configuration must be numpy ndarray of size 6')
1125
+ if np.abs(np.linalg.norm(configuration[3:6]) - 1.0) > 1e-5:
1126
+ raise ValueError('Illegal vacuum axis. Must be norm one')
1127
+ return configuration[0:3], configuration[3:6]
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/grasp_quality_config.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ """
22
+ """
23
+ Configurations for grasp quality computation.
24
+ Author: Jeff Mahler
25
+ """
26
+ from abc import ABCMeta, abstractmethod
27
+
28
+ import copy
29
+ import itertools as it
30
+ import logging
31
+ import matplotlib.pyplot as plt
32
+ try:
33
+ import mayavi.mlab as mlab
34
+ except:
35
+ # logging.warning('Failed to import mayavi')
36
+ pass
37
+
38
+ import numpy as np
39
+ import os
40
+ import sys
41
+ import time
42
+
43
+ import IPython
44
+
45
+ # class GraspQualityConfig(object, metaclass=ABCMeta):
46
+ class GraspQualityConfig(object):
47
+ """
48
+ Base wrapper class for parameters used in grasp quality computation.
49
+ Used to elegantly enforce existence and type of required parameters.
50
+
51
+ Attributes
52
+ ----------
53
+ config : :obj:`dict`
54
+ dictionary mapping parameter names to parameter values
55
+ """
56
+ __metaclass__ = ABCMeta
57
+ def __init__(self, config):
58
+ # check valid config
59
+ self.check_valid(config)
60
+
61
+ # parse config
62
+ for key, value in list(config.items()):
63
+ setattr(self, key, value)
64
+
65
+ def contains(self, key):
66
+ """ Checks whether or not the key is supported """
67
+ if key in list(self.__dict__.keys()):
68
+ return True
69
+ return False
70
+
71
+ def __getattr__(self, key):
72
+ if self.contains(key):
73
+ return object.__getattribute__(self, key)
74
+ return None
75
+
76
+ def __getitem__(self, key):
77
+ if self.contains(key):
78
+ return object.__getattribute__(self, key)
79
+ raise KeyError('Key %s not found' %(key))
80
+
81
+ def keys(self):
82
+ return list(self.__dict__.keys())
83
+
84
+ @abstractmethod
85
+ def check_valid(self, config):
86
+ """ Raise an exception if the config is missing required keys """
87
+ pass
88
+
89
+ class QuasiStaticGraspQualityConfig(GraspQualityConfig):
90
+ """
91
+ Parameters for quasi-static grasp quality computation.
92
+
93
+ Attributes
94
+ ----------
95
+ config : :obj:`dict`
96
+ dictionary mapping parameter names to parameter values
97
+
98
+ Notes
99
+ -----
100
+ Required configuration key-value pairs in Other Parameters.
101
+
102
+ Other Parameters
103
+ ----------------
104
+ quality_method : :obj:`str`
105
+ string name of quasi-static quality metric
106
+ friction_coef : float
107
+ coefficient of friction at contact point
108
+ num_cone_faces : int
109
+ number of faces to use in friction cone approximation
110
+ soft_fingers : bool
111
+ whether to use a soft finger model
112
+ quality_type : :obj:`str`
113
+ string name of grasp quality type (e.g. quasi-static, robust quasi-static)
114
+ check_approach : bool
115
+ whether or not to check the approach direction
116
+ """
117
+ REQUIRED_KEYS = ['quality_method',
118
+ 'friction_coef',
119
+ 'num_cone_faces',
120
+ 'soft_fingers',
121
+ 'quality_type',
122
+ 'check_approach',
123
+ 'all_contacts_required']
124
+
125
+ def __init__(self, config):
126
+ GraspQualityConfig.__init__(self, config)
127
+
128
+ def __copy__(self):
129
+ """ Makes a copy of the config """
130
+ obj_copy = QuasiStaticGraspQualityConfig(self.__dict__)
131
+ return obj_copy
132
+
133
+ def check_valid(self, config):
134
+ for key in QuasiStaticGraspQualityConfig.REQUIRED_KEYS:
135
+ if key not in list(config.keys()):
136
+ raise ValueError('Invalid configuration. Key %s must be specified' %(key))
137
+
138
+ class RobustQuasiStaticGraspQualityConfig(GraspQualityConfig):
139
+ """
140
+ Parameters for quasi-static grasp quality computation.
141
+
142
+ Attributes
143
+ ----------
144
+ config : :obj:`dict`
145
+ dictionary mapping parameter names to parameter values
146
+
147
+ Notes
148
+ -----
149
+ Required configuration key-value pairs in Other Parameters.
150
+
151
+ Other Parameters
152
+ ----------------
153
+ quality_method : :obj:`str`
154
+ string name of quasi-static quality metric
155
+ friction_coef : float
156
+ coefficient of friction at contact point
157
+ num_cone_faces : int
158
+ number of faces to use in friction cone approximation
159
+ soft_fingers : bool
160
+ whether to use a soft finger model
161
+ quality_type : :obj:`str`
162
+ string name of grasp quality type (e.g. quasi-static, robust quasi-static)
163
+ check_approach : bool
164
+ whether or not to check the approach direction
165
+ num_quality_samples : int
166
+ number of samples to use
167
+ """
168
+ ROBUST_REQUIRED_KEYS = ['num_quality_samples']
169
+
170
+ def __init__(self, config):
171
+ GraspQualityConfig.__init__(self, config)
172
+
173
+ def __copy__(self):
174
+ """ Makes a copy of the config """
175
+ obj_copy = RobustQuasiStaticGraspQualityConfig(self.__dict__)
176
+ return obj_copy
177
+
178
+ def check_valid(self, config):
179
+ required_keys = QuasiStaticGraspQualityConfig.REQUIRED_KEYS + \
180
+ RobustQuasiStaticGraspQualityConfig.ROBUST_REQUIRED_KEYS
181
+ for key in required_keys:
182
+ if key not in list(config.keys()):
183
+ raise ValueError('Invalid configuration. Key %s must be specified' %(key))
184
+
185
+ class GraspQualityConfigFactory:
186
+ """ Helper class to automatically create grasp quality configurations of different types. """
187
+ @staticmethod
188
+ def create_config(config):
189
+ """ Automatically create a quality config from a dictionary.
190
+
191
+ Parameters
192
+ ----------
193
+ config : :obj:`dict`
194
+ dictionary mapping parameter names to parameter values
195
+ """
196
+ if config['quality_type'] == 'quasi_static':
197
+ return QuasiStaticGraspQualityConfig(config)
198
+ elif config['quality_type'] == 'robust_quasi_static':
199
+ return RobustQuasiStaticGraspQualityConfig(config)
200
+ else:
201
+ raise ValueError('Quality config type %s not supported' %(config['type']))
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/grasp_quality_function.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ """
22
+ """
23
+ User-friendly functions for computing grasp quality metrics.
24
+ Author: Jeff Mahler
25
+ """
26
+ from abc import ABCMeta, abstractmethod
27
+
28
+ import copy
29
+ import itertools as it
30
+ import logging
31
+ import matplotlib.pyplot as plt
32
+
33
+ import numpy as np
34
+ import os
35
+ import scipy.stats
36
+ import sys
37
+ import time
38
+
39
+ from .grasp import Grasp
40
+ from .graspable_object import GraspableObject
41
+ from .graspable_object import GraspQualityConfig
42
+ from .robust_grasp_quality import RobustPointGraspMetrics3D
43
+ from .random_variables import GraspableObjectPoseGaussianRV, ParallelJawGraspPoseGaussianRV, ParamsGaussianRV
44
+ from .quality import PointGraspMetrics3D
45
+
46
+ from autolab_core import RigidTransform
47
+ import IPython
48
+
49
+ class GraspQualityResult:
50
+ """ Stores the results of grasp quality computation.
51
+
52
+ Attributes
53
+ ----------
54
+ quality : float
55
+ value of quality
56
+ uncertainty : float
57
+ uncertainty estimate of the quality value
58
+ quality_config : :obj:`GraspQualityConfig`
59
+ """
60
+ def __init__(self, quality, uncertainty=0.0, quality_config=None):
61
+ self.quality = quality
62
+ self.uncertainty = uncertainty
63
+ self.quality_config = quality_config
64
+
65
+ # class GraspQualityFunction(object, metaclass=ABCMeta):
66
+ class GraspQualityFunction(object):
67
+ """
68
+ Abstraction for grasp quality functions to make scripts for labeling with quality functions simple and readable.
69
+
70
+ Attributes
71
+ ----------
72
+ graspable : :obj:`GraspableObject3D`
73
+ object to evaluate grasp quality on
74
+ quality_config : :obj:`GraspQualityConfig`
75
+ set of parameters to evaluate grasp quality
76
+ """
77
+ __metaclass__ = ABCMeta
78
+
79
+
80
+ def __init__(self, graspable, quality_config):
81
+ # check valid types
82
+ if not isinstance(graspable, GraspableObject):
83
+ raise ValueError('Must provide GraspableObject')
84
+ if not isinstance(quality_config, GraspQualityConfig):
85
+ raise ValueError('Must provide GraspQualityConfig')
86
+
87
+ # set member variables
88
+ self.graspable_ = graspable
89
+ self.quality_config_ = quality_config
90
+
91
+ self._setup()
92
+
93
+ def __call__(self, grasp):
94
+ return self.quality(grasp)
95
+
96
+ @abstractmethod
97
+ def _setup(self):
98
+ """ Sets up common variables for grasp quality evaluations """
99
+ pass
100
+
101
+ @abstractmethod
102
+ def quality(self, grasp):
103
+ """ Compute grasp quality.
104
+
105
+ Parameters
106
+ ----------
107
+ grasp : :obj:`GraspableObject3D`
108
+ grasp to quality quality on
109
+
110
+ Returns
111
+ -------
112
+ :obj:`GraspQualityResult`
113
+ result of quality computation
114
+ """
115
+ pass
116
+
117
+ class QuasiStaticQualityFunction(GraspQualityFunction):
118
+ """ Grasp quality metric using a quasi-static model.
119
+ """
120
+ def __init__(self, graspable, quality_config):
121
+ GraspQualityFunction.__init__(self, graspable, quality_config)
122
+
123
+ @property
124
+ def graspable(self):
125
+ return self.graspable_
126
+
127
+ @graspable.setter
128
+ def graspable(self, obj):
129
+ self.graspable_ = obj
130
+
131
+ def _setup(self):
132
+ if self.quality_config_.quality_type != 'quasi_static':
133
+ raise ValueError('Quality configuration must be quasi static')
134
+
135
+ def quality(self, grasp):
136
+ """ Compute grasp quality using a quasistatic method.
137
+
138
+ Parameters
139
+ ----------
140
+ grasp : :obj:`GraspableObject3D`
141
+ grasp to quality quality on
142
+
143
+ Returns
144
+ -------
145
+ :obj:`GraspQualityResult`
146
+ result of quality computation
147
+ """
148
+ if not isinstance(grasp, Grasp):
149
+ raise ValueError('Must provide Grasp object to compute quality')
150
+
151
+ quality = PointGraspMetrics3D.grasp_quality(grasp, self.graspable_,
152
+ self.quality_config_)
153
+ return GraspQualityResult(quality, quality_config=self.quality_config_)
154
+
155
+ class RobustQuasiStaticQualityFunction(GraspQualityFunction):
156
+ """ Grasp quality metric using a robust quasi-static model (average over random perturbations)
157
+ """
158
+ def __init__(self, graspable, quality_config, T_obj_world=RigidTransform(from_frame='obj', to_frame='world')):
159
+ self.T_obj_world_ = T_obj_world
160
+ GraspQualityFunction.__init__(self, graspable, quality_config)
161
+
162
+ @property
163
+ def graspable(self):
164
+ return self.graspable_
165
+
166
+ @graspable.setter
167
+ def graspable(self, obj):
168
+ self.graspable_ = obj
169
+ self._setup()
170
+
171
+ def _setup(self):
172
+ if self.quality_config_.quality_type != 'robust_quasi_static':
173
+ raise ValueError('Quality configuration must be robust quasi static')
174
+ self.graspable_rv_ = GraspableObjectPoseGaussianRV(self.graspable_,
175
+ self.T_obj_world_,
176
+ self.quality_config_.obj_uncertainty)
177
+ self.params_rv_ = ParamsGaussianRV(self.quality_config_,
178
+ self.quality_config_.params_uncertainty)
179
+
180
+ def quality(self, grasp):
181
+ """ Compute grasp quality using a robust quasistatic method.
182
+
183
+ Parameters
184
+ ----------
185
+ grasp : :obj:`GraspableObject3D`
186
+ grasp to quality quality on
187
+
188
+ Returns
189
+ -------
190
+ :obj:`GraspQualityResult`
191
+ result of quality computation
192
+ """
193
+ if not isinstance(grasp, Grasp):
194
+ raise ValueError('Must provide Grasp object to compute quality')
195
+ grasp_rv = ParallelJawGraspPoseGaussianRV(grasp,
196
+ self.quality_config_.grasp_uncertainty)
197
+ mean_q, std_q = RobustPointGraspMetrics3D.expected_quality(grasp_rv,
198
+ self.graspable_rv_,
199
+ self.params_rv_,
200
+ self.quality_config_)
201
+ return GraspQualityResult(mean_q, std_q, quality_config=self.quality_config_)
202
+
203
+ class GraspQualityFunctionFactory:
204
+ @staticmethod
205
+ def create_quality_function(graspable, quality_config):
206
+ """ Creates a quality function for a particular object based on a configuration, which can be passed directly from a configuration file.
207
+
208
+ Parameters
209
+ ----------
210
+ graspable : :obj:`GraspableObject3D`
211
+ object to create quality function for
212
+ quality_config : :obj:`GraspQualityConfig`
213
+ parameters for quality function
214
+ """
215
+ # check valid types
216
+ if not isinstance(graspable, GraspableObject):
217
+ raise ValueError('Must provide GraspableObject')
218
+ if not isinstance(quality_config, GraspQualityConfig):
219
+ raise ValueError('Must provide GraspQualityConfig')
220
+
221
+ if quality_config.quality_type == 'quasi_static':
222
+ return QuasiStaticQualityFunction(graspable, quality_config)
223
+ elif quality_config.quality_type == 'robust_quasi_static':
224
+ return RobustQuasiStaticQualityFunction(graspable, quality_config)
225
+ else:
226
+ raise ValueError('Grasp quality type %s not supported' %(quality_config.quality_type))
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/graspable_object.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+
11
+ IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+
16
+ REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
19
+ HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
20
+ MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
21
+ """
22
+ """
23
+ Encapsulates data and operations on a 2D or 3D object that can be grasped
24
+ Author: Jeff Mahler
25
+ """
26
+ from abc import ABCMeta, abstractmethod
27
+
28
+ import copy
29
+ import logging
30
+ import numpy as np
31
+
32
+ from .meshpy import mesh as m
33
+ from .meshpy import sdf as s
34
+
35
+ import IPython
36
+ import matplotlib.pyplot as plt
37
+
38
+ from autolab_core import RigidTransform, SimilarityTransform
39
+
40
+
41
+ # class GraspableObject(metaclass=ABCMeta):
42
+ class GraspableObject:
43
+ """ Encapsulates geometric structures for computing contact in grasping.
44
+
45
+ Attributes
46
+ ----------
47
+ sdf : :obj:`Sdf3D`
48
+ signed distance field, for quickly computing contact points
49
+ mesh : :obj:`Mesh3D`
50
+ 3D triangular mesh to specify object geometry, should match SDF
51
+ key : :obj:`str`
52
+ object identifier, usually given from the database
53
+ model_name : :obj:`str`
54
+ name of the object mesh as a .obj file, for use in collision checking
55
+ mass : float
56
+ mass of the object
57
+ convex_pieces : :obj:`list` of :obj:`Mesh3D`
58
+ convex decomposition of the object geom for collision checking
59
+ """
60
+ __metaclass__ = ABCMeta
61
+
62
+ def __init__(self, sdf, mesh, key='', model_name='', mass=1.0, convex_pieces=None):
63
+ self.sdf_ = sdf
64
+ self.mesh_ = mesh
65
+
66
+ self.key_ = key
67
+ self.model_name_ = model_name # for OpenRave usage, gross!
68
+ self.mass_ = mass
69
+ self.convex_pieces_ = convex_pieces
70
+
71
+ @property
72
+ def sdf(self):
73
+ return self.sdf_
74
+
75
+ @property
76
+ def mesh(self):
77
+ return self.mesh_
78
+
79
+ @property
80
+ def mass(self):
81
+ return self.mass_
82
+
83
+ @property
84
+ def key(self):
85
+ return self.key_
86
+
87
+ @property
88
+ def model_name(self):
89
+ return self.model_name_
90
+
91
+ @property
92
+ def convex_pieces(self):
93
+ return self.convex_pieces_
94
+
95
+ class GraspableObject3D(GraspableObject):
96
+ """ 3D Graspable object for computing contact in grasping.
97
+
98
+ Attributes
99
+ ----------
100
+ sdf : :obj:`Sdf3D`
101
+ signed distance field, for quickly computing contact points
102
+ mesh : :obj:`Mesh3D`
103
+ 3D triangular mesh to specify object geometry, should match SDF
104
+ key : :obj:`str`
105
+ object identifier, usually given from the database
106
+ model_name : :obj:`str`
107
+ name of the object mesh as a .obj file, for use in collision checking
108
+ mass : float
109
+ mass of the object
110
+ convex_pieces : :obj:`list` of :obj:`Mesh3D`
111
+ convex decomposition of the object geom for collision checking
112
+ """
113
+ def __init__(self, sdf, mesh, key='',
114
+ model_name='', mass=1.0,
115
+ convex_pieces=None):
116
+ if not isinstance(sdf, s.Sdf3D):
117
+ raise ValueError('Must initialize 3D graspable object with 3D sdf')
118
+ if not isinstance(mesh, m.Mesh3D):
119
+ raise ValueError('Must initialize 3D graspable object with 3D mesh')
120
+
121
+ GraspableObject.__init__(self, sdf, mesh, key=key,
122
+ model_name=model_name, mass=mass,
123
+ convex_pieces=convex_pieces)
124
+
125
+ def moment_arm(self, x):
126
+ """ Computes the moment arm to a point x.
127
+
128
+ Parameters
129
+ ----------
130
+ x : 3x1 :obj:`numpy.ndarray`
131
+ point to get moment arm for
132
+
133
+ Returns
134
+ -------
135
+ 3x1 :obj:`numpy.ndarray`
136
+ """
137
+ return x - self.mesh.center_of_mass
138
+
139
+ def rescale(self, scale):
140
+ """ Rescales uniformly by a given factor.
141
+
142
+ Parameters
143
+ ----------
144
+ scale : float
145
+ the amount to scale the object
146
+
147
+ Returns
148
+ -------
149
+ :obj:`GraspableObject3D`
150
+ the graspable object rescaled by the given factor
151
+ """
152
+ stf = SimilarityTransform(scale=scale)
153
+ sdf_rescaled = self.sdf_.rescale(scale)
154
+ mesh_rescaled = self.mesh_.transform(stf)
155
+ convex_pieces_rescaled = None
156
+ if self.convex_pieces_ is not None:
157
+ convex_pieces_rescaled = []
158
+ for convex_piece in self.convex_pieces_:
159
+ convex_piece_rescaled = convex_piece.transform(stf)
160
+ convex_pieces_rescaled.append(convex_piece_rescaled)
161
+ return GraspableObject3D(sdf_rescaled, mesh_rescaled, key=self.key,
162
+ model_name=self.model_name, mass=self.mass,
163
+ convex_pieces=convex_pieces_rescaled)
164
+
165
+ def transform(self, delta_T):
166
+ """ Transform by a delta transform.
167
+
168
+
169
+ Parameters
170
+ ----------
171
+ delta_T : :obj:`RigidTransform`
172
+ the transformation from the current reference frame to the alternate reference frame
173
+
174
+ Returns
175
+ -------
176
+ :obj:`GraspableObject3D`
177
+ graspable object trasnformed by the delta
178
+ """
179
+ sdf_tf = self.sdf_.transform(delta_T)
180
+ mesh_tf = self.mesh_.transform(delta_T)
181
+ convex_pieces_tf = None
182
+ if self.convex_pieces_ is not None:
183
+ convex_pieces_tf = []
184
+ for convex_piece in self.convex_pieces_:
185
+ convex_piece_tf = convex_piece.transform(delta_T)
186
+ convex_pieces_tf.append(convex_piece_tf)
187
+ return GraspableObject3D(sdf_tf, mesh_tf, key=self.key,
188
+ model_name=self.model_name, mass=self.mass,
189
+ convex_pieces=convex_pieces_tf)
190
+
191
+ def surface_information(self, grasp, width, num_steps, plot=False, direction1=None, direction2=None):
192
+ """ Returns the patches on this object for a given grasp.
193
+
194
+ Parameters
195
+ ----------
196
+ grasp : :obj:`ParallelJawPtGrasp3D`
197
+ grasp to get the patch information for
198
+ width : float
199
+ width of jaw opening
200
+ num_steps : int
201
+ number of steps
202
+ plot : bool
203
+ whether to plot the intermediate computation, for debugging
204
+ direction1 : normalized 3x1 :obj:`numpy.ndarray`
205
+ direction along which to compute the surface information for the first jaw, if None then defaults to grasp axis
206
+ direction2 : normalized 3x1 :obj:`numpy.ndarray`
207
+ direction along which to compute the surface information for the second jaw, if None then defaults to grasp axis
208
+
209
+ Returns
210
+ -------
211
+ :obj:`list` of :obj:`SurfaceWindow`
212
+ surface patches, one for each contact
213
+ """
214
+ contacts_found, contacts = grasp.close_fingers(self)#, vis=True)
215
+ if not contacts_found:
216
+ raise ValueError('Failed to find contacts')
217
+ contact1, contact2 = contacts
218
+
219
+ if plot:
220
+ plt.figure()
221
+ contact1.plot_friction_cone()
222
+ contact2.plot_friction_cone()
223
+
224
+ ax = plt.gca(projection = '3d')
225
+ ax.set_xlim3d(0, self.sdf.dims_[0])
226
+ ax.set_ylim3d(0, self.sdf.dims_[1])
227
+ ax.set_zlim3d(0, self.sdf.dims_[2])
228
+
229
+ window1 = contact1.surface_information(width, num_steps, direction=direction1)
230
+ window2 = contact2.surface_information(width, num_steps, direction=direction2)
231
+ return window1, window2, contact1, contact2
232
+
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2017 Berkeley AUTOLAB & University of California, Berkeley
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # try:
2
+ # # from meshpy import meshrender
3
+ # import meshrender
4
+ # except:
5
+ # print('Unable to import meshrender shared library! Rendering will not work. Likely due to missing Boost.Numpy')
6
+ # print('Boost.Numpy can be installed following the instructions in https://github.com/ndarray/Boost.NumPy')
7
+ from .mesh import Mesh3D
8
+ # from .image_converter import ImageToMeshConverter
9
+ from .obj_file import ObjFile
10
+ # from .off_file import OffFile
11
+ # from .render_modes import RenderMode
12
+ from .sdf import Sdf, Sdf3D
13
+ from .sdf_file import SdfFile
14
+ from .stable_pose import StablePose
15
+ from . import mesh
16
+ from . import obj_file
17
+ from . import sdf_file
18
+ # from .stp_file import StablePoseFile
19
+ # from .urdf_writer import UrdfWriter, convex_decomposition
20
+ # from .lighting import MaterialProperties, LightingProperties
21
+
22
+ # from .mesh_renderer import ViewsphereDiscretizer, PlanarWorksurfaceDiscretizer, VirtualCamera, SceneObject
23
+ # from .random_variables import CameraSample, RenderSample, UniformViewsphereRandomVariable, \
24
+ # UniformPlanarWorksurfaceRandomVariable, UniformPlanarWorksurfaceImageRandomVariable
25
+
26
+ __all__ = ['Mesh3D','ObjFile','Sdf','Sdf3D','SdfFile','StablePose','mesh','obj_file','sdf_file']
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/mesh.py ADDED
@@ -0,0 +1,1957 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Encapsulates mesh for grasping operations
3
+ Authors: Jeff Mahler and Matt Matl
4
+ """
5
+ import math
6
+ try:
7
+ import queue
8
+ except ImportError:
9
+ import Queue as queue
10
+ import os
11
+ import random
12
+ from subprocess import Popen
13
+ import sys
14
+
15
+ import numpy as np
16
+ import scipy.spatial as ss
17
+ import sklearn.decomposition
18
+ import trimesh as tm
19
+
20
+ from autolab_core import RigidTransform, Point, Direction, PointCloud, NormalCloud
21
+
22
+ from . import obj_file
23
+ from . import stable_pose as sp
24
+
25
+
26
+ class Mesh3D(object):
27
+ """A triangular mesh for a three-dimensional shape representation.
28
+
29
+ Attributes
30
+ ----------
31
+ vertices : :obj:`numpy.ndarray` of float
32
+ A #verts by 3 array, where each row contains an ordered
33
+ [x,y,z] set that describes one vertex.
34
+ triangles : :obj:`numpy.ndarray` of int
35
+ A #tris by 3 array, where each row contains indices of vertices in
36
+ the `vertices` array that are part of the triangle.
37
+ normals : :obj:`numpy.ndarray` of float
38
+ A #normals by 3 array, where each row contains a normalized
39
+ vector. This list should contain one norm per vertex.
40
+ density : float
41
+ The density of the mesh.
42
+ center_of_mass : :obj:`numpy.ndarray` of float
43
+ The 3D location of the mesh's center of mass.
44
+ mass : float
45
+ The mass of the mesh (read-only).
46
+ inertia : :obj:`numpy.ndarray` of float
47
+ The 3x3 inertial matrix of the mesh (read-only).
48
+ bb_center : :obj:`numpy.ndarray` of float
49
+ The 3D location of the center of the mesh's minimal bounding box
50
+ (read-only).
51
+ centroid : :obj:`numpy.ndarray` of float
52
+ The 3D location of the mesh's vertex mean (read-only).
53
+ """
54
+
55
+ ScalingTypeMin = 0
56
+ ScalingTypeMed = 1
57
+ ScalingTypeMax = 2
58
+ ScalingTypeRelative = 3
59
+ ScalingTypeDiag = 4
60
+ OBJ_EXT = '.obj'
61
+ PROC_TAG = '_proc'
62
+ C_canonical = np.array([[1.0 / 60.0, 1.0 / 120.0, 1.0 / 120.0],
63
+ [1.0 / 120.0, 1.0 / 60.0, 1.0 / 120.0],
64
+ [1.0 / 120.0, 1.0 / 120.0, 1.0 / 60.0]])
65
+
66
+ def __init__(self, vertices, triangles, normals=None,
67
+ density=1.0, center_of_mass=None,
68
+ trimesh=None, T_obj_world=RigidTransform(from_frame='obj', to_frame='world')):
69
+ """Construct a 3D triangular mesh.
70
+
71
+ Parameters
72
+ ----------
73
+ vertices : :obj:`numpy.ndarray` of float
74
+ A #verts by 3 array, where each row contains an ordered
75
+ [x,y,z] set that describes one vertex.
76
+ triangles : :obj:`numpy.ndarray` of int
77
+ A #tris by 3 array, where each row contains indices of vertices in
78
+ the `vertices` array that are part of the triangle.
79
+ normals : :obj:`numpy.ndarray` of float
80
+ A #normals by 3 array, where each row contains a normalized
81
+ vector. This list should contain one norm per vertex.
82
+ density : float
83
+ The density of the mesh.
84
+ center_of_mass : :obj:`numpy.ndarray` of float
85
+ The 3D location of the mesh's center of mass.
86
+ uniform_com : bool
87
+ Whether or not to assume a uniform mass density for center of mass comp
88
+ """
89
+ if vertices is not None:
90
+ vertices = np.array(vertices)
91
+ self.vertices_ = vertices
92
+
93
+ if triangles is not None:
94
+ triangles = np.array(triangles)
95
+ self.triangles_ = triangles
96
+
97
+ if normals is not None:
98
+ normals = np.array(normals)
99
+ if normals.shape[0] == 3:
100
+ normals = normals.T
101
+ self.normals_ = normals
102
+
103
+ self.density_ = density
104
+
105
+ self.center_of_mass_ = center_of_mass
106
+
107
+ # Read-Only parameter initialization
108
+ self.mass_ = None
109
+ self.inertia_ = None
110
+ self.bb_center_ = self._compute_bb_center()
111
+ self.centroid_ = self._compute_centroid()
112
+ self.surface_area_ = None
113
+ self.face_dag_ = None
114
+ self.trimesh_ = trimesh
115
+ self.T_obj_world_ = T_obj_world
116
+
117
+ if self.center_of_mass_ is None:
118
+ if self.is_watertight:
119
+ self.center_of_mass_ = np.array(self._compute_com_uniform())
120
+ else:
121
+ self.center_of_mass_ = np.array(self.bb_center_)
122
+
123
+ ##################################################################
124
+ # Properties
125
+ ##################################################################
126
+
127
+ # =============================================
128
+ # Read-Write Properties
129
+ # =============================================
130
+ @property
131
+ def vertices(self):
132
+ """:obj:`numpy.ndarray` of float : A #verts by 3 array,
133
+ where each row contains an ordered
134
+ [x,y,z] set that describes one vertex.
135
+ """
136
+ return self.vertices_
137
+
138
+ @vertices.setter
139
+ def vertices(self, v):
140
+ self.vertices_ = np.array(v)
141
+ self.mass_ = None
142
+ self.inertia_ = None
143
+ self.normals_ = None
144
+ self.surface_area_ = None
145
+ self.bb_center_ = self._compute_bb_center()
146
+ self.centroid_ = self._compute_centroid()
147
+
148
+ @property
149
+ def triangles(self):
150
+ """:obj:`numpy.ndarray` of int : A #tris by 3 array,
151
+ where each row contains indices of vertices in
152
+ the `vertices` array that are part of the triangle.
153
+ """
154
+ return self.triangles_
155
+
156
+ @triangles.setter
157
+ def triangles(self, t):
158
+ self.triangles_ = np.array(t)
159
+ self.mass_ = None
160
+ self.inertia_ = None
161
+ self.surface_area_ = None
162
+
163
+ @property
164
+ def normals(self):
165
+ """:obj:`numpy.ndarray` of float :
166
+ A #normals by 3 array, where each row contains a normalized
167
+ vector. This list should contain one norm per vertex.
168
+ """
169
+ return self.normals_
170
+
171
+ @normals.setter
172
+ def normals(self, n):
173
+ self.normals_ = np.array(n)
174
+
175
+ @property
176
+ def density(self):
177
+ """float : The density of the mesh.
178
+ """
179
+ return self.density_
180
+
181
+ @density.setter
182
+ def density(self, d):
183
+ self.density_ = d
184
+ self.mass_ = None
185
+ self.inertia_ = None
186
+
187
+ @property
188
+ def center_of_mass(self):
189
+ """:obj:`numpy.ndarray` of float :
190
+ The 3D location of the mesh's center of mass.
191
+ """
192
+ return self.center_of_mass_
193
+
194
+ @center_of_mass.setter
195
+ def center_of_mass(self, com):
196
+ self.center_of_mass_ = com
197
+ self.inertia_ = None
198
+
199
+ @property
200
+ def num_vertices(self):
201
+ """ :obj:`int`:
202
+ The number of total vertices
203
+ """
204
+ return self.vertices.shape[0]
205
+
206
+ @property
207
+ def num_triangles(self):
208
+ """ :obj:`int`:
209
+ The number of total triangles
210
+ """
211
+ return self.triangles.shape[0]
212
+
213
+ # =============================================
214
+ # Read-Only Properties
215
+ # =============================================
216
+ @property
217
+ def mass(self):
218
+ """float : The mass of the mesh (read-only).
219
+ """
220
+ if self.mass_ is None:
221
+ self.mass_ = self._compute_mass()
222
+ return self.mass_
223
+
224
+ @property
225
+ def inertia(self):
226
+ """:obj:`numpy.ndarray` of float :
227
+ The 3x3 inertial matrix of the mesh (read-only).
228
+ """
229
+ if self.inertia_ is None:
230
+ self.inertia_ = self._compute_inertia()
231
+ return self.inertia_
232
+
233
+ @property
234
+ def bb_center(self):
235
+ """:obj:`numpy.ndarray` of float :
236
+ The 3D location of the center of the mesh's minimal bounding box
237
+ (read-only).
238
+ """
239
+ return self.bb_center_
240
+
241
+ @property
242
+ def centroid(self):
243
+ """:obj:`numpy.ndarray` of float :
244
+ The 3D location of the mesh's vertex mean (read-only).
245
+ """
246
+ return self.centroid_
247
+
248
+ ##################################################################
249
+ # Public Class Methods
250
+ ##################################################################
251
+
252
+ def min_coords(self):
253
+ """Returns the minimum coordinates of the mesh.
254
+
255
+ Returns
256
+ -------
257
+ :obj:`numpy.ndarray` of float
258
+ A 3-ndarray of floats that represents the minimal
259
+ x, y, and z coordinates represented in the mesh.
260
+ """
261
+ return np.min(self.vertices_, axis=0)
262
+
263
+ def max_coords(self):
264
+ """Returns the maximum coordinates of the mesh.
265
+
266
+ Returns
267
+ -------
268
+ :obj:`numpy.ndarray` of float
269
+ A 3-ndarray of floats that represents the minimal
270
+ x, y, and z coordinates represented in the mesh.
271
+ """
272
+ return np.max(self.vertices_, axis=0)
273
+
274
+ def bounding_box(self):
275
+ """Returns the mesh's bounding box corners.
276
+
277
+ Returns
278
+ -------
279
+ :obj:`tuple` of :obj:`numpy.ndarray` of float
280
+ A 2-tuple of 3-ndarrays of floats. The first 3-array
281
+ contains the vertex of the smallest corner of the bounding box,
282
+ and the second 3-array contains the largest corner of the bounding
283
+ box.
284
+ """
285
+ return self.min_coords(), self.max_coords()
286
+
287
+ def bounding_box_mesh(self):
288
+ """Returns the mesh bounding box as a mesh.
289
+
290
+ Returns
291
+ -------
292
+ :obj:`Mesh3D`
293
+ A Mesh3D representation of the mesh's bounding box.
294
+ """
295
+ min_vert, max_vert = self.bounding_box()
296
+ xs, ys, zs = list(zip(max_vert, min_vert))
297
+ vertices = []
298
+ for x in xs:
299
+ for y in ys:
300
+ for z in zs:
301
+ vertices.append([x, y, z])
302
+ triangles = (np.array([
303
+ [5, 7, 3], [5, 3, 1],
304
+ [2, 4, 8], [2, 8, 6],
305
+ [6, 8, 7], [6, 7, 5],
306
+ [1, 3, 4], [1, 4, 2],
307
+ [6, 5, 1], [6, 1, 2],
308
+ [7, 8, 4], [7, 4, 3],
309
+ ]) - 1)
310
+ return Mesh3D(vertices, triangles)
311
+
312
+ def principal_dims(self):
313
+ """Returns the maximal span of the mesh's coordinates.
314
+
315
+ The maximal span is the maximum coordinate value minus
316
+ the minimal coordinate value in each principal axis.
317
+
318
+ Returns
319
+ -------
320
+ :obj:`numpy.ndarray` of float
321
+ A 3-ndarray of floats that represents the maximal
322
+ x, y, and z spans of the mesh.
323
+ """
324
+ return self.max_coords() - self.min_coords()
325
+
326
+ def support(self, direction):
327
+ """Returns the support function in the given direction
328
+
329
+ Parameters
330
+ ----------
331
+ direction : :obj:`numpy.ndarray` of float
332
+ A 3-ndarray of floats that is a unit vector in
333
+ the direction of the desired support.
334
+
335
+ Returns
336
+ -------
337
+ :obj:`numpy.ndarray` of float
338
+ A 3-ndarray of floats that represents the support.
339
+ """
340
+ ip = self.vertices_.dot(direction)
341
+ index = np.where(ip == np.max(ip))[0][0]
342
+ x0 = self.vertices_[index, :]
343
+ n = direction
344
+ com_proj = x0.dot(n) * n
345
+ return com_proj
346
+
347
+ def tri_centers(self):
348
+ """Returns an array of the triangle centers as 3D points.
349
+
350
+ Returns
351
+ -------
352
+ :obj:`numpy.ndarray` of :obj:`numpy.ndarray` of float
353
+ An ndarray of 3-ndarrays of floats, where each 3-ndarray
354
+ represents the 3D point at the center of the corresponding
355
+ mesh triangle.
356
+ """
357
+ centers = []
358
+ for tri in self.triangles_:
359
+ centers.append(self._center_of_tri(tri))
360
+ return np.array(centers)
361
+
362
+ def tri_normals(self, align_to_hull=False):
363
+ """Returns a list of the triangle normals.
364
+
365
+ Parameters
366
+ ----------
367
+ align_to_hull : bool
368
+ If true, we re-orient the normals to point outward from
369
+ the mesh by using the convex hull.
370
+
371
+ Returns
372
+ -------
373
+ :obj:`numpy.ndarray` of float
374
+ A #triangles by 3 array of floats, where each 3-ndarray
375
+ represents the 3D normal vector of the corresponding triangle.
376
+ """
377
+ # compute normals
378
+ v0 = self.vertices_[self.triangles_[:, 0], :]
379
+ v1 = self.vertices_[self.triangles_[:, 1], :]
380
+ v2 = self.vertices_[self.triangles_[:, 2], :]
381
+ n = np.cross(v1 - v0, v2 - v0)
382
+ normals = n / np.tile(np.linalg.norm(n, axis=1)[:, np.newaxis], [1, 3])
383
+
384
+ # reverse normal based on alignment with convex hull
385
+ if align_to_hull:
386
+ tri_centers = self.tri_centers()
387
+ hull = ss.ConvexHull(tri_centers)
388
+ hull_tris = hull.simplices
389
+ hull_vertex_ind = hull_tris[0][0]
390
+ hull_vertex = tri_centers[hull_vertex_ind]
391
+ hull_vertex_normal = normals[hull_vertex_ind]
392
+ v = hull_vertex.reshape([1, 3])
393
+ n = hull_vertex_normal
394
+ ip = (tri_centers - np.tile(hull_vertex,
395
+ [tri_centers.shape[0], 1])).dot(n)
396
+ if ip[0] > 0:
397
+ normals = -normals
398
+ return normals
399
+
400
+ def surface_area(self):
401
+ """Return the surface area of the mesh.
402
+
403
+ Returns
404
+ -------
405
+ float
406
+ The surface area of the mesh.
407
+ """
408
+ if self.surface_area_ is None:
409
+ area = 0.0
410
+ for tri in self.triangles:
411
+ tri_area = self._area_of_tri(tri)
412
+ area += tri_area
413
+ self.surface_area_ = area
414
+ return self.surface_area_
415
+
416
+ def total_volume(self):
417
+ """Return the total volume of the mesh.
418
+
419
+ Returns
420
+ -------
421
+ float
422
+ The total volume of the mesh.
423
+ """
424
+ total_volume = 0
425
+ for tri in self.triangles_:
426
+ volume = self._signed_volume_of_tri(tri)
427
+ total_volume = total_volume + volume
428
+
429
+ # Correct for flipped triangles
430
+ if total_volume < 0:
431
+ total_volume = -total_volume
432
+ return total_volume
433
+
434
+ def covariance(self):
435
+ """Return the total covariance of the mesh's triangles.
436
+
437
+ Returns
438
+ -------
439
+ float
440
+ The total covariance of the mesh's triangles.
441
+ """
442
+ C_sum = np.zeros([3, 3])
443
+ for tri in self.triangles_:
444
+ C = self._covariance_of_tri(tri)
445
+ C_sum = C_sum + C
446
+ return C_sum
447
+
448
+ def remove_bad_tris(self):
449
+ """Remove triangles with out-of-bounds vertices from the mesh.
450
+ """
451
+ new_tris = []
452
+ num_v = self.vertices_.shape[0]
453
+ for t in self.triangles_:
454
+ if (t[0] >= 0 and t[0] < num_v and
455
+ t[1] >= 0 and t[1] < num_v and
456
+ t[2] >= 0 and t[2] < num_v):
457
+ new_tris.append(t)
458
+ self.triangles = np.array(new_tris)
459
+
460
+ def remove_unreferenced_vertices(self):
461
+ """Remove any vertices that are not part of a triangular face.
462
+
463
+ Note
464
+ ----
465
+ This method will fail if any bad triangles are present, so run
466
+ remove_bad_tris() first if you're unsure if bad triangles are present.
467
+
468
+ Returns
469
+ -------
470
+ bool
471
+ Returns True if vertices were removed, False otherwise.
472
+
473
+ """
474
+ num_v = self.vertices_.shape[0]
475
+
476
+ # Fill in a 1 for each referenced vertex
477
+ reffed_array = np.zeros([num_v, 1])
478
+ for f in self.triangles_:
479
+ reffed_array[f[0]] = 1
480
+ reffed_array[f[1]] = 1
481
+ reffed_array[f[2]] = 1
482
+
483
+ # Trim out vertices that are not referenced
484
+ reffed_v_old_ind = np.where(reffed_array == 1)
485
+ reffed_v_old_ind = reffed_v_old_ind[0]
486
+
487
+ # Count number of referenced vertices before each index
488
+ reffed_v_new_ind = np.cumsum(reffed_array).astype(np.int) - 1
489
+
490
+ try:
491
+ self.vertices = self.vertices_[reffed_v_old_ind, :]
492
+ if self.normals is not None:
493
+ self.normals = self.normals[reffed_v_old_ind, :]
494
+ except IndexError:
495
+ return False
496
+
497
+ # create new face indices
498
+ new_triangles = []
499
+ for f in self.triangles_:
500
+ new_triangles.append([reffed_v_new_ind[f[0]],
501
+ reffed_v_new_ind[f[1]],
502
+ reffed_v_new_ind[f[2]]])
503
+ self.triangles = np.array(new_triangles)
504
+ return True
505
+
506
+ def center_vertices_avg(self):
507
+ """Center the mesh's vertices at the centroid.
508
+
509
+ This shifts the mesh without rotating it so that
510
+ the centroid (mean) of all vertices is at the origin.
511
+ """
512
+ centroid = np.mean(self.vertices_, axis=0)
513
+ self.vertices = self.vertices_ - centroid
514
+
515
+ def center_vertices_bb(self):
516
+ """Center the mesh's vertices at the center of its bounding box.
517
+
518
+ This shifts the mesh without rotating it so that
519
+ the center of its bounding box is at the origin.
520
+ """
521
+ min_vertex = self.min_coords()
522
+ max_vertex = self.max_coords()
523
+ center = (max_vertex + min_vertex) / 2
524
+ self.vertices = self.vertices_ - center
525
+
526
+ def center_vertices(self):
527
+ """Center the mesh's vertices on the mesh center of mass.
528
+
529
+ This shifts the mesh without rotating it so that
530
+ the center of its bounding box is at the origin.
531
+ """
532
+ self.vertices = self.vertices_ - self.center_of_mass_
533
+ self.trimesh_ = None # flag re-comp of trimesh
534
+
535
+ def normalize_vertices(self):
536
+ """Normalize the mesh's orientation along its principal axes.
537
+
538
+ Transforms the vertices and normals of the mesh
539
+ such that the origin of the resulting mesh's coordinate frame
540
+ is at the center of the bounding box and the principal axes (as determined
541
+ from PCA) are aligned with the vertical Z, Y, and X axes in that order.
542
+ """
543
+
544
+ self.center_vertices_bb()
545
+
546
+ # Find principal axes
547
+ pca = sklearn.decomposition.PCA(n_components=3)
548
+ pca.fit(self.vertices_)
549
+
550
+ # Count num vertices on side of origin wrt principal axes
551
+ # to determine correct orientation
552
+ comp_array = pca.components_
553
+ norm_proj = self.vertices_.dot(comp_array.T)
554
+ opposite_aligned = np.sum(norm_proj < 0, axis=0)
555
+ same_aligned = np.sum(norm_proj >= 0, axis=0)
556
+
557
+ # create rotation from principal axes to standard basis
558
+ z_axis = comp_array[0, :]
559
+ y_axis = comp_array[1, :]
560
+ if opposite_aligned[2] > same_aligned[2]:
561
+ z_axis = -z_axis
562
+ if opposite_aligned[1] > same_aligned[1]:
563
+ y_axis = -y_axis
564
+ x_axis = np.cross(y_axis, z_axis)
565
+ R_pc_obj = np.c_[x_axis, y_axis, z_axis]
566
+
567
+ # rotate vertices, normals and reassign to the mesh
568
+ self.vertices = (R_pc_obj.T.dot(self.vertices.T)).T
569
+ self.center_vertices_bb()
570
+
571
+ # TODO JEFF LOOK HERE (BUG IN INITIAL CODE FROM MESHPROCESSOR)
572
+ if self.normals_ is not None:
573
+ self.normals = (R_pc_obj.T.dot(self.normals.T)).T
574
+
575
+ def compute_vertex_normals(self):
576
+ """ Get normals from triangles"""
577
+ normals = []
578
+ # weighted average of triangle normal for each vertex
579
+ for i in range(len(self.vertices)):
580
+ inds = np.where(self.triangles == i)
581
+ tris = self.triangles[inds[0], :]
582
+ normal = np.zeros(3)
583
+ for tri in tris:
584
+ # compute triangle normal
585
+ t = self.vertices[tri, :]
586
+ v0 = t[1, :] - t[0, :]
587
+ v1 = t[2, :] - t[0, :]
588
+ if np.linalg.norm(v0) == 0:
589
+ continue
590
+ v0 = v0 / np.linalg.norm(v0)
591
+ if np.linalg.norm(v1) == 0:
592
+ continue
593
+ v1 = v1 / np.linalg.norm(v1)
594
+ n = np.cross(v0, v1)
595
+ if np.linalg.norm(n) == 0:
596
+ continue
597
+ n = n / np.linalg.norm(n)
598
+
599
+ # compute weight by area of triangle
600
+ w_area = self._area_of_tri(tri)
601
+
602
+ # compute weight by edge angle
603
+ vertex_ind = np.where(tri == i)[0][0]
604
+ if vertex_ind == 0:
605
+ e0 = t[1, :] - t[0, :]
606
+ e1 = t[2, :] - t[0, :]
607
+ elif vertex_ind == 1:
608
+ e0 = t[0, :] - t[1, :]
609
+ e1 = t[2, :] - t[1, :]
610
+ elif vertex_ind == 2:
611
+ e0 = t[0, :] - t[2, :]
612
+ e1 = t[1, :] - t[2, :]
613
+ if np.linalg.norm(e0) == 0:
614
+ continue
615
+ if np.linalg.norm(e1) == 0:
616
+ continue
617
+ e0 = e0 / np.linalg.norm(e0)
618
+ e1 = e1 / np.linalg.norm(e1)
619
+ w_angle = np.arccos(e0.dot(e1))
620
+
621
+ # weighted update
622
+ # www.bytehazard.com/articles/vertnorm.html
623
+ normal += w_area * w_angle * n
624
+
625
+ # normalize
626
+ if np.linalg.norm(normal) == 0:
627
+ normal = np.array([1, 0, 0])
628
+ normal = normal / np.linalg.norm(normal)
629
+ normals.append(normal)
630
+
631
+ # set numpy array
632
+ self.normals = np.array(normals)
633
+
634
+ # reverse normals based on alignment with convex hull
635
+ hull = ss.ConvexHull(self.vertices)
636
+ hull_tris = hull.simplices.tolist()
637
+ hull_vertex_inds = np.unique(hull_tris)
638
+
639
+ num_aligned = 0
640
+ num_misaligned = 0
641
+ for hull_vertex_ind in hull_vertex_inds:
642
+ hull_vertex = self.vertices[hull_vertex_ind, :]
643
+ hull_vertex_normal = normals[hull_vertex_ind]
644
+ ip = (hull_vertex - self.vertices).dot(hull_vertex_normal)
645
+ num_aligned += np.sum(ip > 0)
646
+ num_misaligned += np.sum(ip <= 0)
647
+
648
+ if num_misaligned > num_aligned:
649
+ self.normals = -self.normals
650
+
651
+ def flip_normals(self):
652
+ """ Flips the mesh normals. """
653
+ if self.normals is not None:
654
+ self.normals = -self.normals
655
+ return True
656
+ return False
657
+
658
+ def scale_principal_eigenvalues(self, new_evals):
659
+ self.normalize_vertices()
660
+
661
+ pca = sklearn.decomposition.PCA(n_components=3)
662
+ pca.fit(self.vertices_)
663
+
664
+ evals = pca.explained_variance_
665
+ if len(new_evals) == 3:
666
+ self.vertices[:, 0] *= new_evals[2] / np.sqrt(evals[2])
667
+ self.vertices[:, 1] *= new_evals[1] / np.sqrt(evals[1])
668
+ self.vertices[:, 2] *= new_evals[0] / np.sqrt(evals[0])
669
+ elif len(new_evals) == 2:
670
+ self.vertices[:, 1] *= new_evals[1] / np.sqrt(evals[1])
671
+ self.vertices[:, 2] *= new_evals[0] / np.sqrt(evals[0])
672
+ elif len(new_evals) == 1:
673
+ self.vertices[:, 0] *= new_evals[0] / np.sqrt(evals[0])
674
+ self.vertices[:, 1] *= new_evals[0] / np.sqrt(evals[0])
675
+ self.vertices[:, 2] *= new_evals[0] / np.sqrt(evals[0])
676
+
677
+ self.center_vertices_bb()
678
+ return evals
679
+
680
+ def copy(self):
681
+ """Return a copy of the mesh.
682
+
683
+ Note
684
+ ----
685
+ This method only copies the vertices and triangles of the mesh.
686
+ """
687
+ return Mesh3D(np.copy(self.vertices_), np.copy(self.triangles_))
688
+
689
+ def subdivide(self, min_tri_length=np.inf):
690
+ """Return a copy of the mesh that has been subdivided by one iteration.
691
+
692
+ Note
693
+ ----
694
+ This method only copies the vertices and triangles of the mesh.
695
+ """
696
+ new_vertices = self.vertices.tolist()
697
+ old_triangles = self.triangles.tolist()
698
+
699
+ new_triangles = []
700
+ tri_queue = queue.Queue()
701
+
702
+ for j, triangle in enumerate(old_triangles):
703
+ tri_queue.put((j, triangle))
704
+
705
+ num_subdivisions_per_tri = np.zeros(len(old_triangles))
706
+ while not tri_queue.empty():
707
+ tri_index_pair = tri_queue.get()
708
+ j = tri_index_pair[0]
709
+ triangle = tri_index_pair[1]
710
+
711
+ if (np.isinf(min_tri_length) and num_subdivisions_per_tri[j] == 0) or \
712
+ (Mesh3D._max_edge_length(triangle, new_vertices) > min_tri_length):
713
+
714
+ # subdivide
715
+ t_vertices = np.array([new_vertices[i] for i in triangle])
716
+ edge01 = 0.5 * (t_vertices[0, :] + t_vertices[1, :])
717
+ edge12 = 0.5 * (t_vertices[1, :] + t_vertices[2, :])
718
+ edge02 = 0.5 * (t_vertices[0, :] + t_vertices[2, :])
719
+
720
+ i_01 = len(new_vertices)
721
+ i_12 = len(new_vertices) + 1
722
+ i_02 = len(new_vertices) + 2
723
+ new_vertices.append(edge01)
724
+ new_vertices.append(edge12)
725
+ new_vertices.append(edge02)
726
+
727
+ num_subdivisions_per_tri[j] += 1
728
+
729
+ for triplet in [[triangle[0], i_01, i_02],
730
+ [triangle[1], i_12, i_01],
731
+ [triangle[2], i_02, i_12],
732
+ [i_01, i_12, i_02]]:
733
+ tri_queue.put((j, triplet))
734
+
735
+ else:
736
+ # add to final list
737
+ new_triangles.append(triangle)
738
+
739
+ return Mesh3D(np.array(new_vertices), np.array(new_triangles),
740
+ center_of_mass=self.center_of_mass)
741
+
742
+ def transform(self, T):
743
+ """Return a copy of the mesh that has been transformed by T.
744
+
745
+ Parameters
746
+ ----------
747
+ T : :obj:`RigidTransform`
748
+ The RigidTransform by which the mesh is transformed.
749
+
750
+ Note
751
+ ----
752
+ This method only copies the vertices and triangles of the mesh.
753
+ """
754
+ vertex_cloud = PointCloud(self.vertices_.T, frame=T.from_frame)
755
+ vertex_cloud_tf = T * vertex_cloud
756
+ vertices = vertex_cloud_tf.data.T
757
+ if self.normals_ is not None:
758
+ normal_cloud = NormalCloud(self.normals_.T, frame=T.from_frame)
759
+ normal_cloud_tf = T * normal_cloud
760
+ normals = normal_cloud_tf.data.T
761
+ com = Point(self.center_of_mass_, frame=T.from_frame)
762
+ com_tf = T * com
763
+
764
+ if self.normals_ is not None:
765
+ return Mesh3D(vertices.copy(), self.triangles.copy(), normals=normals.copy(), center_of_mass=com_tf.data)
766
+ return Mesh3D(vertices.copy(), self.triangles.copy(), center_of_mass=com_tf.data)
767
+
768
+ def update_tf(self, delta_T):
769
+ """ Updates the mesh transformation. """
770
+ new_T_obj_world = self.T_obj_world * delta_T.inverse().as_frames('obj', 'obj')
771
+ return Mesh3D(self.vertices, self.triangles, normals=self.normals, trimesh=self.trimesh,
772
+ T_obj_world=new_T_obj_world)
773
+
774
+ def random_points(self, n_points):
775
+ """Generate uniformly random points on the surface of the mesh.
776
+
777
+ Parameters
778
+ ----------
779
+ n_points : int
780
+ The number of random points to generate.
781
+
782
+ Returns
783
+ -------
784
+ :obj:`numpy.ndarray` of float
785
+ A n_points by 3 ndarray that contains the sampled 3D points.
786
+ """
787
+ probs = self._tri_area_percentages()
788
+ tri_inds = np.random.choice(list(range(len(probs))), n_points, p=probs)
789
+ points = []
790
+ for tri_ind in tri_inds:
791
+ tri = self.triangles[tri_ind]
792
+ points.append(self._rand_point_on_tri(tri))
793
+ return np.array(points)
794
+
795
+ def ray_intersections(self, ray, point, distance):
796
+ """Returns a list containing the indices of the triangles that
797
+ are intersected by the given ray emanating from the given point
798
+ within some distance.
799
+ """
800
+ ray = ray / np.linalg.norm(ray)
801
+ norms = self.tri_normals()
802
+ tri_point_pairs = []
803
+ for i, tri in enumerate(self.triangles):
804
+ if np.dot(ray, norms[i]) == 0.0:
805
+ continue
806
+ t = -1 * np.dot((point - self.vertices[tri[0]]), norms[i]) / (np.dot(ray, norms[i]))
807
+ if (t > 0 and t <= distance):
808
+ contact_point = point + t * ray
809
+ tri_verts = [self.vertices[j] for j in tri]
810
+ if Mesh3D._point_in_tri(tri_verts, contact_point):
811
+ tri_point_pairs.append((i, contact_point))
812
+ return tri_point_pairs
813
+
814
+ def get_T_surface_obj(self, T_obj_surface, delta=0.0):
815
+ """ Gets the transformation that puts the object resting exactly on
816
+ the z=delta plane
817
+
818
+ Parameters
819
+ ----------
820
+ T_obj_surface : :obj:`RigidTransform`
821
+ The RigidTransform by which the mesh is transformed.
822
+ delta : float
823
+ Z-coordinate to rest the mesh on
824
+
825
+ Note
826
+ ----
827
+ This method copies the vertices and triangles of the mesh.
828
+ """
829
+ T_obj_surface_ori = T_obj_surface.copy()
830
+ T_obj_surface_ori.translation = np.zeros(3)
831
+ obj_tf = self.transform(T_obj_surface_ori)
832
+ mn, mx = obj_tf.bounding_box()
833
+
834
+ z = mn[2]
835
+ x0 = np.array([0, 0, -z + delta])
836
+
837
+ T_obj_surface = RigidTransform(rotation=T_obj_surface_ori.rotation,
838
+ translation=x0, from_frame='obj',
839
+ to_frame='surface')
840
+ return T_obj_surface
841
+
842
+ def rescale_dimension(self, scale, scaling_type=ScalingTypeMin):
843
+ """Rescales the vertex coordinates to scale using the given scaling_type.
844
+
845
+ Parameters
846
+ ----------
847
+ scale : float
848
+ The desired scaling factor of the selected dimension, if scaling_type
849
+ is ScalingTypeMin, ScalingTypeMed, ScalingTypeMax, or
850
+ ScalingTypeDiag. Otherwise, the overall scaling factor.
851
+
852
+ scaling_type : int
853
+ One of ScalingTypeMin, ScalingTypeMed, ScalingTypeMax,
854
+ ScalingTypeRelative, or ScalingTypeDiag.
855
+ ScalingTypeMin scales the smallest vertex extent (X, Y, or Z)
856
+ by scale, ScalingTypeMed scales the median vertex extent, and
857
+ ScalingTypeMax scales the maximum vertex extent. ScalingTypeDiag
858
+ scales the bounding box diagonal (divided by three), and
859
+ ScalingTypeRelative provides absolute scaling.
860
+ """
861
+ vertex_extent = self.principal_dims()
862
+
863
+ # Find minimal dimension
864
+ relative_scale = 1.0
865
+ if scaling_type == Mesh3D.ScalingTypeMin:
866
+ dim = np.where(vertex_extent == np.min(vertex_extent))[0][0]
867
+ relative_scale = vertex_extent[dim]
868
+ elif scaling_type == Mesh3D.ScalingTypeMed:
869
+ dim = np.where(vertex_extent == np.med(vertex_extent))[0][0]
870
+ relative_scale = vertex_extent[dim]
871
+ elif scaling_type == Mesh3D.ScalingTypeMax:
872
+ dim = np.where(vertex_extent == np.max(vertex_extent))[0][0]
873
+ relative_scale = vertex_extent[dim]
874
+ elif scaling_type == Mesh3D.ScalingTypeRelative:
875
+ relative_scale = 1.0
876
+ elif scaling_type == Mesh3D.ScalingTypeDiag:
877
+ diag = np.linalg.norm(vertex_extent)
878
+ relative_scale = diag / 3.0 # make the gripper size exactly one third of the diagonal
879
+
880
+ # Compute scale factor and rescale vertices
881
+ scale_factor = scale / relative_scale
882
+ self.vertices = scale_factor * self.vertices
883
+
884
+ def rescale(self, scale_factor):
885
+ """Rescales the vertex coordinates by scale_factor.
886
+
887
+ Parameters
888
+ ----------
889
+ scale_factor : float
890
+ The desired scale factor for the mesh's vertices.
891
+ """
892
+ self.vertices = scale_factor * self.vertices
893
+
894
+ def convex_hull(self):
895
+ """Return a 3D mesh that represents the convex hull of the mesh.
896
+ """
897
+ hull = ss.ConvexHull(self.vertices_)
898
+ hull_tris = hull.simplices
899
+ if self.normals_ is None:
900
+ cvh_mesh = Mesh3D(self.vertices_.copy(), hull_tris.copy(), center_of_mass=self.center_of_mass_)
901
+ else:
902
+ cvh_mesh = Mesh3D(self.vertices_.copy(), hull_tris.copy(), normals=self.normals_.copy(),
903
+ center_of_mass=self.center_of_mass_)
904
+ cvh_mesh.remove_unreferenced_vertices()
905
+ return cvh_mesh
906
+
907
+ def stable_poses(self, min_prob=0.0):
908
+ """Computes all valid StablePose objects for the mesh.
909
+
910
+ Parameters
911
+ ----------
912
+ min_prob : float
913
+ stable poses that are less likely than this threshold will be discarded
914
+
915
+ Returns
916
+ -------
917
+ :obj:`list` of :obj:`StablePose`
918
+ A list of StablePose objects for the mesh.
919
+ """
920
+ # compute face dag if necessary
921
+ if self.face_dag_ is None:
922
+ self._compute_face_dag()
923
+ cvh_mesh = self.face_dag_.mesh
924
+ cvh_verts = self.face_dag_.mesh.vertices
925
+
926
+ # propagate probabilities
927
+ cm = self.center_of_mass
928
+ prob_map = Mesh3D._compute_prob_map(list(self.face_dag_.nodes.values()), cvh_verts, cm)
929
+
930
+ # compute stable poses
931
+ stable_poses = []
932
+ for face, p in list(prob_map.items()):
933
+ x0 = cvh_verts[face[0]]
934
+ r = cvh_mesh._compute_basis([cvh_verts[i] for i in face])
935
+ if p > min_prob:
936
+ stable_poses.append(sp.StablePose(p, r, x0, face=face))
937
+
938
+ return stable_poses
939
+
940
+ def resting_pose(self, T_obj_world, eps=1e-10):
941
+ """ Returns the stable pose that the mesh will rest on if it lands
942
+ on an infinite planar worksurface quasi-statically in the given
943
+ transformation (only the rotation is used).
944
+
945
+ Parameters
946
+ ----------
947
+ T_obj_world : :obj:`autolab_core.RigidTransform`
948
+ transformation from object to table basis (z-axis upward) specifying the orientation of the mesh
949
+ eps : float
950
+ numeric tolerance in cone projection solver
951
+
952
+ Returns
953
+ -------
954
+ :obj:`StablePose`
955
+ stable pose specifying the face that the mesh will land on
956
+ """
957
+ # compute face dag if necessary
958
+ if self.face_dag_ is None:
959
+ self._compute_face_dag()
960
+
961
+ # adjust transform to place mesh in contact with table
962
+ T_obj_table = self.get_T_surface_obj(T_obj_world, delta=0.0)
963
+
964
+ # transform mesh
965
+ cvh_mesh = self.face_dag_.mesh
966
+ cvh_verts = cvh_mesh.vertices
967
+ mesh_tf = cvh_mesh.transform(T_obj_table)
968
+ vertices_tf = mesh_tf.vertices
969
+
970
+ # find the vertex with the minimum z value
971
+ min_z = np.min(vertices_tf[:, 2])
972
+ contact_ind = np.where(vertices_tf[:, 2] == min_z)[0]
973
+ if contact_ind.shape[0] == 0:
974
+ raise ValueError('Unable to find the vertex contacting the table!')
975
+ vertex_ind = contact_ind[0]
976
+
977
+ # project the center of mass onto the table plane
978
+ table_tri = np.array([[0, 0, 0],
979
+ [1, 0, 0],
980
+ [0, 1, 0]])
981
+ proj_cm = Mesh3D._proj_point_to_plane(table_tri, self.center_of_mass)
982
+ contact_vertex = vertices_tf[vertex_ind]
983
+ v_cm = proj_cm - contact_vertex
984
+ v_cm = v_cm[:2]
985
+
986
+ # compute which face the vertex will topple onto
987
+ # break loop when topple tri is found
988
+ topple_tri = None
989
+ neighboring_tris = self.face_dag_.vertex_to_tri[vertex_ind]
990
+ random.shuffle(neighboring_tris)
991
+ for neighboring_tri in neighboring_tris:
992
+ # find indices of other two vertices
993
+ ind = [0, 1, 2]
994
+ for i, v in enumerate(neighboring_tri):
995
+ if np.allclose(contact_vertex, vertices_tf[v]):
996
+ ind.remove(i)
997
+
998
+ # form edges in table plane
999
+ i1 = neighboring_tri[ind[0]]
1000
+ i2 = neighboring_tri[ind[1]]
1001
+ v1 = Mesh3D._proj_point_to_plane(table_tri, vertices_tf[i1])
1002
+ v2 = Mesh3D._proj_point_to_plane(table_tri, vertices_tf[i2])
1003
+ u1 = v1 - contact_vertex
1004
+ u2 = v2 - contact_vertex
1005
+ U = np.array([u1[:2], u2[:2]]).T
1006
+
1007
+ # solve linear subproblem to find cone coefficients
1008
+ try:
1009
+ alpha = np.linalg.solve(U + eps * np.eye(2), v_cm)
1010
+
1011
+ # exit loop with topple tri if found
1012
+ if np.all(alpha >= 0):
1013
+ tri_normal = cvh_mesh._compute_basis([cvh_verts[i] for i in neighboring_tri])[2, :]
1014
+ if tri_normal[2] < 0:
1015
+ tri_normal = -tri_normal
1016
+
1017
+ # check whether lower
1018
+ lower = True
1019
+ tri_center = np.mean([vertices_tf[i] for i in neighboring_tri], axis=0)
1020
+ if topple_tri is not None:
1021
+ topple_tri_center = np.mean([vertices_tf[i] for i in topple_tri], axis=0)
1022
+ lower = (tri_normal.dot(topple_tri_center - tri_center) > 0)
1023
+ if lower:
1024
+ topple_tri = neighboring_tri
1025
+
1026
+ except np.linalg.LinAlgError:
1027
+ logging.warning('Failed to solve linear system')
1028
+
1029
+ # check solution
1030
+ if topple_tri is None:
1031
+ raise ValueError('Failed to find a valid topple triangle')
1032
+
1033
+ # compute the face that the mesh will eventually rest on
1034
+ # by following the child nodes to a sink
1035
+ cur_node = self.face_dag_.nodes[tuple(topple_tri)]
1036
+ visited = []
1037
+ while not cur_node.is_sink:
1038
+ if cur_node in visited:
1039
+ raise ValueError('Found loop!')
1040
+ visited.append(cur_node)
1041
+ cur_node = cur_node.children[0]
1042
+
1043
+ # create stable pose
1044
+ resting_face = cur_node.face
1045
+ x0 = cvh_verts[vertex_ind]
1046
+ R = cvh_mesh._compute_basis([cvh_verts[i] for i in resting_face])
1047
+
1048
+ # align with axes with the original pose
1049
+ best_theta = 0
1050
+ best_dot = 0
1051
+ cur_theta = 0
1052
+ delta_theta = 0.01
1053
+ px = R[:, 0].copy()
1054
+ px[2] = 0
1055
+ py = R[:, 1].copy()
1056
+ py[2] = 0
1057
+ align_x = True
1058
+ if np.linalg.norm(py) > np.linalg.norm(px):
1059
+ align_x = False
1060
+ while cur_theta <= 2 * np.pi:
1061
+ Rz = RigidTransform.z_axis_rotation(cur_theta)
1062
+ Rp = Rz.dot(R)
1063
+ dot_prod = Rp[:, 0].dot(T_obj_world.x_axis)
1064
+ if not align_x:
1065
+ dot_prod = Rp[:, 1].dot(T_obj_world.y_axis)
1066
+ if dot_prod > best_dot:
1067
+ best_dot = dot_prod
1068
+ best_theta = cur_theta
1069
+ cur_theta += delta_theta
1070
+ R = RigidTransform.z_axis_rotation(best_theta).dot(R)
1071
+ return sp.StablePose(0.0, R, x0, face=resting_face)
1072
+
1073
+ def merge(self, other_mesh):
1074
+ """ Combines this mesh with another mesh.
1075
+
1076
+ Parameters
1077
+ ----------
1078
+ other_mesh : :obj:`Mesh3D`
1079
+ the mesh to combine with
1080
+
1081
+ Returns
1082
+ -------
1083
+ :obj:`Mesh3D`
1084
+ merged mesh
1085
+ """
1086
+ total_vertices = self.num_vertices + other_mesh.num_vertices
1087
+ total_triangles = self.num_triangles + other_mesh.num_triangles
1088
+ combined_vertices = np.zeros([total_vertices, 3])
1089
+ combined_triangles = np.zeros([total_triangles, 3])
1090
+
1091
+ combined_vertices[:self.num_vertices, :] = self.vertices
1092
+ combined_vertices[self.num_vertices:, :] = other_mesh.vertices
1093
+
1094
+ combined_triangles[:self.num_triangles, :] = self.triangles
1095
+ combined_triangles[self.num_triangles:, :] = other_mesh.triangles + self.num_vertices
1096
+
1097
+ combined_normals = None
1098
+ if self.normals is not None and other_mesh.normals is not None:
1099
+ combined_normals = np.zeros([total_vertices, 3])
1100
+ combined_normals[:self.num_vertices, :] = self.normals
1101
+ combined_normals[self.num_vertices:, :] = other_mesh.normals
1102
+ return Mesh3D(combined_vertices, combined_triangles.astype(np.int32), combined_normals)
1103
+
1104
+ def flip_tri_orientation(self):
1105
+ """ Flips the orientation of all triangles. """
1106
+ new_tris = self.triangles
1107
+ new_tris[:, 1] = self.triangles[:, 2]
1108
+ new_tris[:, 2] = self.triangles[:, 1]
1109
+ return Mesh3D(self.vertices, new_tris, self.normals,
1110
+ center_of_mass=self.center_of_mass)
1111
+
1112
+ def find_contact(self, origin, direction):
1113
+ """ Finds the contact location with the mesh, if it exists. """
1114
+ # create points
1115
+ origin_world = Point(origin, frame='world')
1116
+ direction_world = Direction(direction, frame='world')
1117
+
1118
+ # find contact using trimesh ray intersector
1119
+ origin_obj = self.T_obj_world.inverse() * origin_world
1120
+ direction_obj = self.T_obj_world.inverse() * direction_world
1121
+ locations, _, tri_indices = self.trimesh.ray.intersects_location([origin_obj.data], [direction_obj.data])
1122
+
1123
+ if len(locations) == 0:
1124
+ return None, None
1125
+
1126
+ # return closest point
1127
+ dists = np.linalg.norm(locations - origin_obj.data, axis=1)
1128
+ closest_ind = np.where(dists == np.min(dists))[0][0]
1129
+ point_obj = Point(locations[closest_ind, :], frame='obj')
1130
+ normal_obj = Direction(self.trimesh.face_normals[tri_indices[closest_ind], :], frame='obj')
1131
+ point_world = self.T_obj_world * point_obj
1132
+ normal_world = self.T_obj_world * normal_obj
1133
+
1134
+ return point_world.data, normal_world.data
1135
+
1136
+ def visualize(self, color=(0.5, 0.5, 0.5), style='surface', opacity=1.0):
1137
+ """Plots visualization of mesh using MayaVI.
1138
+
1139
+ Parameters
1140
+ ----------
1141
+ color : :obj:`tuple` of float
1142
+ 3-tuple of floats in [0,1] to give the mesh's color
1143
+
1144
+ style : :obj:`str`
1145
+ Either 'surface', which produces an opaque surface, or
1146
+ 'wireframe', which produces a wireframe.
1147
+
1148
+ opacity : float
1149
+ A value in [0,1] indicating the opacity of the mesh.
1150
+ Zero is transparent, one is opaque.
1151
+
1152
+ Returns
1153
+ -------
1154
+ :obj:`mayavi.modules.surface.Surface`
1155
+ The displayed surface.
1156
+ """
1157
+ surface = mv.triangular_mesh(self.vertices_[:, 0],
1158
+ self.vertices_[:, 1],
1159
+ self.vertices_[:, 2],
1160
+ self.triangles_, representation=style,
1161
+ color=color, opacity=opacity)
1162
+ return surface
1163
+
1164
+ @staticmethod
1165
+ def load(filename, cache_dir, preproc_script=None):
1166
+ """Load a mesh from a file.
1167
+
1168
+ Note
1169
+ ----
1170
+ If the mesh is not already in .obj format, this requires
1171
+ the installation of meshlab. Meshlab has a command called
1172
+ meshlabserver that is used to convert the file into a .obj format.
1173
+
1174
+ Parameters
1175
+ ----------
1176
+ filename : :obj:`str`
1177
+ Path to mesh file.
1178
+ cache_dir : :obj:`str`
1179
+ A directory to store a converted .obj file in, if
1180
+ the file isn't already in .obj format.
1181
+ preproc_script : :obj:`str`
1182
+ The path to an optional script to run before converting
1183
+ the mesh file to .obj if necessary.
1184
+
1185
+ Returns
1186
+ -------
1187
+ :obj:`Mesh3D`
1188
+ A 3D mesh object read from the file.
1189
+ """
1190
+ file_path, file_root = os.path.split(filename)
1191
+ file_root, file_ext = os.path.splitext(file_root)
1192
+ obj_filename = filename
1193
+
1194
+ if file_ext != Mesh3D.OBJ_EXT:
1195
+ obj_filename = os.path.join(cache_dir, file_root + Mesh3D.PROC_TAG + Mesh3D.OBJ_EXT)
1196
+ if preproc_script is None:
1197
+ meshlabserver_cmd = 'meshlabserver -i \"%s\" -o \"%s\"' % (filename, obj_filename)
1198
+ else:
1199
+ meshlabserver_cmd = 'meshlabserver -i \"%s\" -o \"%s\" -s \"%s\"' % (
1200
+ filename, obj_filename, preproc_script)
1201
+ os.system(meshlabserver_cmd)
1202
+
1203
+ if not os.path.exists(obj_filename):
1204
+ raise ValueError('Unable to open file %s. It may not exist or meshlab may not be installed.' % (filename))
1205
+
1206
+ # Read mesh from obj file
1207
+ return obj_file.ObjFile(obj_filename).read()
1208
+
1209
+ @property
1210
+ def trimesh(self):
1211
+ """ Convert to trimesh. """
1212
+ if self.trimesh_ is None:
1213
+ self.trimesh_ = tm.Trimesh(vertices=self.vertices,
1214
+ faces=self.triangles,
1215
+ vertex_normals=self.normals)
1216
+ return self.trimesh_
1217
+
1218
+ @property
1219
+ def is_watertight(self):
1220
+ return self.trimesh.is_watertight
1221
+
1222
+ @property
1223
+ def T_obj_world(self):
1224
+ """ Return pose. """
1225
+ return self.T_obj_world_
1226
+
1227
+ ##################################################################
1228
+ # Private Class Methods
1229
+ ##################################################################
1230
+
1231
+ def _compute_mass(self):
1232
+ """Computes the mesh mass.
1233
+
1234
+ Note
1235
+ ----
1236
+ Only works for watertight meshes.
1237
+
1238
+ Returns
1239
+ -------
1240
+ float
1241
+ The mass of the mesh.
1242
+ """
1243
+ return self.density_ * self.total_volume()
1244
+
1245
+ def _compute_inertia(self):
1246
+ """Computes the mesh inertia matrix.
1247
+
1248
+ Note
1249
+ ----
1250
+ Only works for watertight meshes.
1251
+
1252
+ Returns
1253
+ -------
1254
+ :obj:`numpy.ndarray` of float
1255
+ The 3x3 inertial matrix.
1256
+ """
1257
+ C = self.covariance()
1258
+ return self.density_ * (np.trace(C) * np.eye(3) - C)
1259
+
1260
+ def _compute_bb_center(self):
1261
+ """Computes the center point of the bounding box.
1262
+
1263
+ Returns
1264
+ -------
1265
+ :obj:`numpy.ndarray` of float
1266
+ 3-ndarray of floats that contains the coordinates
1267
+ of the center of the bounding box.
1268
+ """
1269
+
1270
+ bb_center = (self.min_coords() + self.max_coords()) / 2.0
1271
+ return bb_center
1272
+
1273
+ def _compute_com_uniform(self):
1274
+ """Computes the center of mass using a uniform mass distribution assumption.
1275
+
1276
+ Returns
1277
+ -------
1278
+ :obj:`numpy.ndarray` of float
1279
+ 3-ndarray of floats that contains the coordinates
1280
+ of the center of mass.
1281
+ """
1282
+ """
1283
+ total_volume = 0
1284
+ weighted_point_sum = np.zeros([1, 3])
1285
+ for tri in self.triangles_:
1286
+ volume = self._signed_volume_of_tri(tri)
1287
+ center = self._center_of_tri(tri)
1288
+ weighted_point_sum = weighted_point_sum + volume * center
1289
+ total_volume = total_volume + volume
1290
+ center_of_mass = weighted_point_sum / total_volume
1291
+ return center_of_mass[0]
1292
+ """
1293
+ return self.trimesh.center_mass
1294
+
1295
+ def _compute_centroid(self):
1296
+ """Computes the centroid (mean) of the mesh's vertices.
1297
+
1298
+ Returns
1299
+ -------
1300
+ :obj:`numpy.ndarray` of float
1301
+ 3-ndarray of floats that contains the coordinates
1302
+ of the centroid.
1303
+ """
1304
+ return np.mean(self.vertices_, axis=0)
1305
+
1306
+ def _signed_volume_of_tri(self, tri):
1307
+ """Return the signed volume of the given triangle.
1308
+
1309
+ Parameters
1310
+ ----------
1311
+ tri : :obj:`numpy.ndarray` of int
1312
+ The triangle for which we wish to compute a signed volume.
1313
+
1314
+ Returns
1315
+ -------
1316
+ float
1317
+ The signed volume associated with the triangle.
1318
+ """
1319
+ v1 = self.vertices_[tri[0], :]
1320
+ v2 = self.vertices_[tri[1], :]
1321
+ v3 = self.vertices_[tri[2], :]
1322
+
1323
+ volume = (1.0 / 6.0) * (v1.dot(np.cross(v2, v3)))
1324
+ return volume
1325
+
1326
+ def _center_of_tri(self, tri):
1327
+ """Return the center of the given triangle.
1328
+
1329
+ Parameters
1330
+ ----------
1331
+ tri : :obj:`numpy.ndarray` of int
1332
+ The triangle for which we wish to compute a signed volume.
1333
+
1334
+ Returns
1335
+ -------
1336
+ :obj:`numpy.ndarray` of float
1337
+ The 3D point at the center of the triangle
1338
+ """
1339
+ v1 = self.vertices_[tri[0], :]
1340
+ v2 = self.vertices_[tri[1], :]
1341
+ v3 = self.vertices_[tri[2], :]
1342
+ center = (1.0 / 3.0) * (v1 + v2 + v3)
1343
+ return center
1344
+
1345
+ def _covariance_of_tri(self, tri):
1346
+ """Return the covariance matrix of the given triangle.
1347
+
1348
+ Parameters
1349
+ ----------
1350
+ tri : :obj:`numpy.ndarray` of int
1351
+ The triangle for which we wish to compute a covariance.
1352
+
1353
+ Returns
1354
+ -------
1355
+ :obj:`numpy.ndarray` of float
1356
+ The 3x3 covariance matrix of the given triangle.
1357
+ """
1358
+ v1 = self.vertices_[tri[0], :]
1359
+ v2 = self.vertices_[tri[1], :]
1360
+ v3 = self.vertices_[tri[2], :]
1361
+
1362
+ A = np.zeros([3, 3])
1363
+ A[:, 0] = v1 - self.center_of_mass_
1364
+ A[:, 1] = v2 - self.center_of_mass_
1365
+ A[:, 2] = v3 - self.center_of_mass_
1366
+ C = np.linalg.det(A) * A.dot(Mesh3D.C_canonical).dot(A.T)
1367
+ return C
1368
+
1369
+ def _area_of_tri(self, tri):
1370
+ """Return the area of the given triangle.
1371
+
1372
+ Parameters
1373
+ ----------
1374
+ tri : :obj:`numpy.ndarray` of int
1375
+ The triangle for which we wish to compute an area.
1376
+
1377
+ Returns
1378
+ -------
1379
+ float
1380
+ The area of the triangle.
1381
+ """
1382
+ verts = [self.vertices[i] for i in tri]
1383
+ ab = verts[1] - verts[0]
1384
+ ac = verts[2] - verts[0]
1385
+ return 0.5 * np.linalg.norm(np.cross(ab, ac))
1386
+
1387
+ def _tri_area_percentages(self):
1388
+ """Return a list of the percent area each triangle contributes to the
1389
+ mesh's surface area.
1390
+
1391
+ Returns
1392
+ -------
1393
+ :obj:`list` of float
1394
+ A list of percentages in [0,1] for each face that represents its
1395
+ total contribution to the area of the mesh.
1396
+ """
1397
+ probs = []
1398
+ area = 0.0
1399
+ for tri in self.triangles:
1400
+ tri_area = self._area_of_tri(tri)
1401
+ probs.append(tri_area)
1402
+ area += tri_area
1403
+ probs = probs / area
1404
+ return probs
1405
+
1406
+ def _rand_point_on_tri(self, tri):
1407
+ """Return a random point on the given triangle.
1408
+
1409
+ Parameters
1410
+ ----------
1411
+ tri : :obj:`numpy.ndarray` of int
1412
+ The triangle for which we wish to compute an area.
1413
+
1414
+ Returns
1415
+ -------
1416
+ :obj:`numpy.ndarray` of float
1417
+ A 3D point on the triangle.
1418
+ """
1419
+ verts = [self.vertices[i] for i in tri]
1420
+ r1 = np.sqrt(np.random.uniform())
1421
+ r2 = np.random.uniform()
1422
+ p = (1 - r1) * verts[0] + r1 * (1 - r2) * verts[1] + r1 * r2 * verts[2]
1423
+ return p
1424
+
1425
+ def _compute_proj_area(self, verts):
1426
+ """Projects vertices onto the unit sphere from the center of mass
1427
+ and computes the projected area.
1428
+
1429
+ Parameters
1430
+ ----------
1431
+ verts : `list` of `numpy.ndarray` of float
1432
+ List of 3-ndarrays of floats that represent the vertices to be
1433
+ projected onto the unit sphere.
1434
+
1435
+ Returns
1436
+ -------
1437
+ float
1438
+ The total projected area on the unit sphere.
1439
+ """
1440
+ cm = self.center_of_mass
1441
+ angles = []
1442
+
1443
+ proj_verts = [(v - cm) / np.linalg.norm(v - cm) for v in verts]
1444
+
1445
+ a = math.acos(min(1, max(-1, np.dot(proj_verts[0], proj_verts[1]) /
1446
+ (np.linalg.norm(proj_verts[0]) * np.linalg.norm(proj_verts[1])))))
1447
+ b = math.acos(min(1, max(-1, np.dot(proj_verts[0], proj_verts[2]) /
1448
+ (np.linalg.norm(proj_verts[0]) * np.linalg.norm(proj_verts[2])))))
1449
+ c = math.acos(min(1, max(-1, np.dot(proj_verts[1], proj_verts[2]) /
1450
+ (np.linalg.norm(proj_verts[1]) * np.linalg.norm(proj_verts[2])))))
1451
+ s = (a + b + c) / 2
1452
+
1453
+ try:
1454
+ return 4 * math.atan(math.sqrt(math.tan(s / 2) * math.tan((s - a) / 2) *
1455
+ math.tan((s - b) / 2) * math.tan((s - c) / 2)))
1456
+ except:
1457
+ s = s + 0.001
1458
+ return 4 * math.atan(math.sqrt(math.tan(s / 2) * math.tan((s - a) / 2) *
1459
+ math.tan((s - b) / 2) * math.tan((s - c) / 2)))
1460
+
1461
+ def _compute_basis(self, face_verts):
1462
+ """Computes axes for a transformed basis relative to the plane in which input vertices lie.
1463
+
1464
+ Parameters
1465
+ ----------
1466
+ face_verts : :obj:`numpy.ndarray` of float
1467
+ A set of three 3D points that form a plane.
1468
+
1469
+ Returns:
1470
+ :obj:`numpy.ndarray` of float
1471
+ A 3-by-3 ndarray whose rows are the new basis. This matrix
1472
+ can be applied to the mesh to rotate the mesh to lie flat
1473
+ on the input face.
1474
+ """
1475
+ centroid = np.mean(face_verts, axis=0)
1476
+
1477
+ z_o = np.cross(face_verts[1] - face_verts[0], face_verts[2] - face_verts[0])
1478
+ z_o = z_o / np.linalg.norm(z_o)
1479
+
1480
+ # Ensure that all vertices are on the positive halfspace (aka above the table)
1481
+ dot_product = (self.vertices - centroid).dot(z_o)
1482
+ dot_product[np.abs(dot_product) < 1e-10] = 0.0
1483
+ if np.any(dot_product < 0):
1484
+ z_o = -z_o
1485
+
1486
+ x_o = np.array([-z_o[1], z_o[0], 0])
1487
+ if np.linalg.norm(x_o) == 0.0:
1488
+ x_o = np.array([1, 0, 0])
1489
+ else:
1490
+ x_o = x_o / np.linalg.norm(x_o)
1491
+ y_o = np.cross(z_o, x_o)
1492
+ y_o = y_o / np.linalg.norm(y_o)
1493
+
1494
+ R = np.array([np.transpose(x_o), np.transpose(y_o), np.transpose(z_o)])
1495
+
1496
+ # rotate the vertices and then align along the principal axes
1497
+ rotated_vertices = R.dot(self.vertices.T)
1498
+ xy_components = rotated_vertices[:2, :].T
1499
+
1500
+ pca = sklearn.decomposition.PCA(n_components=2)
1501
+ pca.fit(xy_components)
1502
+ comp_array = pca.components_
1503
+ x_o = R.T.dot(np.array([comp_array[0, 0], comp_array[0, 1], 0]))
1504
+ y_o = np.cross(z_o, x_o)
1505
+ return np.array([np.transpose(x_o), np.transpose(y_o), np.transpose(z_o)])
1506
+
1507
+ def _compute_face_dag(self):
1508
+ """ Computes a directed acyclic graph (DAG) specifying the
1509
+ toppling structure of the mesh faces by:
1510
+ 1) Computing the mesh convex hull
1511
+ 2) Creating maps from vertices and edges to the triangles that share them
1512
+ 3) Connecting each triangle in the convex hull to the face it will topple to, if landed on
1513
+ Modifies the class variable self.face_dag_.
1514
+ """
1515
+ # compute convex hull
1516
+ cm = self.center_of_mass
1517
+ cvh_mesh = self.convex_hull()
1518
+ cvh_tris = cvh_mesh.triangles
1519
+ cvh_verts = cvh_mesh.vertices
1520
+
1521
+ # create vertex and edge maps, and create nodes of graph
1522
+ nodes = {} # mapping from triangle tuples to GraphVertex objects
1523
+ vertex_to_tri = {} # mapping from vertex indidces to adjacent triangle lists
1524
+ edge_to_tri = {} # mapping from edge tuples to adjacent triangle lists
1525
+
1526
+ for tri in cvh_tris:
1527
+ # add vertex to tri mapping
1528
+ for v in tri:
1529
+ if v in vertex_to_tri:
1530
+ vertex_to_tri[v] += [tuple(tri)]
1531
+ else:
1532
+ vertex_to_tri[v] = [tuple(tri)]
1533
+
1534
+ # add edges to tri mapping
1535
+ tri_verts = [cvh_verts[i] for i in tri]
1536
+ s1 = Mesh3D._Segment(tri_verts[0], tri_verts[1])
1537
+ s2 = Mesh3D._Segment(tri_verts[0], tri_verts[2])
1538
+ s3 = Mesh3D._Segment(tri_verts[1], tri_verts[2])
1539
+ for seg in [s1, s2, s3]:
1540
+ k = seg.tup
1541
+ if k in edge_to_tri:
1542
+ edge_to_tri[k] += [tuple(tri)]
1543
+ else:
1544
+ edge_to_tri[k] = [tuple(tri)]
1545
+
1546
+ # add triangle to graph with prior probability estimate
1547
+ p = self._compute_proj_area(tri_verts) / (4 * math.pi)
1548
+ nodes[tuple(tri)] = Mesh3D._GraphVertex(p, tri)
1549
+
1550
+ # connect nodes in the graph based on geometric toppling criteria
1551
+ # a directed edge between two graph nodes implies that landing on one face will lead to toppling onto its successor
1552
+ # an outdegree of 0 for any graph node implies it is a sink (the object will come to rest if it topples to this face)
1553
+ for tri in cvh_tris:
1554
+ # vertices
1555
+ tri_verts = [cvh_verts[i] for i in tri]
1556
+
1557
+ # project the center of mass onto the triangle
1558
+ proj_cm = Mesh3D._proj_point_to_plane(tri_verts, cm)
1559
+
1560
+ # update list of top vertices, add edges between vertices as needed
1561
+ if not Mesh3D._point_in_tri(tri_verts, proj_cm):
1562
+ # form segment objects
1563
+ s1 = Mesh3D._Segment(tri_verts[0], tri_verts[1])
1564
+ s2 = Mesh3D._Segment(tri_verts[0], tri_verts[2])
1565
+ s3 = Mesh3D._Segment(tri_verts[1], tri_verts[2])
1566
+
1567
+ # compute the closest edges
1568
+ closest_edges = Mesh3D._closest_segment(proj_cm, [s1, s2, s3])
1569
+
1570
+ # choose the closest edge based on the midpoint of the triangle segments
1571
+ if len(closest_edges) == 1:
1572
+ closest_edge = closest_edges[0]
1573
+ else:
1574
+ closest_edge = Mesh3D._closer_segment(proj_cm, closest_edges[0], closest_edges[1])
1575
+
1576
+ # compute the topple face from the closest edge
1577
+ for face in edge_to_tri[closest_edge.tup]:
1578
+ if list(face) != list(tri):
1579
+ topple_face = face
1580
+ predecessor = nodes[tuple(tri)]
1581
+ successor = nodes[tuple(topple_face)]
1582
+ predecessor.add_edge(successor)
1583
+
1584
+ # save to class variable
1585
+ self.face_dag_ = Mesh3D._FaceDAG(cvh_mesh, nodes, vertex_to_tri, edge_to_tri)
1586
+
1587
+ class _Segment:
1588
+ """Object representation of a finite line segment in 3D space.
1589
+
1590
+ Attributes
1591
+ ----------
1592
+ p1 : :obj:`numpy.ndarray` of float
1593
+ The first endpoint of the line segment
1594
+ p2 : :obj:`numpy.ndarray` of float
1595
+ The second endpoint of the line segment
1596
+ tup : :obj:`tuple` of :obj:`tuple` of float
1597
+ A tuple representation of the segment, with the two
1598
+ endpoints arranged in lexicographical order.
1599
+ """
1600
+
1601
+ def __init__(self, p1, p2):
1602
+ """Creates a Segment with given endpoints.
1603
+
1604
+ Parameters
1605
+ ----------
1606
+ p1 : :obj:`numpy.ndarray` of float
1607
+ The first endpoint of the line segment
1608
+ p2 : :obj:`numpy.ndarray` of float
1609
+ The second endpoint of the line segment
1610
+ """
1611
+ self.p1 = p1
1612
+ self.p2 = p2
1613
+ self.tup = self._ordered_tuple()
1614
+
1615
+ def dist_to_point(self, point):
1616
+ """Computes the distance from the segment to the given 3D point.
1617
+
1618
+ Parameters
1619
+ ----------
1620
+ point : :obj:`numpy.ndarray` of float
1621
+ The 3D point to measure distance to.
1622
+
1623
+ Returns
1624
+ -------
1625
+ float
1626
+ The euclidean distance between the segment and the point.
1627
+ """
1628
+ p1, p2 = self.p1, self.p2
1629
+ ap = point - p1
1630
+ ab = p2 - p1
1631
+ proj_point = p1 + (np.dot(ap, ab) / np.dot(ab, ab)) * ab
1632
+ if self._contains_proj_point(proj_point):
1633
+ return np.linalg.norm(point - proj_point)
1634
+ else:
1635
+ return min(np.linalg.norm(point - p1),
1636
+ np.linalg.norm(point - p2))
1637
+
1638
+ def _contains_proj_point(self, point):
1639
+ """Is the given 3D point (assumed to be on the line that contains
1640
+ the segment) actually within the segment?
1641
+
1642
+ Parameters
1643
+ ----------
1644
+ point : :obj:`numpy.ndarray` of float
1645
+ The 3D point to check against.
1646
+
1647
+ Returns
1648
+ -------
1649
+ bool
1650
+ True if the point was within the segment or False otherwise.
1651
+ """
1652
+ p1, p2 = self.p1, self.p2
1653
+ return (point[0] >= min(p1[0], p2[0]) and point[0] <= max(p1[0], p2[0]) and
1654
+ point[1] >= min(p1[1], p2[1]) and point[1] <= max(p1[1], p2[1]) and
1655
+ point[2] >= min(p1[2], p2[2]) and point[2] <= max(p1[2], p2[2]))
1656
+
1657
+ def _ordered_tuple(self):
1658
+ """Returns an ordered tuple that represents the segment.
1659
+
1660
+ The points within are ordered lexicographically.
1661
+
1662
+ Returns
1663
+ -------
1664
+
1665
+ tup : :obj:`tuple` of :obj:`tuple` of float
1666
+ A tuple representation of the segment, with the two
1667
+ endpoints arranged in lexicographical order.
1668
+ """
1669
+ if (self.p1.tolist() > self.p2.tolist()):
1670
+ return (tuple(self.p1), tuple(self.p2))
1671
+ else:
1672
+ return (tuple(self.p2), tuple(self.p1))
1673
+
1674
+ class _FaceDAG:
1675
+ """ A directed acyclic graph specifying the topppling dependency structure
1676
+ for faces of a given mesh geometry with a specific center of mass.
1677
+ Useful for quasi-static stable pose analysis.
1678
+
1679
+ Attributes
1680
+ ----------
1681
+ mesh : :obj:`Mesh3D`
1682
+ the 3D triangular mesh that the DAG refers to (usually the convex hull)
1683
+ nodes : :obj:`dict` mapping 3-`tuple` of integers (triangles) to :obj:`Mesh3D._GraphVertex`
1684
+ the nodes in the DAG
1685
+ vertex_to_tri : :obj:`dict` mapping :obj:`int` (vertex indices) to 3-`tuple` of integers (triangles)
1686
+ edge_to_tri : :obj:`dict` mapping 2-`tuple` of integers (edges) to 3-`tuple` of integers (triangles)
1687
+ """
1688
+
1689
+ def __init__(self, mesh, nodes, vertex_to_tri, edge_to_tri):
1690
+ self.mesh = mesh
1691
+ self.nodes = nodes
1692
+ self.vertex_to_tri = vertex_to_tri
1693
+ self.edge_to_tri = edge_to_tri
1694
+
1695
+ class _GraphVertex:
1696
+ """A directed graph vertex that links a probability to a face.
1697
+ """
1698
+
1699
+ def __init__(self, probability, face):
1700
+ """Create a graph vertex with given probability and face.
1701
+
1702
+ Parameters
1703
+ ----------
1704
+ probability : float
1705
+ Probability associated with this vertex.
1706
+ face : :obj:`numpy.ndarray` of int
1707
+ A 3x3 array that represents the face
1708
+ associated with this vertex. Each row is a list
1709
+ of vertices in one face.
1710
+ """
1711
+ self.probability = probability
1712
+ self.children = []
1713
+ self.parents = []
1714
+ self.face = face
1715
+ self.has_parent = False
1716
+ self.num_parents = 0
1717
+ self.sink = None
1718
+
1719
+ @property
1720
+ def is_sink(self):
1721
+ return len(self.children) == 0
1722
+
1723
+ def add_edge(self, child):
1724
+ """Connects this vertex to the input child vertex.
1725
+
1726
+ Parameters
1727
+ ----------
1728
+ child : :obj:`_GraphVertex`
1729
+ The child to link to.
1730
+ """
1731
+ self.children.append(child)
1732
+ child.parents.append(self)
1733
+ child.has_parent = True
1734
+ child.num_parents += 1
1735
+
1736
+ @staticmethod
1737
+ def _max_edge_length(tri, vertices):
1738
+ """Compute the maximum edge length of a triangle.
1739
+
1740
+ Parameters
1741
+ ----------
1742
+ tri : :obj:`numpy.ndarray` of int
1743
+ The triangle of interest.
1744
+
1745
+ vertices : :obj:`numpy.ndarray` of `numpy.ndarray` of float
1746
+ The set of vertices which the face references.
1747
+
1748
+ Returns
1749
+ -------
1750
+ float
1751
+ The max edge length of the triangle.
1752
+ """
1753
+ v0 = np.array(vertices[tri[0]])
1754
+ v1 = np.array(vertices[tri[1]])
1755
+ v2 = np.array(vertices[tri[2]])
1756
+ max_edge_len = max(np.linalg.norm(v1 - v0),
1757
+ max(np.linalg.norm(v1 - v0),
1758
+ np.linalg.norm(v2 - v1)))
1759
+ return max_edge_len
1760
+
1761
+ @staticmethod
1762
+ def _proj_point_to_plane(tri_verts, point):
1763
+ """Project the given point onto the plane containing the three points in
1764
+ tri_verts.
1765
+
1766
+ Parameters
1767
+ ----------
1768
+ tri_verts : :obj:`numpy.ndarray` of float
1769
+ A list of three 3D points that defines a plane.
1770
+ point : :obj:`numpy.ndarray` of float
1771
+ The 3D point to project onto the plane.
1772
+ """
1773
+
1774
+ # Compute a normal vector to the triangle
1775
+ v0 = tri_verts[2] - tri_verts[0]
1776
+ v1 = tri_verts[1] - tri_verts[0]
1777
+ n = np.cross(v0, v1)
1778
+ n = n / np.linalg.norm(n)
1779
+
1780
+ # Compute distance from the point to the triangle's plane
1781
+ # by projecting a vector from the plane to the point onto
1782
+ # the normal vector
1783
+ dist = np.dot(n, point - tri_verts[0])
1784
+
1785
+ # Project the point back along the normal vector
1786
+ return (point - dist * n)
1787
+
1788
+ @staticmethod
1789
+ def _point_in_tri(tri_verts, point):
1790
+ """Is the given point contained in the given triangle?
1791
+
1792
+ Parameters
1793
+ ----------
1794
+ tri_verts : :obj:`list` of :obj:`numpy.ndarray` of float
1795
+ A list of three 3D points that definie a triangle.
1796
+
1797
+ point : :obj:`numpy.ndarray` of float
1798
+ A 3D point that should be coplanar with the triangle.
1799
+
1800
+ Returns
1801
+ -------
1802
+ bool
1803
+ True if the point is in the triangle, False otherwise.
1804
+ """
1805
+ # Implementation provided by http://blackpawn.com/texts/pointinpoly/
1806
+
1807
+ # Compute vectors
1808
+ v0 = tri_verts[2] - tri_verts[0]
1809
+ v1 = tri_verts[1] - tri_verts[0]
1810
+ v2 = point - tri_verts[0]
1811
+
1812
+ # Compute Dot Products
1813
+ dot00 = np.dot(v0, v0)
1814
+ dot01 = np.dot(v0, v1)
1815
+ dot02 = np.dot(v0, v2)
1816
+ dot11 = np.dot(v1, v1)
1817
+ dot12 = np.dot(v1, v2)
1818
+
1819
+ # Compute Barycentric Coords
1820
+ inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01)
1821
+ u = (dot11 * dot02 - dot01 * dot12) * inv_denom
1822
+ v = (dot00 * dot12 - dot01 * dot02) * inv_denom
1823
+
1824
+ # Check if point is in triangle
1825
+ return (u >= 0.0 and v >= 0.0 and u + v <= 1.0)
1826
+
1827
+ @staticmethod
1828
+ def _closest_segment(point, line_segments):
1829
+ """Returns the finite line segment(s) the least distance from the input point.
1830
+
1831
+ Parameters
1832
+ ----------
1833
+ point : :obj:`numpy.ndarray` of float
1834
+ The 3D point to measure distance to.
1835
+ line_segments: :obj:`list` of :obj:`_Segments`
1836
+ The list of line segments.
1837
+
1838
+ Returns
1839
+ -------
1840
+ :obj:`list` of :obj:`_Segments`
1841
+ The list of line segments that were closest to the input point.
1842
+ """
1843
+ min_dist = sys.maxsize
1844
+ min_segs = []
1845
+ distances = []
1846
+ segments = []
1847
+ common_endpoint = None
1848
+
1849
+ for segment in line_segments:
1850
+ dist = segment.dist_to_point(point)
1851
+ distances.append(dist)
1852
+ segments.append(segment)
1853
+ if dist < min_dist:
1854
+ min_dist = dist
1855
+
1856
+ for i in range(len(distances)):
1857
+ if min_dist + 0.000001 >= distances[i]:
1858
+ min_segs.append(segments[i])
1859
+
1860
+ return min_segs
1861
+
1862
+ @staticmethod
1863
+ def _closer_segment(point, s1, s2):
1864
+ """ Compute which segment is closer to a given point by seeing
1865
+ which side of the midline between the two segments the point falls on.
1866
+
1867
+ Parameters
1868
+ ----------
1869
+ point : :obj:`numpy.ndarray`
1870
+ 3d array containing point projected onto plane spanned by s1, s1
1871
+ s1 : :obj:`Mesh3D._Segment`
1872
+ first segment to check
1873
+ s2 : :obj:`Mesh3D._Segment`
1874
+ second segment to check
1875
+
1876
+ Returns
1877
+ -------
1878
+ :obj:`Mesh3D._Segment`
1879
+ best segment to check
1880
+ """
1881
+ # find the shared vertex and compute the midline between the segments
1882
+ if np.allclose(s1.p1, s2.p1):
1883
+ p = s1.p1
1884
+ l1 = s1.p2 - p
1885
+ l2 = s2.p2 - p
1886
+ elif np.allclose(s1.p2, s2.p1):
1887
+ p = s1.p2
1888
+ l1 = s1.p1 - p
1889
+ l2 = s2.p2 - p
1890
+ elif np.allclose(s1.p1, s2.p2):
1891
+ p = s1.p1
1892
+ l1 = s1.p2 - p
1893
+ l2 = s2.p1 - p
1894
+ else:
1895
+ p = s1.p2
1896
+ l1 = s1.p1 - p
1897
+ l2 = s2.p1 - p
1898
+ v = point - p
1899
+ midline = 0.5 * (l1 + l2)
1900
+
1901
+ # compute projection onto the midline
1902
+ if np.linalg.norm(midline) == 0:
1903
+ raise ValueError('Illegal triangle')
1904
+ alpha = midline.dot(v) / midline.dot(midline)
1905
+ w = alpha * midline
1906
+
1907
+ # compute residual (component of query point orthogonal to midline)
1908
+ x = v - w
1909
+
1910
+ # figure out which line is on the same side of the midline
1911
+ # as the residual
1912
+ d1 = x.dot(l1)
1913
+ d2 = x.dot(l2)
1914
+ closer_segment = s2
1915
+ if d1 > d2:
1916
+ closer_segment = s1
1917
+ return closer_segment
1918
+
1919
+ @staticmethod
1920
+ def _compute_prob_map(vertices, cvh_verts, cm):
1921
+ """Creates a map from faces to static stability probabilities.
1922
+
1923
+ Parameters
1924
+ ----------
1925
+ vertices : :obj:`list` of :obj:`_GraphVertex`
1926
+
1927
+ Returns
1928
+ -------
1929
+ :obj:`dictionary` of :obj:`tuple` of int to float
1930
+ Maps tuple representations of faces to probabilities.
1931
+ """
1932
+ # follow the child nodes of each vertex until a sink, then add in the resting probability
1933
+ prob_mapping = {}
1934
+ for vertex in vertices:
1935
+ c = vertex
1936
+ visited = []
1937
+ while not c.is_sink:
1938
+ if c in visited:
1939
+ break
1940
+ visited.append(c)
1941
+ c = c.children[0]
1942
+
1943
+ if tuple(c.face) not in list(prob_mapping.keys()):
1944
+ prob_mapping[tuple(c.face)] = 0.0
1945
+ prob_mapping[tuple(c.face)] += vertex.probability
1946
+ vertex.sink = c
1947
+
1948
+ # set resting probabilities of faces to zero
1949
+ for vertex in vertices:
1950
+ if not vertex.is_sink:
1951
+ prob_mapping[tuple(vertex.face)] = 0
1952
+
1953
+ return prob_mapping
1954
+
1955
+
1956
+ if __name__ == '__main__':
1957
+ pass
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/obj_file.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File for loading and saving meshes from .OBJ files
3
+ Author: Jeff Mahler
4
+ """
5
+ import os
6
+ try:
7
+ from . import mesh
8
+ except ImportError:
9
+ import mesh
10
+
11
+
12
+ class ObjFile(object):
13
+ """
14
+ A Wavefront .obj file reader and writer.
15
+
16
+ Attributes
17
+ ----------
18
+ filepath : :obj:`str`
19
+ The full path to the .obj file associated with this reader/writer.
20
+ """
21
+
22
+ def __init__(self, filepath):
23
+ """Construct and initialize a .obj file reader and writer.
24
+
25
+ Parameters
26
+ ----------
27
+ filepath : :obj:`str`
28
+ The full path to the desired .obj file
29
+
30
+ Raises
31
+ ------
32
+ ValueError
33
+ If the file extension is not .obj.
34
+ """
35
+ self.filepath_ = filepath
36
+ file_root, file_ext = os.path.splitext(self.filepath_)
37
+ if file_ext != '.obj':
38
+ raise ValueError('Extension %s invalid for OBJs' %(file_ext))
39
+
40
+ @property
41
+ def filepath(self):
42
+ """Returns the full path to the .obj file associated with this reader/writer.
43
+
44
+ Returns
45
+ -------
46
+ :obj:`str`
47
+ The full path to the .obj file associated with this reader/writer.
48
+ """
49
+ return self.filepath_
50
+
51
+ def read(self):
52
+ """Reads in the .obj file and returns a Mesh3D representation of that mesh.
53
+
54
+ Returns
55
+ -------
56
+ :obj:`Mesh3D`
57
+ A Mesh3D created from the data in the .obj file.
58
+ """
59
+ numVerts = 0
60
+ verts = []
61
+ norms = None
62
+ faces = []
63
+ tex_coords = []
64
+ face_norms = []
65
+ f = open(self.filepath_, 'r')
66
+
67
+ for line in f:
68
+ # Break up the line by whitespace
69
+ vals = line.split()
70
+ if len(vals) > 0:
71
+ # Look for obj tags (see http://en.wikipedia.org/wiki/Wavefront_.obj_file)
72
+ if vals[0] == 'v':
73
+ # Add vertex
74
+ v = list(map(float, vals[1:4]))
75
+ verts.append(v)
76
+ if vals[0] == 'vn':
77
+ # Add normal
78
+ if norms is None:
79
+ norms = []
80
+ n = list(map(float, vals[1:4]))
81
+ norms.append(n)
82
+ if vals[0] == 'f':
83
+ # Add faces (includes vertex indices, texture coordinates, and normals)
84
+ vi = []
85
+ vti = []
86
+ nti = []
87
+ if vals[1].find('/') == -1:
88
+ vi = list(map(int, vals[1:]))
89
+ vi = [i - 1 for i in vi]
90
+ else:
91
+ for j in range(1, len(vals)):
92
+ # Break up like by / to read vert inds, tex coords, and normal inds
93
+ val = vals[j]
94
+ tokens = val.split('/')
95
+ for i in range(len(tokens)):
96
+ if i == 0:
97
+ vi.append(int(tokens[i]) - 1) # adjust for python 0 - indexing
98
+ elif i == 1:
99
+ if tokens[i] != '':
100
+ vti.append(int(tokens[i]))
101
+ elif i == 2:
102
+ nti.append(int(tokens[i]))
103
+ faces.append(vi)
104
+ # Below two lists are currently not in use
105
+ tex_coords.append(vti)
106
+ face_norms.append(nti)
107
+ f.close()
108
+
109
+ return mesh.Mesh3D(verts, faces, norms)
110
+
111
+ def write(self, mesh):
112
+ """Writes a Mesh3D object out to a .obj file format
113
+
114
+ Parameters
115
+ ----------
116
+ mesh : :obj:`Mesh3D`
117
+ The Mesh3D object to write to the .obj file.
118
+
119
+ Note
120
+ ----
121
+ Does not support material files or texture coordinates.
122
+ """
123
+ f = open(self.filepath_, 'w')
124
+ vertices = mesh.vertices
125
+ faces = mesh.triangles
126
+ normals = mesh.normals
127
+
128
+ # write human-readable header
129
+ f.write('###########################################################\n')
130
+ f.write('# OBJ file generated by UC Berkeley Automation Sciences Lab\n')
131
+ f.write('#\n')
132
+ f.write('# Num Vertices: %d\n' %(vertices.shape[0]))
133
+ f.write('# Num Triangles: %d\n' %(faces.shape[0]))
134
+ f.write('#\n')
135
+ f.write('###########################################################\n')
136
+ f.write('\n')
137
+
138
+ for v in vertices:
139
+ f.write('v %f %f %f\n' %(v[0], v[1], v[2]))
140
+
141
+ # write the normals list
142
+ if normals is not None and normals.shape[0] > 0:
143
+ for n in normals:
144
+ f.write('vn %f %f %f\n' %(n[0], n[1], n[2]))
145
+
146
+ # write the normals list
147
+ for t in faces:
148
+ f.write('f %d %d %d\n' %(t[0]+1, t[1]+1, t[2]+1)) # convert back to 1-indexing
149
+
150
+ f.close()
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/sdf.py ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Definition of SDF Class
3
+ Author: Sahaana Suri, Jeff Mahler, and Matt Matl
4
+
5
+ **Currently assumes clean input**
6
+ """
7
+ from abc import ABCMeta, abstractmethod
8
+ import logging
9
+ import numpy as np
10
+ from numbers import Number
11
+
12
+ import time
13
+
14
+ from autolab_core import RigidTransform, SimilarityTransform, PointCloud, Point, NormalCloud
15
+
16
+
17
+ from sys import version_info
18
+ if version_info[0] != 3:
19
+ range = xrange
20
+
21
+
22
+ # class Sdf(metaclass=ABCMeta): # work for python3
23
+ class Sdf():
24
+ """ Abstract class for signed distance fields.
25
+ """
26
+ __metaclass__ = ABCMeta
27
+ ##################################################################
28
+ # General SDF Properties
29
+ ##################################################################
30
+ @property
31
+ def dimensions(self):
32
+ """SDF dimension information.
33
+
34
+ Returns
35
+ -------
36
+ :obj:`numpy.ndarray` of int
37
+ The ndarray that contains the dimensions of the sdf.
38
+ """
39
+ return self.dims_
40
+
41
+ @property
42
+ def origin(self):
43
+ """The location of the origin in the SDF grid.
44
+
45
+ Returns
46
+ -------
47
+ :obj:`numpy.ndarray` of float
48
+ The 2- or 3-ndarray that contains the location of
49
+ the origin of the mesh grid in real space.
50
+ """
51
+ return self.origin_
52
+
53
+ @property
54
+ def resolution(self):
55
+ """The grid resolution (how wide each grid cell is).
56
+
57
+ Returns
58
+ -------
59
+ float
60
+ The width of each grid cell.
61
+ """
62
+ return self.resolution_
63
+
64
+ @property
65
+ def center(self):
66
+ """Center of grid.
67
+
68
+ This basically transforms the world frame to grid center.
69
+
70
+ Returns
71
+ -------
72
+ :obj:`numpy.ndarray`
73
+ """
74
+ return self.center_
75
+
76
+ @property
77
+ def gradients(self):
78
+ """Gradients of the SDF.
79
+
80
+ Returns
81
+ -------
82
+ :obj:`list` of :obj:`numpy.ndarray` of float
83
+ A list of ndarrays of the same dimension as the SDF. The arrays
84
+ are in axis order and specify the gradients for that axis
85
+ at each point.
86
+ """
87
+ return self.gradients_
88
+
89
+ @property
90
+ def data(self):
91
+ """The SDF data.
92
+
93
+ Returns
94
+ -------
95
+ :obj:`numpy.ndarray` of float
96
+ The 2- or 3-dimensional ndarray that holds the grid of signed
97
+ distances.
98
+ """
99
+ return self.data_
100
+
101
+ ##################################################################
102
+ # General SDF Abstract Methods
103
+ ##################################################################
104
+ @abstractmethod
105
+ def transform(self, tf):
106
+ """Returns a new SDF transformed by similarity tf.
107
+ """
108
+ pass
109
+
110
+ @abstractmethod
111
+ def transform_pt_obj_to_grid(self, x_world, direction=False):
112
+ """Transforms points from world frame to grid frame
113
+ """
114
+ pass
115
+
116
+ @abstractmethod
117
+ def transform_pt_grid_to_obj(self, x_grid, direction=False):
118
+ """Transforms points from grid frame to world frame
119
+ """
120
+ pass
121
+
122
+ @abstractmethod
123
+ def surface_points(self):
124
+ """Returns the points on the surface.
125
+
126
+ Returns
127
+ -------
128
+ :obj:`tuple` of :obj:`numpy.ndarray` of int, :obj:`numpy.ndarray` of float
129
+ The points on the surface and the signed distances at those points.
130
+ """
131
+ pass
132
+
133
+ @abstractmethod
134
+ def __getitem__(self, coords):
135
+ """Returns the signed distance at the given coordinates.
136
+
137
+ Parameters
138
+ ----------
139
+ coords : :obj:`numpy.ndarray` of int
140
+ A 2- or 3-dimensional ndarray that indicates the desired
141
+ coordinates in the grid.
142
+
143
+ Returns
144
+ -------
145
+ float
146
+ The signed distance at the given coords (interpolated).
147
+ """
148
+ pass
149
+
150
+ ##################################################################
151
+ # Universal SDF Methods
152
+ ##################################################################
153
+ def transform_to_world(self):
154
+ """Returns an sdf object with center in the world frame of reference.
155
+ """
156
+ return self.transform(self.pose_, scale=self.scale_)
157
+
158
+ def center_world(self):
159
+ """Center of grid (basically transforms world frame to grid center)
160
+ """
161
+ return self.transform_pt_grid_to_obj(self.center_)
162
+
163
+ def on_surface(self, coords):
164
+ """Determines whether or not a point is on the object surface.
165
+
166
+ Parameters
167
+ ----------
168
+ coords : :obj:`numpy.ndarray` of int
169
+ A 2- or 3-dimensional ndarray that indicates the desired
170
+ coordinates in the grid.
171
+
172
+ Returns
173
+ -------
174
+ :obj:`tuple` of bool, float
175
+ Is the point on the object's surface, and what
176
+ is the signed distance at that point?
177
+ """
178
+ sdf_val = self[coords]
179
+ if np.abs(sdf_val) < self.surface_thresh_:
180
+ return True, sdf_val
181
+ return False, sdf_val
182
+
183
+ def is_out_of_bounds(self, coords):
184
+ """Returns True if coords is an out of bounds access.
185
+
186
+ Parameters
187
+ ----------
188
+ coords : :obj:`numpy.ndarray` of int
189
+ A 2- or 3-dimensional ndarray that indicates the desired
190
+ coordinates in the grid.
191
+
192
+ Returns
193
+ -------
194
+ bool
195
+ Are the coordinates in coords out of bounds?
196
+ """
197
+ return np.array(coords < 0).any() or np.array(coords >= self.dims_).any()
198
+
199
+ def _compute_gradients(self):
200
+ """Computes the gradients of the SDF.
201
+
202
+ Returns
203
+ -------
204
+ :obj:`list` of :obj:`numpy.ndarray` of float
205
+ A list of ndarrays of the same dimension as the SDF. The arrays
206
+ are in axis order and specify the gradients for that axis
207
+ at each point.
208
+ """
209
+ self.gradients_ = np.gradient(self.data_)
210
+
211
+
212
+ class Sdf3D(Sdf):
213
+ # static indexing vars
214
+ num_interpolants = 8
215
+ min_coords_x = [0, 2, 3, 5]
216
+ max_coords_x = [1, 4, 6, 7]
217
+ min_coords_y = [0, 1, 3, 6]
218
+ max_coords_y = [2, 4, 5, 7]
219
+ min_coords_z = [0, 1, 2, 4]
220
+ max_coords_z = [3, 5, 6, 7]
221
+
222
+ def __init__(self, sdf_data, origin, resolution, use_abs=False,
223
+ T_sdf_world=RigidTransform(from_frame='sdf', to_frame='world')):
224
+ self.data_ = sdf_data
225
+ self.origin_ = origin
226
+ self.resolution_ = resolution
227
+ self.dims_ = self.data_.shape
228
+
229
+ # set up surface params
230
+ self.surface_thresh_ = self.resolution_ * np.sqrt(2) / 2
231
+ self.surface_points_ = None
232
+ self.surface_points_w_ = None
233
+ self.surface_vals_ = None
234
+ self._compute_surface_points()
235
+
236
+ # resolution is max dist from surface when surf is orthogonal to diagonal grid cells
237
+ spts, _ = self.surface_points()
238
+ self.center_ = 0.5 * (np.min(spts, axis=0) + np.max(spts, axis=0))
239
+ self.points_buf_ = np.zeros([Sdf3D.num_interpolants, 3], dtype=np.int)
240
+ self.coords_buf_ = np.zeros([3, ])
241
+ self.pts_ = None
242
+
243
+ # tranform sdf basis to grid (X and Z axes are flipped!)
244
+ t_world_grid = self.resolution_ * self.center_
245
+ s_world_grid = 1.0 / self.resolution_
246
+
247
+ # FIXME: Since in autolab_core==0.0.4, it applies (un)scale transformation before translation in SimilarityTransform
248
+ # here we shoule use unscaled origin to get the correct world coordinates
249
+ # PS: in world coordinate, the origin here is the left-bottom-down corner of the padded bounding squre box
250
+ t_grid_sdf = self.origin
251
+ self.T_grid_sdf_ = SimilarityTransform(translation=t_grid_sdf,
252
+ scale=self.resolution,
253
+ from_frame='grid',
254
+ to_frame='sdf')
255
+ self.T_sdf_world_ = T_sdf_world
256
+ self.T_grid_world_ = self.T_sdf_world_ * self.T_grid_sdf_
257
+
258
+ self.T_sdf_grid_ = self.T_grid_sdf_.inverse()
259
+ self.T_world_grid_ = self.T_grid_world_.inverse()
260
+ self.T_world_sdf_ = self.T_sdf_world_.inverse()
261
+
262
+ # optionally use only the absolute values (useful for non-closed meshes in 3D)
263
+ self.use_abs_ = use_abs
264
+ if use_abs:
265
+ self.data_ = np.abs(self.data_)
266
+
267
+ self._compute_gradients()
268
+ self.surface_points_w_ = self.transform_pt_grid_to_obj(self.surface_points_.T).T
269
+ surface, _ = self.surface_points(grid_basis=True)
270
+ self.surface_for_signed_val = surface[np.random.choice(len(surface), 1000)] # FIXME: for speed
271
+
272
+ def transform(self, delta_T):
273
+ """ Creates a new SDF with a given pose with respect to world coordinates.
274
+
275
+ Parameters
276
+ ----------
277
+ delta_T : :obj:`autolab_core.RigidTransform`
278
+ transform from cur sdf to transformed sdf coords
279
+ """
280
+ new_T_sdf_world = self.T_sdf_world_ * delta_T.inverse().as_frames('sdf', 'sdf')
281
+ return Sdf3D(self.data_, self.origin_, self.resolution_, use_abs=self.use_abs_,
282
+ T_sdf_world=new_T_sdf_world)
283
+
284
+ def _signed_distance(self, coords):
285
+ """Returns the signed distance at the given coordinates, interpolating
286
+ if necessary.
287
+
288
+ Parameters
289
+ ----------
290
+ coords : :obj:`numpy.ndarray` of int
291
+ A 3-dimensional ndarray that indicates the desired
292
+ coordinates in the grid.
293
+
294
+ Returns
295
+ -------
296
+ float
297
+ The signed distance at the given coords (interpolated).
298
+
299
+ Raises
300
+ ------
301
+ IndexError
302
+ If the coords vector does not have three entries.
303
+ """
304
+ if len(coords) != 3:
305
+ raise IndexError('Indexing must be 3 dimensional')
306
+ if self.is_out_of_bounds(coords):
307
+ logging.debug('Out of bounds access. Snapping to SDF dims')
308
+ # find cloest surface point
309
+ surface = self.surface_for_signed_val
310
+ closest_surface_coord = surface[np.argmin(np.linalg.norm(surface - coords, axis=-1))]
311
+ sd = np.linalg.norm(self.transform_pt_grid_to_obj(closest_surface_coord) -
312
+ self.transform_pt_grid_to_obj(coords)) + \
313
+ self.data_[closest_surface_coord[0], closest_surface_coord[1], closest_surface_coord[2]]
314
+ else:
315
+ # snap to grid dims
316
+ self.coords_buf_[0] = max(0, min(coords[0], self.dims_[0] - 1))
317
+ self.coords_buf_[1] = max(0, min(coords[1], self.dims_[1] - 1))
318
+ self.coords_buf_[2] = max(0, min(coords[2], self.dims_[2] - 1))
319
+ # regular indexing if integers
320
+ if np.issubdtype(type(coords[0]), np.integer) and \
321
+ np.issubdtype(type(coords[1]), np.integer) and \
322
+ np.issubdtype(type(coords[2]), np.integer):
323
+ return self.data_[int(self.coords_buf_[0]), int(self.coords_buf_[1]), int(self.coords_buf_[2])]
324
+
325
+ # otherwise interpolate
326
+ min_coords = np.floor(self.coords_buf_)
327
+ max_coords = min_coords + 1 # assumed to be on grid
328
+ self.points_buf_[Sdf3D.min_coords_x, 0] = min_coords[0]
329
+ self.points_buf_[Sdf3D.max_coords_x, 0] = max_coords[0]
330
+ self.points_buf_[Sdf3D.min_coords_y, 1] = min_coords[1]
331
+ self.points_buf_[Sdf3D.max_coords_y, 1] = max_coords[1]
332
+ self.points_buf_[Sdf3D.min_coords_z, 2] = min_coords[2]
333
+ self.points_buf_[Sdf3D.max_coords_z, 2] = max_coords[2]
334
+
335
+ # bilinearly interpolate points
336
+ sd = 0.0
337
+ for i in range(Sdf3D.num_interpolants):
338
+ p = self.points_buf_[i, :]
339
+ if self.is_out_of_bounds(p):
340
+ v = 0.0
341
+ else:
342
+ v = self.data_[p[0], p[1], p[2]]
343
+ w = np.prod(-np.abs(p - self.coords_buf_) + 1)
344
+ sd = sd + w * v
345
+
346
+ return sd
347
+
348
+ def __getitem__(self, coords):
349
+ """Returns the signed distance at the given coordinates.
350
+
351
+ Parameters
352
+ ----------
353
+ coords : :obj:`numpy.ndarray` of int
354
+ A or 3-dimensional ndarray that indicates the desired
355
+ coordinates in the grid.
356
+
357
+ Returns
358
+ -------
359
+ float
360
+ The signed distance at the given coords (interpolated).
361
+
362
+ Raises
363
+ ------
364
+ IndexError
365
+ If the coords vector does not have three entries.
366
+ """
367
+ return self._signed_distance(coords)
368
+
369
+ def gradient(self, coords):
370
+ """Returns the SDF gradient at the given coordinates, interpolating if necessary
371
+
372
+ Parameters
373
+ ----------
374
+ coords : :obj:`numpy.ndarray` of int
375
+ A 3-dimensional ndarray that indicates the desired
376
+ coordinates in the grid.
377
+
378
+ Returns
379
+ -------
380
+ float
381
+ The gradient at the given coords (interpolated).
382
+
383
+ Raises
384
+ ------
385
+ IndexError
386
+ If the coords vector does not have three entries.
387
+ """
388
+ if len(coords) != 3:
389
+ raise IndexError('Indexing must be 3 dimensional')
390
+
391
+ # log warning if out of bounds access
392
+ if self.is_out_of_bounds(coords):
393
+ logging.debug('Out of bounds access. Snapping to SDF dims')
394
+
395
+ # snap to grid dims
396
+ self.coords_buf_[0] = max(0, min(coords[0], self.dims_[0] - 1))
397
+ self.coords_buf_[1] = max(0, min(coords[1], self.dims_[1] - 1))
398
+ self.coords_buf_[2] = max(0, min(coords[2], self.dims_[2] - 1))
399
+
400
+ # regular indexing if integers
401
+ if type(coords[0]) is int and type(coords[1]) is int and type(coords[2]) is int:
402
+ self.coords_buf_ = self.coords_buf_.astype(np.int)
403
+ return self.data_[self.coords_buf_[0], self.coords_buf_[1], self.coords_buf_[2]]
404
+
405
+ # otherwise interpolate
406
+ min_coords = np.floor(self.coords_buf_)
407
+ max_coords = min_coords + 1
408
+ self.points_buf_[Sdf3D.min_coords_x, 0] = min_coords[0]
409
+ self.points_buf_[Sdf3D.max_coords_x, 0] = min_coords[0]
410
+ self.points_buf_[Sdf3D.min_coords_y, 1] = min_coords[1]
411
+ self.points_buf_[Sdf3D.max_coords_y, 1] = max_coords[1]
412
+ self.points_buf_[Sdf3D.min_coords_z, 2] = min_coords[2]
413
+ self.points_buf_[Sdf3D.max_coords_z, 2] = max_coords[2]
414
+
415
+ # bilinear interpolation
416
+ g = np.zeros(3)
417
+ gp = np.zeros(3)
418
+ w_sum = 0.0
419
+ for i in range(Sdf3D.num_interpolants):
420
+ p = self.points_buf_[i, :]
421
+ if self.is_out_of_bounds(p):
422
+ gp[0] = 0.0
423
+ gp[1] = 0.0
424
+ gp[2] = 0.0
425
+ else:
426
+ gp[0] = self.gradients_[0][p[0], p[1], p[2]]
427
+ gp[1] = self.gradients_[1][p[0], p[1], p[2]]
428
+ gp[2] = self.gradients_[2][p[0], p[1], p[2]]
429
+
430
+ w = np.prod(-np.abs(p - self.coords_buf_) + 1)
431
+ g = g + w * gp
432
+
433
+ return g
434
+
435
+ def curvature(self, coords, delta=0.001):
436
+ """
437
+ Returns an approximation to the local SDF curvature (Hessian) at the
438
+ given coordinate in grid basis.
439
+
440
+ Parameters
441
+ ---------
442
+ coords : numpy 3-vector
443
+ the grid coordinates at which to get the curvature
444
+ delta :
445
+ Returns
446
+ -------
447
+ curvature : 3x3 ndarray of the curvature at the surface points
448
+ """
449
+ # perturb local coords
450
+ coords_x_up = coords + np.array([delta, 0, 0])
451
+ coords_x_down = coords + np.array([-delta, 0, 0])
452
+ coords_y_up = coords + np.array([0, delta, 0])
453
+ coords_y_down = coords + np.array([0, -delta, 0])
454
+ coords_z_up = coords + np.array([0, 0, delta])
455
+ coords_z_down = coords + np.array([0, 0, -delta])
456
+
457
+ # get gradient
458
+ grad_x_up = self.gradient(coords_x_up)
459
+ grad_x_down = self.gradient(coords_x_down)
460
+ grad_y_up = self.gradient(coords_y_up)
461
+ grad_y_down = self.gradient(coords_y_down)
462
+ grad_z_up = self.gradient(coords_z_up)
463
+ grad_z_down = self.gradient(coords_z_down)
464
+
465
+ # finite differences
466
+ curvature_x = (grad_x_up - grad_x_down) / (4 * delta)
467
+ curvature_y = (grad_y_up - grad_y_down) / (4 * delta)
468
+ curvature_z = (grad_z_up - grad_z_down) / (4 * delta)
469
+ curvature = np.c_[curvature_x, np.c_[curvature_y, curvature_z]]
470
+ curvature = curvature + curvature.T
471
+ return curvature
472
+
473
+ def surface_normal(self, coords, delta=1.5):
474
+ """Returns the sdf surface normal at the given coordinates by
475
+ computing the tangent plane using SDF interpolation.
476
+
477
+ Parameters
478
+ ----------
479
+ coords : :obj:`numpy.ndarray` of int
480
+ A 3-dimensional ndarray that indicates the desired
481
+ coordinates in the grid.
482
+
483
+ delta : float
484
+ A radius for collecting surface points near the target coords
485
+ for calculating the surface normal.
486
+
487
+ Returns
488
+ -------
489
+ :obj:`numpy.ndarray` of float
490
+ The 3-dimensional ndarray that represents the surface normal.
491
+
492
+ Raises
493
+ ------
494
+ IndexError
495
+ If the coords vector does not have three entries.
496
+ """
497
+ if len(coords) != 3:
498
+ raise IndexError('Indexing must be 3 dimensional')
499
+
500
+ # log warning if out of bounds access
501
+ if self.is_out_of_bounds(coords):
502
+ logging.debug('Out of bounds access. Snapping to SDF dims')
503
+
504
+ # snap to grid dims
505
+ # coords[0] = max(0, min(coords[0], self.dims_[0] - 1))
506
+ # coords[1] = max(0, min(coords[1], self.dims_[1] - 1))
507
+ # coords[2] = max(0, min(coords[2], self.dims_[2] - 1))
508
+ index_coords = np.zeros(3)
509
+
510
+ # check points on surface
511
+ sdf_val = self[coords]
512
+ if np.abs(sdf_val) >= self.surface_thresh_:
513
+ logging.debug('Cannot compute normal. Point must be on surface')
514
+ return None
515
+
516
+ # collect all surface points within the delta sphere
517
+ X = []
518
+ d = np.zeros(3)
519
+ dx = -delta
520
+ while dx <= delta:
521
+ dy = -delta
522
+ while dy <= delta:
523
+ dz = -delta
524
+ while dz <= delta:
525
+ d = np.array([dx, dy, dz])
526
+ if dx != 0 or dy != 0 or dz != 0:
527
+ d = delta * d / np.linalg.norm(d)
528
+ index_coords[0] = coords[0] + d[0]
529
+ index_coords[1] = coords[1] + d[1]
530
+ index_coords[2] = coords[2] + d[2]
531
+ sdf_val = self[index_coords]
532
+ if np.abs(sdf_val) < self.surface_thresh_:
533
+ X.append([index_coords[0], index_coords[1], index_coords[2], sdf_val])
534
+ dz += delta
535
+ dy += delta
536
+ dx += delta
537
+
538
+ # fit a plane to the surface points
539
+ X.sort(key=lambda x: x[3])
540
+ X = np.array(X)[:, :3]
541
+ A = X - np.mean(X, axis=0)
542
+ try:
543
+ U, S, V = np.linalg.svd(A.T)
544
+ n = U[:, 2]
545
+ except:
546
+ logging.warning('Tangent plane does not exist. Returning None.')
547
+ return None
548
+ # make sure surface normal is outward
549
+ # referenced from Zhou Xian's github, but if the model is not watertight, this method may fail
550
+ # https://github.com/zhouxian/meshpy_berkeley/commit/96428f3b7af618a0828a7eb88f22541cdafacfc7
551
+ if self[coords + n * 0.01] < self[coords]:
552
+ n = -n
553
+ return n
554
+
555
+ def _compute_surface_points(self):
556
+ surface_points = np.where(np.abs(self.data_) < self.surface_thresh_)
557
+ x = surface_points[0]
558
+ y = surface_points[1]
559
+ z = surface_points[2]
560
+ self.surface_points_ = np.c_[x, np.c_[y, z]]
561
+ self.surface_vals_ = self.data_[self.surface_points_[:, 0], self.surface_points_[:, 1],
562
+ self.surface_points_[:, 2]]
563
+
564
+ def surface_points(self, grid_basis=True):
565
+ """Returns the points on the surface.
566
+
567
+ Parameters
568
+ ----------
569
+ grid_basis : bool
570
+ If False, the surface points are transformed to the world frame.
571
+ If True (default), the surface points are left in grid coordinates.
572
+
573
+ Returns
574
+ -------
575
+ :obj:`tuple` of :obj:`numpy.ndarray` of int, :obj:`numpy.ndarray` of float
576
+ The points on the surface and the signed distances at those points.
577
+ """
578
+ if not grid_basis:
579
+ return self.surface_points_w_, self.surface_vals_
580
+ return self.surface_points_, self.surface_vals_
581
+
582
+ def rescale(self, scale):
583
+ """ Rescale an SDF by a given scale factor.
584
+
585
+ Parameters
586
+ ----------
587
+ scale : float
588
+ the amount to scale the SDF
589
+
590
+ Returns
591
+ -------
592
+ :obj:`Sdf3D`
593
+ new sdf with given scale
594
+ """
595
+ resolution_tf = scale * self.resolution_
596
+ return Sdf3D(self.data_, self.origin_, resolution_tf, use_abs=self.use_abs_,
597
+ T_sdf_world=self.T_sdf_world_)
598
+
599
+ def transform_dense(self, delta_T, detailed=False):
600
+ """ Transform the grid by pose T and scale with canonical reference
601
+ frame at the SDF center with axis alignment.
602
+
603
+ Parameters
604
+ ----------
605
+ delta_T : SimilarityTransform
606
+ the transformation from the current frame of reference to the new frame of reference
607
+ detailed : bool
608
+ whether or not to use interpolation
609
+
610
+ Returns
611
+ -------
612
+ :obj:`Sdf3D`
613
+ new sdf with grid warped by T
614
+ """
615
+ # map all surface points to their new location
616
+ start_t = time.clock()
617
+
618
+ # form points array
619
+ if self.pts_ is None:
620
+ [x_ind, y_ind, z_ind] = np.indices(self.dims_)
621
+ self.pts_ = np.c_[x_ind.flatten().T, np.c_[y_ind.flatten().T, z_ind.flatten().T]].astype(np.float32)
622
+
623
+ # transform points
624
+ num_pts = self.pts_.shape[0]
625
+ pts_sdf = self.T_grid_sdf_ * PointCloud(self.pts_.T, frame='grid')
626
+ pts_sdf_tf = delta_T.as_frames('sdf', 'sdf') * pts_sdf
627
+ pts_grid_tf = self.T_sdf_grid_ * pts_sdf_tf
628
+ pts_tf = pts_grid_tf.data.T
629
+ all_points_t = time.clock()
630
+
631
+ # transform the center
632
+ origin_sdf = self.T_grid_sdf_ * Point(self.origin_, frame='grid')
633
+ origin_sdf_tf = delta_T.as_frames('sdf', 'sdf') * origin_sdf
634
+ origin_tf = self.T_sdf_grid_ * origin_sdf_tf
635
+ origin_tf = origin_tf.data
636
+
637
+ # use same resolution (since indices will be rescaled)
638
+ resolution_tf = self.resolution_
639
+ origin_res_t = time.clock()
640
+
641
+ # add each point to the new pose
642
+ if detailed:
643
+ sdf_data_tf = np.zeros([num_pts, 1])
644
+ for i in range(num_pts):
645
+ sdf_data_tf[i] = self[pts_tf[i, 0], pts_tf[i, 1], pts_tf[i, 2]]
646
+ else:
647
+ pts_tf_round = np.round(pts_tf).astype(np.int64)
648
+
649
+ # snap to closest boundary
650
+ pts_tf_round[:, 0] = np.max(np.c_[np.zeros([num_pts, 1]), pts_tf_round[:, 0]], axis=1)
651
+ pts_tf_round[:, 0] = np.min(np.c_[(self.dims_[0] - 1) * np.ones([num_pts, 1]), pts_tf_round[:, 0]], axis=1)
652
+
653
+ pts_tf_round[:, 1] = np.max(np.c_[np.zeros([num_pts, 1]), pts_tf_round[:, 1]], axis=1)
654
+ pts_tf_round[:, 1] = np.min(np.c_[(self.dims_[1] - 1) * np.ones([num_pts, 1]), pts_tf_round[:, 1]], axis=1)
655
+
656
+ pts_tf_round[:, 2] = np.max(np.c_[np.zeros([num_pts, 1]), pts_tf_round[:, 2]], axis=1)
657
+ pts_tf_round[:, 2] = np.min(np.c_[(self.dims_[2] - 1) * np.ones([num_pts, 1]), pts_tf_round[:, 2]], axis=1)
658
+
659
+ sdf_data_tf = self.data_[pts_tf_round[:, 0], pts_tf_round[:, 1], pts_tf_round[:, 2]]
660
+
661
+ sdf_data_tf_grid = sdf_data_tf.reshape(self.dims_)
662
+ tf_t = time.clock()
663
+
664
+ logging.debug('Sdf3D: Time to transform coords: %f' % (all_points_t - start_t))
665
+ logging.debug('Sdf3D: Time to transform origin: %f' % (origin_res_t - all_points_t))
666
+ logging.debug('Sdf3D: Time to transfer sd: %f' % (tf_t - origin_res_t))
667
+ return Sdf3D(sdf_data_tf_grid, origin_tf, resolution_tf, use_abs=self._use_abs_, T_sdf_world=self.T_sdf_world_)
668
+
669
+ def transform_pt_obj_to_grid(self, x_sdf, direction=False):
670
+ """ Converts a point in sdf coords to the grid basis. If direction then don't translate.
671
+
672
+ Parameters
673
+ ----------
674
+ x_sdf : numpy 3xN ndarray or numeric scalar
675
+ points to transform from sdf basis in meters to grid basis
676
+ direction : bool
677
+ Returns
678
+ -------
679
+ x_grid : numpy 3xN ndarray or scalar
680
+ points in grid basis
681
+ """
682
+ if isinstance(x_sdf, Number):
683
+ return self.T_world_grid_.scale * x_sdf
684
+ if direction:
685
+ points_sdf = NormalCloud(x_sdf.astype(np.float32), frame='world')
686
+ else:
687
+ points_sdf = PointCloud(x_sdf.astype(np.float32), frame='world')
688
+ x_grid = self.T_world_grid_ * points_sdf
689
+ return x_grid.data
690
+
691
+ def transform_pt_grid_to_obj(self, x_grid, direction=False):
692
+ """ Converts a point in grid coords to the world basis. If direction then don't translate.
693
+
694
+ Parameters
695
+ ----------
696
+ x_grid : numpy 3xN ndarray or numeric scalar
697
+ points to transform from grid basis to sdf basis in meters
698
+ direction : bool
699
+ Returns
700
+ -------
701
+ x_sdf : numpy 3xN ndarray
702
+ points in sdf basis (meters)
703
+ """
704
+ if isinstance(x_grid, Number):
705
+ return self.T_grid_world_.scale * x_grid
706
+ if direction:
707
+ points_grid = NormalCloud(x_grid.astype(np.float32), frame='grid')
708
+ else:
709
+ points_grid = PointCloud(x_grid.astype(np.float32), frame='grid')
710
+ x_sdf = self.T_grid_world_ * points_grid
711
+ return x_sdf.data
712
+
713
+ @staticmethod
714
+ def find_zero_crossing_linear(x1, y1, x2, y2):
715
+ """ Find zero crossing using linear approximation"""
716
+ # NOTE: use sparingly, approximations can be shoddy
717
+ d = x2 - x1
718
+ t1 = 0
719
+ t2 = np.linalg.norm(d)
720
+ v = d / t2
721
+
722
+ m = (y2 - y1) / (t2 - t1)
723
+ b = y1
724
+ t_zc = -b / m
725
+ x_zc = x1 + t_zc * v
726
+ return x_zc
727
+
728
+ @staticmethod
729
+ def find_zero_crossing_quadratic(x1, y1, x2, y2, x3, y3, eps=1.0):
730
+ """ Find zero crossing using quadratic approximation along 1d line"""
731
+ # compute coords along 1d line
732
+ v = x2 - x1
733
+ v = v / np.linalg.norm(v)
734
+ if v[v != 0].shape[0] == 0:
735
+ logging.error('Difference is 0. Probably a bug')
736
+
737
+ t1 = 0
738
+ t2 = (x2 - x1)[v != 0] / v[v != 0]
739
+ t2 = t2[0]
740
+ t3 = (x3 - x1)[v != 0] / v[v != 0]
741
+ t3 = t3[0]
742
+
743
+ # solve for quad approx
744
+ x1_row = np.array([t1 ** 2, t1, 1])
745
+ x2_row = np.array([t2 ** 2, t2, 1])
746
+ x3_row = np.array([t3 ** 2, t3, 1])
747
+ X = np.array([x1_row, x2_row, x3_row])
748
+ y_vec = np.array([y1, y2, y3])
749
+ try:
750
+ w = np.linalg.solve(X, y_vec)
751
+ except np.linalg.LinAlgError:
752
+ logging.error('Singular matrix. Probably a bug')
753
+ return None
754
+
755
+ # get positive roots
756
+ possible_t = np.roots(w)
757
+ t_zc = None
758
+ for i in range(possible_t.shape[0]):
759
+ if 0 <= possible_t[i] <= 10 and not np.iscomplex(possible_t[i]):
760
+ t_zc = possible_t[i]
761
+
762
+ # if no positive roots find min
763
+ if np.abs(w[0]) < 1e-10:
764
+ return None
765
+
766
+ if t_zc is None:
767
+ t_zc = -w[1] / (2 * w[0])
768
+
769
+ if t_zc < -eps or t_zc > eps:
770
+ return None
771
+
772
+ x_zc = x1 + t_zc * v
773
+ return x_zc
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/sdf_file.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Reads and writes sdfs to file
3
+ Author: Jeff Mahler
4
+ '''
5
+ import numpy as np
6
+ import os
7
+
8
+ from . import sdf
9
+
10
+ class SdfFile:
11
+ """
12
+ A Signed Distance Field .sdf file reader and writer.
13
+
14
+ Attributes
15
+ ----------
16
+ filepath : :obj:`str`
17
+ The full path to the .sdf or .csv file associated with this reader/writer.
18
+ """
19
+ def __init__(self, filepath):
20
+ """Construct and initialize a .sdf file reader and writer.
21
+
22
+ Parameters
23
+ ----------
24
+ filepath : :obj:`str`
25
+ The full path to the desired .sdf or .csv file
26
+
27
+ Raises
28
+ ------
29
+ ValueError
30
+ If the file extension is not .sdf of .csv.
31
+ """
32
+ self.filepath_ = filepath
33
+ file_root, file_ext = os.path.splitext(self.filepath_)
34
+
35
+ if file_ext == '.sdf':
36
+ self.use_3d_ = True
37
+ elif file_ext == '.csv':
38
+ self.use_3d_ = False
39
+ else:
40
+ raise ValueError('Extension %s invalid for SDFs' %(file_ext))
41
+
42
+ @property
43
+ def filepath(self):
44
+ """Returns the full path to the file associated with this reader/writer.
45
+
46
+ Returns
47
+ -------
48
+ :obj:`str`
49
+ The full path to the file associated with this reader/writer.
50
+ """
51
+ return self.filepath_
52
+
53
+ def read(self):
54
+ """Reads in the SDF file and returns a Sdf object.
55
+
56
+ Returns
57
+ -------
58
+ :obj:`Sdf`
59
+ A Sdf created from the data in the file.
60
+ """
61
+ if self.use_3d_:
62
+ return self._read_3d()
63
+ else:
64
+ return self._read_2d()
65
+
66
+
67
+ def _read_3d(self):
68
+ """Reads in a 3D SDF file and returns a Sdf object.
69
+
70
+ Returns
71
+ -------
72
+ :obj:`Sdf3D`
73
+ A 3DSdf created from the data in the file.
74
+ """
75
+ if not os.path.exists(self.filepath_):
76
+ return None
77
+
78
+ my_file = open(self.filepath_, 'r')
79
+ nx, ny, nz = [int(i) for i in my_file.readline().split()] #dimension of each axis should all be equal for LSH
80
+ ox, oy, oz = [float(i) for i in my_file.readline().split()] #shape origin
81
+ dims = np.array([nx, ny, nz])
82
+ origin = np.array([ox, oy, oz])
83
+
84
+ resolution = float(my_file.readline()) # resolution of the grid cells in original mesh coords
85
+ sdf_data = np.zeros(dims)
86
+
87
+ # loop through file, getting each value
88
+ count = 0
89
+ for k in range(nz):
90
+ for j in range(ny):
91
+ for i in range(nx):
92
+ sdf_data[i][j][k] = float(my_file.readline())
93
+ count += 1
94
+ my_file.close()
95
+ return sdf.Sdf3D(sdf_data, origin, resolution)
96
+
97
+ def _read_2d(self):
98
+ """Reads in a 2D SDF file and returns a Sdf object.
99
+
100
+ Returns
101
+ -------
102
+ :obj:`Sdf2D`
103
+ A 2DSdf created from the data in the file.
104
+ """
105
+ if not os.path.exists(self.filepath_):
106
+ return None
107
+
108
+ sdf_data = np.loadtxt(self.filepath_, delimiter=',')
109
+ return sdf.Sdf2D(sdf_data)
110
+
111
+ def write(self, sdf):
112
+ """Writes an SDF to a file.
113
+
114
+ Parameters
115
+ ----------
116
+ sdf : :obj:`Sdf`
117
+ An Sdf object to write out.
118
+
119
+ Note
120
+ ----
121
+ This is not currently implemented or supported.
122
+ """
123
+ pass
124
+
125
+ if __name__ == '__main__':
126
+ pass
127
+
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/meshpy/stable_pose.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A basic struct-like Stable Pose class to make accessing pose probability and rotation matrix easier
3
+
4
+ Author: Matt Matl and Nikhil Sharma
5
+ """
6
+ import numpy as np
7
+
8
+ from autolab_core import RigidTransform
9
+
10
+ d_theta = np.deg2rad(1)
11
+
12
+ class StablePose(object):
13
+ """A representation of a mesh's stable pose.
14
+
15
+ Attributes
16
+ ----------
17
+ p : float
18
+ Probability associated with this stable pose.
19
+ r : :obj:`numpy.ndarray` of :obj`numpy.ndarray` of float
20
+ 3x3 rotation matrix that rotates the mesh into the stable pose from
21
+ standardized coordinates.
22
+ x0 : :obj:`numpy.ndarray` of float
23
+ 3D point in the mesh that is resting on the table.
24
+ face : :obj:`numpy.ndarray`
25
+ 3D vector of indices corresponding to vertices forming the resting face
26
+ stp_id : :obj:`str`
27
+ A string identifier for the stable pose
28
+ T_obj_table : :obj:`RigidTransform`
29
+ A RigidTransform representation of the pose's rotation matrix.
30
+ """
31
+ def __init__(self, p, r, x0, face=None, stp_id=-1):
32
+ """Create a new stable pose object.
33
+
34
+ Parameters
35
+ ----------
36
+ p : float
37
+ Probability associated with this stable pose.
38
+ r : :obj:`numpy.ndarray` of :obj`numpy.ndarray` of float
39
+ 3x3 rotation matrix that rotates the mesh into the stable pose from
40
+ standardized coordinates.
41
+ x0 : :obj:`numpy.ndarray` of float
42
+ 3D point in the mesh that is resting on the table.
43
+ face : :obj:`numpy.ndarray`
44
+ 3D vector of indices corresponding to vertices forming the resting face
45
+ stp_id : :obj:`str`
46
+ A string identifier for the stable pose
47
+ """
48
+ self.p = p
49
+ self.r = r
50
+ self.x0 = x0
51
+ self.face = face
52
+ self.id = stp_id
53
+
54
+ # fix stable pose bug
55
+ if np.abs(np.linalg.det(self.r) + 1) < 0.01:
56
+ self.r[1,:] = -self.r[1,:]
57
+
58
+ def __eq__(self, other):
59
+ """ Check equivalence by rotation about the z axis """
60
+ if not isinstance(other, StablePose):
61
+ raise ValueError('Can only compare stable pose objects')
62
+ R0 = self.r
63
+ R1 = other.r
64
+ dR = R1.T.dot(R0)
65
+ theta = 0
66
+ while theta < 2 * np.pi:
67
+ Rz = RigidTransform.z_axis_rotation(theta)
68
+ dR = R1.T.dot(Rz).dot(R0)
69
+ if np.linalg.norm(dR - np.eye(3)) < 1e-5:
70
+ return True
71
+ theta += d_theta
72
+ return False
73
+
74
+ @property
75
+ def T_obj_table(self):
76
+ return RigidTransform(rotation=self.r, from_frame='obj', to_frame='table')
77
+
78
+
79
+ @property
80
+ def T_obj_world(self):
81
+ T_world_obj = RigidTransform(rotation=self.r.T,
82
+ translation=self.x0,
83
+ from_frame='world',
84
+ to_frame='obj')
85
+ return T_world_obj.inverse()
86
+
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/dexnet/grasping/quality.py ADDED
@@ -0,0 +1,819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # """
3
+ # Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
4
+ # Permission to use, copy, modify, and distribute this software and its documentation for educational,
5
+ # research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
6
+ # hereby granted, provided that the above copyright notice, this paragraph and the following two
7
+ # paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
8
+ # Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
9
+ # 7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
10
+ #
11
+ # IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
12
+ # INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
13
+ # THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
14
+ # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
+ #
16
+ # REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ # THE IMPLIgit clone https://github.com/jeffmahler/Boost.NumPy.git
18
+ # ED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
+ # PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
20
+ # HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
21
+ # MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
22
+ # """
23
+ # """
24
+ # Quasi-static point-based grasp quality metrics.
25
+ # Author: Jeff Mahler and Brian Hou
26
+ # """
27
+ import logging
28
+ # logging.root.setLevel(level=logging.DEBUG)
29
+ import numpy as np
30
+
31
+ try:
32
+ import pyhull.convex_hull as cvh
33
+ except:
34
+ # logging.warning('Failed to import pyhull')
35
+ pass
36
+ try:
37
+ import cvxopt as cvx
38
+ except:
39
+ # logging.warning('Failed to import cvx')
40
+ pass
41
+ import os
42
+ import scipy.spatial as ss
43
+ import sys
44
+ import time
45
+
46
+ from .grasp import PointGrasp
47
+ from. graspable_object import GraspableObject3D
48
+ from .grasp_quality_config import GraspQualityConfig
49
+
50
+ from .meshpy import mesh as m
51
+ from .meshpy import sdf as s
52
+
53
+ import matplotlib.pyplot as plt
54
+ from mpl_toolkits.mplot3d import Axes3D
55
+
56
+ import IPython
57
+
58
+ # turn off output logging
59
+ cvx.solvers.options['show_progress'] = False
60
+
61
+
62
+ class PointGraspMetrics3D:
63
+ """ Class to wrap functions for quasistatic point grasp quality metrics.
64
+ """
65
+
66
+ @staticmethod
67
+ def grasp_quality(grasp, obj, params, contacts=None, vis=False):
68
+ """
69
+ Computes the quality of a two-finger point grasps on a given object using a quasi-static model.
70
+
71
+ Parameters
72
+ ----------
73
+ grasp : :obj:`ParallelJawPtGrasp3D`
74
+ grasp to evaluate
75
+ obj : :obj:`GraspableObject3D`
76
+ object to evaluate quality on
77
+ params : :obj:`GraspQualityConfig`
78
+ parameters of grasp quality function
79
+ """
80
+ start = time.time()
81
+ if not isinstance(grasp, PointGrasp):
82
+ raise ValueError('Must provide a point grasp object')
83
+ if not isinstance(obj, GraspableObject3D):
84
+ raise ValueError('Must provide a 3D graspable object')
85
+ if not isinstance(params, GraspQualityConfig):
86
+ raise ValueError('Must provide GraspQualityConfig')
87
+
88
+ # read in params
89
+ method = params.quality_method
90
+ friction_coef = params.friction_coef
91
+ num_cone_faces = params.num_cone_faces
92
+ soft_fingers = params.soft_fingers
93
+ check_approach = params.check_approach
94
+ if not hasattr(PointGraspMetrics3D, method):
95
+ raise ValueError('Illegal point grasp metric %s specified' % (method))
96
+
97
+ # get point grasp contacts
98
+ contacts_start = time.time()
99
+ if contacts is None:
100
+ contacts_found, contacts = grasp.close_fingers(obj, check_approach=check_approach, vis=vis)
101
+ if not contacts_found:
102
+ logging.debug('Contacts not found')
103
+ return 0
104
+
105
+ if method == 'force_closure':
106
+ # Use fast force closure test (Nguyen 1988) if possible.
107
+ if len(contacts) == 2:
108
+ c1, c2 = contacts
109
+ return PointGraspMetrics3D.force_closure(c1, c2, friction_coef)
110
+
111
+ # Default to QP force closure test.
112
+ method = 'force_closure_qp'
113
+
114
+ # add the forces, torques, etc at each contact point
115
+ forces_start = time.time()
116
+ num_contacts = len(contacts)
117
+ forces = np.zeros([3, 0])
118
+ torques = np.zeros([3, 0])
119
+ normals = np.zeros([3, 0])
120
+ for i in range(num_contacts):
121
+ contact = contacts[i]
122
+ if vis:
123
+ if i == 0:
124
+ contact.plot_friction_cone(color='y')
125
+ else:
126
+ contact.plot_friction_cone(color='c')
127
+
128
+ # get contact forces
129
+ force_success, contact_forces, contact_outward_normal = contact.friction_cone(num_cone_faces, friction_coef)
130
+
131
+ if not force_success:
132
+ print('Force computation failed')
133
+ logging.debug('Force computation failed')
134
+ if params.all_contacts_required:
135
+ return 0
136
+
137
+ # get contact torques
138
+ torque_success, contact_torques = contact.torques(contact_forces)
139
+ if not torque_success:
140
+ print('Torque computation failed')
141
+ logging.debug('Torque computation failed')
142
+ if params.all_contacts_required:
143
+ return 0
144
+
145
+ # get the magnitude of the normal force that the contacts could apply
146
+ n = contact.normal_force_magnitude()
147
+
148
+ forces = np.c_[forces, n * contact_forces]
149
+ torques = np.c_[torques, n * contact_torques]
150
+ normals = np.c_[normals, n * -contact_outward_normal] # store inward pointing normals
151
+
152
+ if normals.shape[1] == 0:
153
+ logging.debug('No normals')
154
+ print('No normals')
155
+ return 0
156
+
157
+ # normalize torques
158
+ if 'torque_scaling' not in list(params.keys()):
159
+ torque_scaling = 1.0
160
+ if method == 'ferrari_canny_L1':
161
+ mn, mx = obj.mesh.bounding_box()
162
+ torque_scaling = 1.0 / np.median(mx)
163
+ print("torque scaling", torque_scaling)
164
+ params.torque_scaling = torque_scaling
165
+
166
+ if vis:
167
+ ax = plt.gca()
168
+ ax.set_xlim3d(0, obj.sdf.dims_[0])
169
+ ax.set_ylim3d(0, obj.sdf.dims_[1])
170
+ ax.set_zlim3d(0, obj.sdf.dims_[2])
171
+ plt.show()
172
+
173
+ # evaluate the desired quality metric
174
+ quality_start = time.time()
175
+ Q_func = getattr(PointGraspMetrics3D, method)
176
+ quality = Q_func(forces, torques, normals,
177
+ soft_fingers=soft_fingers,
178
+ params=params)
179
+
180
+ end = time.time()
181
+ logging.debug('Contacts took %.3f sec' % (forces_start - contacts_start))
182
+ logging.debug('Forces took %.3f sec' % (quality_start - forces_start))
183
+ logging.debug('Quality eval took %.3f sec' % (end - quality_start))
184
+ logging.debug('Everything took %.3f sec' % (end - start))
185
+
186
+ return quality
187
+
188
+ @staticmethod
189
+ def grasp_matrix(forces, torques, normals, soft_fingers=False,
190
+ finger_radius=0.005, params=None):
191
+ """ Computes the grasp map between contact forces and wrenchs on the object in its reference frame.
192
+
193
+ Parameters
194
+ ----------
195
+ forces : 3xN :obj:`numpy.ndarray`
196
+ set of forces on object in object basis
197
+ torques : 3xN :obj:`numpy.ndarray`
198
+ set of torques on object in object basis
199
+ normals : 3xN :obj:`numpy.ndarray`
200
+ surface normals at the contact points
201
+ soft_fingers : bool
202
+ whether or not to use the soft finger contact model
203
+ finger_radius : float
204
+ the radius of the fingers to use
205
+ params : :obj:`GraspQualityConfig`
206
+ set of parameters for grasp matrix and contact model
207
+
208
+ Returns
209
+ -------
210
+ G : 6xM :obj:`numpy.ndarray`
211
+ grasp map
212
+ """
213
+ if params is not None and 'finger_radius' in list(params.keys()):
214
+ finger_radius = params.finger_radius
215
+ num_forces = forces.shape[1]
216
+ num_torques = torques.shape[1]
217
+ if num_forces != num_torques:
218
+ raise ValueError('Need same number of forces and torques')
219
+
220
+ num_cols = num_forces
221
+ if soft_fingers:
222
+ num_normals = 2
223
+ if normals.ndim > 1:
224
+ num_normals = 2 * normals.shape[1]
225
+ num_cols = num_cols + num_normals
226
+
227
+ G = np.zeros([6, num_cols])
228
+ for i in range(num_forces):
229
+ G[:3, i] = forces[:, i]
230
+ # print("liang", params.torque_scaling)
231
+ G[3:, i] = params.torque_scaling * torques[:, i]
232
+
233
+ if soft_fingers:
234
+ torsion = np.pi * finger_radius ** 2 * params.friction_coef * normals * params.torque_scaling
235
+ pos_normal_i = int(-num_normals)
236
+ neg_normal_i = int(-num_normals + num_normals / 2)
237
+ G[3:, pos_normal_i:neg_normal_i] = torsion
238
+ G[3:, neg_normal_i:] = -torsion
239
+
240
+ return G
241
+
242
+ @staticmethod
243
+ def force_closure(c1, c2, friction_coef, use_abs_value=True):
244
+ """" Checks force closure using the antipodality trick.
245
+
246
+ Parameters
247
+ ----------
248
+ c1 : :obj:`Contact3D`
249
+ first contact point
250
+ c2 : :obj:`Contact3D`
251
+ second contact point
252
+ friction_coef : float
253
+ coefficient of friction at the contact point
254
+ use_abs_value : bool
255
+ whether or not to use directoinality of the surface normal (useful when mesh is not oriented)
256
+
257
+ Returns
258
+ -------
259
+ int : 1 if in force closure, 0 otherwise
260
+ """
261
+ if c1.point is None or c2.point is None or c1.normal is None or c2.normal is None:
262
+ return 0
263
+ p1, p2 = c1.point, c2.point
264
+ n1, n2 = -c1.normal, -c2.normal # inward facing normals
265
+
266
+ if (p1 == p2).all(): # same point
267
+ return 0
268
+
269
+ for normal, contact, other_contact in [(n1, p1, p2), (n2, p2, p1)]:
270
+ diff = other_contact - contact
271
+ normal_proj = normal.dot(diff) / np.linalg.norm(normal)
272
+ if use_abs_value:
273
+ normal_proj = abs(normal.dot(diff)) / np.linalg.norm(normal)
274
+
275
+ if normal_proj < 0:
276
+ return 0 # wrong side
277
+ alpha = np.arccos(normal_proj / np.linalg.norm(diff))
278
+ if alpha > np.arctan(friction_coef):
279
+ return 0 # outside of friction cone
280
+ return 1
281
+
282
+ @staticmethod
283
+ def force_closure_qp(forces, torques, normals, soft_fingers=False,
284
+ wrench_norm_thresh=1e-3, wrench_regularizer=1e-10,
285
+ params=None):
286
+ """ Checks force closure by solving a quadratic program (whether or not zero is in the convex hull)
287
+
288
+ Parameters
289
+ ----------
290
+ forces : 3xN :obj:`numpy.ndarray`
291
+ set of forces on object in object basis
292
+ torques : 3xN :obj:`numpy.ndarray`
293
+ set of torques on object in object basis
294
+ normals : 3xN :obj:`numpy.ndarray`
295
+ surface normals at the contact points
296
+ soft_fingers : bool
297
+ whether or not to use the soft finger contact model
298
+ wrench_norm_thresh : float
299
+ threshold to use to determine equivalence of target wrenches
300
+ wrench_regularizer : float
301
+ small float to make quadratic program positive semidefinite
302
+ params : :obj:`GraspQualityConfig`
303
+ set of parameters for grasp matrix and contact model
304
+
305
+ Returns
306
+ -------
307
+ int : 1 if in force closure, 0 otherwise
308
+ """
309
+ if params is not None:
310
+ if 'wrench_norm_thresh' in list(params.keys()):
311
+ wrench_norm_thresh = params.wrench_norm_thresh
312
+ if 'wrench_regularizer' in list(params.keys()):
313
+ wrench_regularizer = params.wrench_regularizer
314
+
315
+ G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals, soft_fingers, params=params)
316
+ min_norm, _ = PointGraspMetrics3D.min_norm_vector_in_facet(G, wrench_regularizer=wrench_regularizer)
317
+ return 1 * (min_norm < wrench_norm_thresh) # if greater than wrench_norm_thresh, 0 is outside of hull
318
+
319
+ @staticmethod
320
+ def partial_closure(forces, torques, normals, soft_fingers=False,
321
+ wrench_norm_thresh=1e-3, wrench_regularizer=1e-10,
322
+ params=None):
323
+ """ Evalutes partial closure: whether or not the forces and torques can resist a specific wrench.
324
+ Estimates resistance by sollving a quadratic program (whether or not the target wrench is in the convex hull).
325
+
326
+ Parameters
327
+ ----------
328
+ forces : 3xN :obj:`numpy.ndarray`
329
+ set of forces on object in object basis
330
+ torques : 3xN :obj:`numpy.ndarray`
331
+ set of torques on object in object basis
332
+ normals : 3xN :obj:`numpy.ndarray`
333
+ surface normals at the contact points
334
+ soft_fingers : bool
335
+ whether or not to use the soft finger contact model
336
+ wrench_norm_thresh : float
337
+ threshold to use to determine equivalence of target wrenches
338
+ wrench_regularizer : float
339
+ small float to make quadratic program positive semidefinite
340
+ params : :obj:`GraspQualityConfig`
341
+ set of parameters for grasp matrix and contact model
342
+
343
+ Returns
344
+ -------
345
+ int : 1 if in partial closure, 0 otherwise
346
+ """
347
+ force_limit = None
348
+ if params is None:
349
+ return 0
350
+ force_limit = params.force_limits
351
+ target_wrench = params.target_wrench
352
+ if 'wrench_norm_thresh' in list(params.keys()):
353
+ wrench_norm_thresh = params.wrench_norm_thresh
354
+ if 'wrench_regularizer' in list(params.keys()):
355
+ wrench_regularizer = params.wrench_regularizer
356
+
357
+ # reorganize the grasp matrix for easier constraint enforcement in optimization
358
+ num_fingers = normals.shape[1]
359
+ num_wrenches_per_finger = forces.shape[1] / num_fingers
360
+ G = np.zeros([6, 0])
361
+ for i in range(num_fingers):
362
+ start_i = num_wrenches_per_finger * i
363
+ end_i = num_wrenches_per_finger * (i + 1)
364
+ G_i = PointGraspMetrics3D.grasp_matrix(forces[:, start_i:end_i], torques[:, start_i:end_i],
365
+ normals[:, i:i + 1],
366
+ soft_fingers, params=params)
367
+ G = np.c_[G, G_i]
368
+
369
+ wrench_resisted, _ = PointGraspMetrics3D.wrench_in_positive_span(G, target_wrench, force_limit, num_fingers,
370
+ wrench_norm_thresh=wrench_norm_thresh,
371
+ wrench_regularizer=wrench_regularizer)
372
+ return 1 * wrench_resisted
373
+
374
+ @staticmethod
375
+ def wrench_resistance(forces, torques, normals, soft_fingers=False,
376
+ wrench_norm_thresh=1e-3, wrench_regularizer=1e-10,
377
+ finger_force_eps=1e-9, params=None):
378
+ """ Evalutes wrench resistance: the inverse norm of the contact forces required to resist a target wrench
379
+ Estimates resistance by sollving a quadratic program (min normal contact forces to produce a wrench).
380
+
381
+ Parameters
382
+ ----------
383
+ forces : 3xN :obj:`numpy.ndarray`
384
+ set of forces on object in object basis
385
+ torques : 3xN :obj:`numpy.ndarray`
386
+ set of torques on object in object basis
387
+ normals : 3xN :obj:`numpy.ndarray`
388
+ surface normals at the contact points
389
+ soft_fingers : bool
390
+ whether or not to use the soft finger contact model
391
+ wrench_norm_thresh : float
392
+ threshold to use to determine equivalence of target wrenches
393
+ wrench_regularizer : float
394
+ small float to make quadratic program positive semidefinite
395
+ finger_force_eps : float
396
+ small float to prevent numeric issues in wrench resistance metric
397
+ params : :obj:`GraspQualityConfig`
398
+ set of parameters for grasp matrix and contact model
399
+
400
+ Returns
401
+ -------
402
+ float : value of wrench resistance metric
403
+ """
404
+ force_limit = None
405
+ if params is None:
406
+ return 0
407
+ force_limit = params.force_limits
408
+ target_wrench = params.target_wrench
409
+ if 'wrench_norm_thresh' in list(params.keys()):
410
+ wrench_norm_thresh = params.wrench_norm_thresh
411
+ if 'wrench_regularizer' in list(params.keys()):
412
+ wrench_regularizer = params.wrench_regularizer
413
+ if 'finger_force_eps' in list(params.keys()):
414
+ finger_force_eps = params.finger_force_eps
415
+
416
+ # reorganize the grasp matrix for easier constraint enforcement in optimization
417
+ num_fingers = normals.shape[1]
418
+ num_wrenches_per_finger = forces.shape[1] / num_fingers
419
+ G = np.zeros([6, 0])
420
+ for i in range(num_fingers):
421
+ start_i = num_wrenches_per_finger * i
422
+ end_i = num_wrenches_per_finger * (i + 1)
423
+ G_i = PointGraspMetrics3D.grasp_matrix(forces[:, start_i:end_i], torques[:, start_i:end_i],
424
+ normals[:, i:i + 1],
425
+ soft_fingers, params=params)
426
+ G = np.c_[G, G_i]
427
+
428
+ # compute metric from finger force norm
429
+ Q = 0
430
+ wrench_resisted, finger_force_norm = PointGraspMetrics3D.wrench_in_positive_span(G, target_wrench, force_limit,
431
+ num_fingers,
432
+ wrench_norm_thresh=wrench_norm_thresh,
433
+ wrench_regularizer=wrench_regularizer)
434
+ if wrench_resisted:
435
+ Q = 1.0 / (finger_force_norm + finger_force_eps) - 1.0 / (2 * force_limit)
436
+ return Q
437
+
438
+ @staticmethod
439
+ def min_singular(forces, torques, normals, soft_fingers=False, params=None):
440
+ """ Min singular value of grasp matrix - measure of wrench that grasp is "weakest" at resisting.
441
+
442
+ Parameters
443
+ ----------
444
+ forces : 3xN :obj:`numpy.ndarray`
445
+ set of forces on object in object basis
446
+ torques : 3xN :obj:`numpy.ndarray`
447
+ set of torques on object in object basis
448
+ normals : 3xN :obj:`numpy.ndarray`
449
+ surface normals at the contact points
450
+ soft_fingers : bool
451
+ whether or not to use the soft finger contact model
452
+ params : :obj:`GraspQualityConfig`
453
+ set of parameters for grasp matrix and contact model
454
+
455
+ Returns
456
+ -------
457
+ float : value of smallest singular value
458
+ """
459
+ G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals, soft_fingers)
460
+ _, S, _ = np.linalg.svd(G)
461
+ min_sig = S[5]
462
+ return min_sig
463
+
464
+ @staticmethod
465
+ def wrench_volume(forces, torques, normals, soft_fingers=False, params=None):
466
+ """ Volume of grasp matrix singular values - score of all wrenches that the grasp can resist.
467
+
468
+ Parameters
469
+ ----------
470
+ forces : 3xN :obj:`numpy.ndarray`
471
+ set of forces on object in object basis
472
+ torques : 3xN :obj:`numpy.ndarray`
473
+ set of torques on object in object basis
474
+ normals : 3xN :obj:`numpy.ndarray`
475
+ surface normals at the contact points
476
+ soft_fingers : bool
477
+ whether or not to use the soft finger contact model
478
+ params : :obj:`GraspQualityConfig`
479
+ set of parameters for grasp matrix and contact model
480
+
481
+ Returns
482
+ -------
483
+ float : value of wrench volume
484
+ """
485
+ k = 1
486
+ if params is not None and 'k' in list(params.keys()):
487
+ k = params.k
488
+
489
+ G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals, soft_fingers)
490
+ _, S, _ = np.linalg.svd(G)
491
+ sig = S
492
+ return k * np.sqrt(np.prod(sig))
493
+
494
+ @staticmethod
495
+ def grasp_isotropy(forces, torques, normals, soft_fingers=False, params=None):
496
+ """ Condition number of grasp matrix - ratio of "weakest" wrench that the grasp can exert to the "strongest" one.
497
+
498
+ Parameters
499
+ ----------
500
+ forces : 3xN :obj:`numpy.ndarray`
501
+ set of forces on object in object basis
502
+ torques : 3xN :obj:`numpy.ndarray`
503
+ set of torques on object in object basis
504
+ normals : 3xN :obj:`numpy.ndarray`
505
+ surface normals at the contact points
506
+ soft_fingers : bool
507
+ whether or not to use the soft finger contact model
508
+ params : :obj:`GraspQualityConfig`
509
+ set of parameters for grasp matrix and contact model
510
+
511
+ Returns
512
+ -------
513
+ float : value of grasp isotropy metric
514
+ """
515
+ G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals, soft_fingers)
516
+ _, S, _ = np.linalg.svd(G)
517
+ max_sig = S[0]
518
+ min_sig = S[5]
519
+ isotropy = min_sig / max_sig
520
+ if np.isnan(isotropy) or np.isinf(isotropy):
521
+ return 0
522
+ return isotropy
523
+
524
+ @staticmethod
525
+ def ferrari_canny_L1(forces, torques, normals, soft_fingers=False, params=None,
526
+ wrench_norm_thresh=1e-3,
527
+ wrench_regularizer=1e-10):
528
+ """ Ferrari & Canny's L1 metric. Also known as the epsilon metric.
529
+
530
+ Parameters
531
+ ----------
532
+ forces : 3xN :obj:`numpy.ndarray`
533
+ set of forces on object in object basis
534
+ torques : 3xN :obj:`numpy.ndarray`
535
+ set of torques on object in object basis
536
+ normals : 3xN :obj:`numpy.ndarray`
537
+ surface normals at the contact points
538
+ soft_fingers : bool
539
+ whether or not to use the soft finger contact model
540
+ params : :obj:`GraspQualityConfig`
541
+ set of parameters for grasp matrix and contact model
542
+ wrench_norm_thresh : float
543
+ threshold to use to determine equivalence of target wrenches
544
+ wrench_regularizer : float
545
+ small float to make quadratic program positive semidefinite
546
+
547
+ Returns
548
+ -------
549
+ float : value of metric
550
+ """
551
+ if params is not None and 'wrench_norm_thresh' in list(params.keys()):
552
+ wrench_norm_thresh = params.wrench_norm_thresh
553
+ if params is not None and 'wrench_regularizer' in list(params.keys()):
554
+ wrench_regularizer = params.wrench_regularizer
555
+
556
+ # create grasp matrix
557
+ G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals,
558
+ soft_fingers, params=params)
559
+ s = time.time()
560
+ # center grasp matrix for better convex hull comp
561
+ hull = cvh.ConvexHull(G.T)
562
+ # TODO: suppress ridiculous amount of output for perfectly valid input to qhull
563
+ e = time.time()
564
+ logging.debug('CVH took %.3f sec' % (e - s))
565
+
566
+ debug = False
567
+ if debug:
568
+ fig = plt.figure()
569
+ torques = G[3:, :].T
570
+ ax = Axes3D(fig)
571
+ ax.scatter(torques[:, 0], torques[:, 1], torques[:, 2], c='b', s=50)
572
+ ax.scatter(0, 0, 0, c='k', s=80)
573
+ ax.set_xlim3d(-1.5, 1.5)
574
+ ax.set_ylim3d(-1.5, 1.5)
575
+ ax.set_zlim3d(-1.5, 1.5)
576
+ ax.set_xlabel('tx')
577
+ ax.set_ylabel('ty')
578
+ ax.set_zlabel('tz')
579
+ plt.show()
580
+
581
+ if len(hull.vertices) == 0:
582
+ logging.warning('Convex hull could not be computed')
583
+ return 0.0
584
+
585
+ # determine whether or not zero is in the convex hull
586
+ s = time.time()
587
+ min_norm_in_hull, v = PointGraspMetrics3D.min_norm_vector_in_facet(G, wrench_regularizer=wrench_regularizer)
588
+ e = time.time()
589
+ logging.debug('Min norm took %.3f sec' % (e - s))
590
+ # print("shunang",min_norm_in_hull)
591
+
592
+ # if norm is greater than 0 then forces are outside of hull
593
+ if min_norm_in_hull > wrench_norm_thresh:
594
+ logging.debug('Zero not in convex hull')
595
+ return 0.0
596
+
597
+ # if there are fewer nonzeros than D-1 (dim of space minus one)
598
+ # then zero is on the boundary and therefore we do not have
599
+ # force closure
600
+ if np.sum(v > 1e-4) <= G.shape[0] - 1:
601
+ logging.warning('Zero not in interior of convex hull')
602
+ return 0.0
603
+
604
+ # find minimum norm vector across all facets of convex hull
605
+ s = time.time()
606
+ min_dist = sys.float_info.max
607
+ closest_facet = None
608
+ # print("shunang",G)
609
+ for v in hull.vertices:
610
+ if np.max(np.array(v)) < G.shape[1]: # because of some occasional odd behavior from pyhull
611
+ facet = G[:, v]
612
+ # print("shunang1",facet)
613
+ dist, _ = PointGraspMetrics3D.min_norm_vector_in_facet(facet, wrench_regularizer=wrench_regularizer)
614
+ if dist < min_dist:
615
+ min_dist = dist
616
+ closest_facet = v
617
+ e = time.time()
618
+ logging.debug('Min dist took %.3f sec for %d vertices' % (e - s, len(hull.vertices)))
619
+
620
+ return min_dist
621
+
622
+
623
+ @staticmethod
624
+ def ferrari_canny_L1_force_only(forces, torques, normals, soft_fingers=False, params=None,
625
+ wrench_norm_thresh=1e-3,
626
+ wrench_regularizer=1e-10):
627
+ """ Ferrari & Canny's L1 metric with force only. Also known as the epsilon metric.
628
+
629
+ Parameters
630
+ ----------
631
+ forces : 3xN :obj:`numpy.ndarray`
632
+ set of forces on object in object basis
633
+ torques : 3xN :obj:`numpy.ndarray`
634
+ set of torques on object in object basis
635
+ normals : 3xN :obj:`numpy.ndarray`
636
+ surface normals at the contact points
637
+ soft_fingers : bool
638
+ whether or not to use the soft finger contact model
639
+ params : :obj:`GraspQualityConfig`
640
+ set of parameters for grasp matrix and contact model
641
+ wrench_norm_thresh : float
642
+ threshold to use to determine equivalence of target wrenches
643
+ wrench_regularizer : float
644
+ small float to make quadratic program positive semidefinite
645
+
646
+ Returns
647
+ -------
648
+ float : value of metric
649
+ """
650
+ if params is not None and 'wrench_norm_thresh' in list(params.keys()):
651
+ wrench_norm_thresh = params.wrench_norm_thresh
652
+ if params is not None and 'wrench_regularizer' in list(params.keys()):
653
+ wrench_regularizer = params.wrench_regularizer
654
+
655
+ # create grasp matrix
656
+ G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals,
657
+ soft_fingers, params=params)
658
+ G = G[:3, :]
659
+ s = time.time()
660
+ # center grasp matrix for better convex hull comp
661
+ hull = cvh.ConvexHull(G.T)
662
+ # TODO: suppress ridiculous amount of output for perfectly valid input to qhull
663
+ e = time.time()
664
+ logging.debug('CVH took %.3f sec' % (e - s))
665
+
666
+ debug = False
667
+ if debug:
668
+ fig = plt.figure()
669
+ torques = G[3:, :].T
670
+ ax = Axes3D(fig)
671
+ ax.scatter(torques[:, 0], torques[:, 1], torques[:, 2], c='b', s=50)
672
+ ax.scatter(0, 0, 0, c='k', s=80)
673
+ ax.set_xlim3d(-1.5, 1.5)
674
+ ax.set_ylim3d(-1.5, 1.5)
675
+ ax.set_zlim3d(-1.5, 1.5)
676
+ ax.set_xlabel('tx')
677
+ ax.set_ylabel('ty')
678
+ ax.set_zlabel('tz')
679
+ plt.show()
680
+
681
+ if len(hull.vertices) == 0:
682
+ logging.warning('Convex hull could not be computed')
683
+ return 0.0
684
+
685
+ # determine whether or not zero is in the convex hull
686
+ s = time.time()
687
+ min_norm_in_hull, v = PointGraspMetrics3D.min_norm_vector_in_facet(G, wrench_regularizer=wrench_regularizer)
688
+ e = time.time()
689
+ logging.debug('Min norm took %.3f sec' % (e - s))
690
+ # print("shunang",min_norm_in_hull)
691
+
692
+ # if norm is greater than 0 then forces are outside of hull
693
+ if min_norm_in_hull > wrench_norm_thresh:
694
+ logging.debug('Zero not in convex hull')
695
+ return 0.0
696
+
697
+ # if there are fewer nonzeros than D-1 (dim of space minus one)
698
+ # then zero is on the boundary and therefore we do not have
699
+ # force closure
700
+ if np.sum(v > 1e-4) <= G.shape[0] - 1:
701
+ logging.warning('Zero not in interior of convex hull')
702
+ return 0.0
703
+
704
+ # find minimum norm vector across all facets of convex hull
705
+ s = time.time()
706
+ min_dist = sys.float_info.max
707
+ closest_facet = None
708
+ # print("shunang",G)
709
+ for v in hull.vertices:
710
+ if np.max(np.array(v)) < G.shape[1]: # because of some occasional odd behavior from pyhull
711
+ facet = G[:, v]
712
+ # print("shunang1",facet)
713
+ dist, _ = PointGraspMetrics3D.min_norm_vector_in_facet(facet, wrench_regularizer=wrench_regularizer)
714
+ if dist < min_dist:
715
+ min_dist = dist
716
+ closest_facet = v
717
+ e = time.time()
718
+ logging.debug('Min dist took %.3f sec for %d vertices' % (e - s, len(hull.vertices)))
719
+
720
+ return min_dist
721
+
722
+ @staticmethod
723
+ def wrench_in_positive_span(wrench_basis, target_wrench, force_limit, num_fingers=1,
724
+ wrench_norm_thresh=1e-4, wrench_regularizer=1e-10):
725
+ """ Check whether a target can be exerted by positive combinations of wrenches in a given basis with L1 norm fonger force limit limit.
726
+
727
+ Parameters
728
+ ----------
729
+ wrench_basis : 6xN :obj:`numpy.ndarray`
730
+ basis for the wrench space
731
+ target_wrench : 6x1 :obj:`numpy.ndarray`
732
+ target wrench to resist
733
+ force_limit : float
734
+ L1 upper bound on the forces per finger (aka contact point)
735
+ num_fingers : int
736
+ number of contacts, used to enforce L1 finger constraint
737
+ wrench_norm_thresh : float
738
+ threshold to use to determine equivalence of target wrenches
739
+ wrench_regularizer : float
740
+ small float to make quadratic program positive semidefinite
741
+
742
+ Returns
743
+ -------
744
+ int
745
+ whether or not wrench can be resisted
746
+ float
747
+ minimum norm of the finger forces required to resist the wrench
748
+ """
749
+ num_wrenches = wrench_basis.shape[1]
750
+
751
+ # quadratic and linear costs
752
+ P = wrench_basis.T.dot(wrench_basis) + wrench_regularizer * np.eye(num_wrenches)
753
+ q = -wrench_basis.T.dot(target_wrench)
754
+
755
+ # inequalities
756
+ lam_geq_zero = -1 * np.eye(num_wrenches)
757
+
758
+ num_wrenches_per_finger = num_wrenches / num_fingers
759
+ force_constraint = np.zeros([num_fingers, num_wrenches])
760
+ for i in range(num_fingers):
761
+ start_i = num_wrenches_per_finger * i
762
+ end_i = num_wrenches_per_finger * (i + 1)
763
+ force_constraint[i, start_i:end_i] = np.ones(num_wrenches_per_finger)
764
+
765
+ G = np.r_[lam_geq_zero, force_constraint]
766
+ h = np.zeros(num_wrenches + num_fingers)
767
+ for i in range(num_fingers):
768
+ h[num_wrenches + i] = force_limit
769
+
770
+ # convert to cvx and solve
771
+ P = cvx.matrix(P)
772
+ q = cvx.matrix(q)
773
+ G = cvx.matrix(G)
774
+ h = cvx.matrix(h)
775
+ sol = cvx.solvers.qp(P, q, G, h)
776
+ v = np.array(sol['x'])
777
+
778
+ min_dist = np.linalg.norm(wrench_basis.dot(v).ravel() - target_wrench) ** 2
779
+
780
+ # add back in the target wrench
781
+ return min_dist < wrench_norm_thresh, np.linalg.norm(v)
782
+
783
+ @staticmethod
784
+ def min_norm_vector_in_facet(facet, wrench_regularizer=1e-10):
785
+ """ Finds the minimum norm point in the convex hull of a given facet (aka simplex) by solving a QP.
786
+
787
+ Parameters
788
+ ----------
789
+ facet : 6xN :obj:`numpy.ndarray`
790
+ vectors forming the facet
791
+ wrench_regularizer : float
792
+ small float to make quadratic program positive semidefinite
793
+
794
+ Returns
795
+ -------
796
+ float
797
+ minimum norm of any point in the convex hull of the facet
798
+ Nx1 :obj:`numpy.ndarray`
799
+ vector of coefficients that achieves the minimum
800
+ """
801
+ dim = facet.shape[1] # num vertices in facet
802
+
803
+ # create alpha weights for vertices of facet
804
+ G = facet.T.dot(facet)
805
+ grasp_matrix = G + wrench_regularizer * np.eye(G.shape[0])
806
+
807
+ # Solve QP to minimize .5 x'Px + q'x subject to Gx <= h, Ax = b
808
+ P = cvx.matrix(2 * grasp_matrix) # quadratic cost for Euclidean dist
809
+ q = cvx.matrix(np.zeros((dim, 1)))
810
+ G = cvx.matrix(-np.eye(dim)) # greater than zero constraint
811
+ h = cvx.matrix(np.zeros((dim, 1)))
812
+ A = cvx.matrix(np.ones((1, dim))) # sum constraint to enforce convex
813
+ b = cvx.matrix(np.ones(1)) # combinations of vertices
814
+
815
+ sol = cvx.solvers.qp(P, q, G, h, A, b)
816
+ v = np.array(sol['x'])
817
+ min_norm = np.sqrt(sol['primal objective'])
818
+
819
+ return abs(min_norm), v
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/eval_utils.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = 'cxwang, mhgou'
2
+ __version__ = '1.0'
3
+
4
+ import os
5
+ import time
6
+ import numpy as np
7
+ import open3d as o3d
8
+ from transforms3d.euler import euler2mat, quat2mat
9
+
10
+ from .rotation import batch_viewpoint_params_to_matrix, matrix_to_dexnet_params
11
+
12
+ from .dexnet.grasping.quality import PointGraspMetrics3D
13
+ from .dexnet.grasping.grasp import ParallelJawPtGrasp3D
14
+ from .dexnet.grasping.graspable_object import GraspableObject3D
15
+ from .dexnet.grasping.grasp_quality_config import GraspQualityConfigFactory
16
+ from .dexnet.grasping.contacts import Contact3D
17
+ from .dexnet.grasping.meshpy.obj_file import ObjFile
18
+ from .dexnet.grasping.meshpy.sdf_file import SdfFile
19
+
20
+ def get_scene_name(num):
21
+ '''
22
+ **Input:**
23
+ - num: int of the scene number.
24
+
25
+ **Output:**
26
+ - string of the scene name.
27
+ '''
28
+ return ('scene_%04d' % (num,))
29
+
30
+ def create_table_points(lx, ly, lz, dx=0, dy=0, dz=0, grid_size=0.01):
31
+ '''
32
+ **Input:**
33
+ - lx:
34
+ - ly:
35
+ - lz:
36
+ **Output:**
37
+ - numpy array of the points with shape (-1, 3).
38
+ '''
39
+ xmap = np.linspace(0, lx, int(lx/grid_size))
40
+ ymap = np.linspace(0, ly, int(ly/grid_size))
41
+ zmap = np.linspace(0, lz, int(lz/grid_size))
42
+ xmap, ymap, zmap = np.meshgrid(xmap, ymap, zmap, indexing='xy')
43
+ xmap += dx
44
+ ymap += dy
45
+ zmap += dz
46
+ points = np.stack([xmap, ymap, zmap], axis=-1)
47
+ points = points.reshape([-1, 3])
48
+ return points
49
+
50
+ def parse_posevector(posevector):
51
+ '''
52
+ **Input:**
53
+ - posevector: list of pose
54
+ **Output:**
55
+ - obj_idx: int of the index of object.
56
+ - mat: numpy array of shape (4, 4) of the 6D pose of object.
57
+ '''
58
+ mat = np.zeros([4,4],dtype=np.float32)
59
+ alpha, beta, gamma = posevector[4:7]
60
+ alpha = alpha / 180.0 * np.pi
61
+ beta = beta / 180.0 * np.pi
62
+ gamma = gamma / 180.0 * np.pi
63
+ mat[:3,:3] = euler2mat(alpha, beta, gamma)
64
+ mat[:3,3] = posevector[1:4]
65
+ mat[3,3] = 1
66
+ obj_idx = int(posevector[0])
67
+ return obj_idx, mat
68
+
69
+ def load_dexnet_model(data_path):
70
+ '''
71
+ **Input:**
72
+
73
+ - data_path: path to load .obj & .sdf files
74
+
75
+ **Output:**
76
+ - obj: dexnet model
77
+ '''
78
+ of = ObjFile('{}.obj'.format(data_path))
79
+ sf = SdfFile('{}.sdf'.format(data_path))
80
+ mesh = of.read()
81
+ sdf = sf.read()
82
+ obj = GraspableObject3D(sdf, mesh)
83
+ return obj
84
+
85
+ def transform_points(points, trans):
86
+ '''
87
+ **Input:**
88
+
89
+ - points: (N, 3)
90
+
91
+ - trans: (4, 4)
92
+
93
+ **Output:**
94
+ - points_trans: (N, 3)
95
+ '''
96
+ ones = np.ones([points.shape[0],1], dtype=points.dtype)
97
+ points_ = np.concatenate([points, ones], axis=-1)
98
+ points_ = np.matmul(trans, points_.T).T
99
+ points_trans = points_[:,:3]
100
+ return points_trans
101
+
102
+ def compute_point_distance(A, B):
103
+ '''
104
+ **Input:**
105
+ - A: (N, 3)
106
+
107
+ - B: (M, 3)
108
+
109
+ **Output:**
110
+ - dists: (N, M)
111
+ '''
112
+ A = A[:, np.newaxis, :]
113
+ B = B[np.newaxis, :, :]
114
+ dists = np.linalg.norm(A-B, axis=-1)
115
+ return dists
116
+
117
+ def compute_closest_points(A, B):
118
+ '''
119
+ **Input:**
120
+
121
+ - A: (N, 3)
122
+
123
+ - B: (M, 3)
124
+
125
+ **Output:**
126
+
127
+ - indices: (N,) closest point index in B for each point in A
128
+ '''
129
+ dists = compute_point_distance(A, B)
130
+ indices = np.argmin(dists, axis=-1)
131
+ return indices
132
+
133
+ def voxel_sample_points(points, voxel_size=0.008):
134
+ '''
135
+ **Input:**
136
+
137
+ - points: (N, 3)
138
+
139
+ **Output:**
140
+
141
+ - points: (n, 3)
142
+ '''
143
+ cloud = o3d.geometry.PointCloud()
144
+ cloud.points = o3d.utility.Vector3dVector(points)
145
+ cloud = cloud.voxel_down_sample(voxel_size)
146
+ points = np.array(cloud.points)
147
+ return points
148
+
149
+ def topk_grasps(grasps, k=10):
150
+ '''
151
+ **Input:**
152
+
153
+ - grasps: (N, 17)
154
+
155
+ - k: int
156
+
157
+ **Output:**
158
+
159
+ - topk_grasps: (k, 17)
160
+ '''
161
+ assert(k > 0)
162
+ grasp_confidence = grasps[:, 0]
163
+ indices = np.argsort(-grasp_confidence)
164
+ topk_indices = indices[:min(k, len(grasps))]
165
+ topk_grasps = grasps[topk_indices]
166
+ return topk_grasps
167
+
168
+ def get_grasp_score(grasp, obj, fc_list, force_closure_quality_config):
169
+ tmp, is_force_closure = False, False
170
+ quality = -1
171
+ for ind_, value_fc in enumerate(fc_list):
172
+ value_fc = round(value_fc, 2)
173
+ tmp = is_force_closure
174
+ is_force_closure = PointGraspMetrics3D.grasp_quality(grasp, obj, force_closure_quality_config[value_fc])
175
+ if tmp and not is_force_closure:
176
+ quality = round(fc_list[ind_ - 1], 2)
177
+ break
178
+ elif is_force_closure and value_fc == fc_list[-1]:
179
+ quality = value_fc
180
+ break
181
+ elif value_fc == fc_list[0] and not is_force_closure:
182
+ break
183
+ return quality
184
+
185
+ def collision_detection(grasp_list, model_list, dexnet_models, poses, scene_points, outlier=0.05, empty_thresh=10, return_dexgrasps=False):
186
+ '''
187
+ **Input:**
188
+
189
+ - grasp_list: [(k1, 17), (k2, 17), ..., (kn, 17)] in camera coordinate
190
+
191
+ - model_list: [(N1, 3), (N2, 3), ..., (Nn, 3)] in camera coordinate
192
+
193
+ - dexnet_models: [GraspableObject3D,] in object coordinate
194
+
195
+ - poses: [(4, 4),] from model coordinate to camera coordinate
196
+
197
+ - scene_points: (Ns, 3) in camera coordinate
198
+
199
+ - outlier: float, used to compute workspace mask
200
+
201
+ - empty_thresh: int, 'num_inner_points < empty_thresh' means empty grasp
202
+
203
+ - return_dexgrasps: bool, return grasps in dex-net format while True
204
+
205
+ **Output:**
206
+
207
+ - collsion_mask_list: [(k1,), (k2,), ..., (kn,)]
208
+
209
+ - empty_mask_list: [(k1,), (k2,), ..., (kn,)]
210
+
211
+ - dexgrasp_list: [[ParallelJawPtGrasp3D,],] in object coordinate
212
+ '''
213
+ height = 0.02
214
+ depth_base = 0.02
215
+ finger_width = 0.01
216
+ collision_mask_list = list()
217
+ num_models = len(model_list)
218
+ empty_mask_list = list()
219
+ dexgrasp_list = list()
220
+
221
+ for i in range(num_models):
222
+ if len(grasp_list[i]) == 0:
223
+ collision_mask_list.append(list())
224
+ empty_mask_list.append(list())
225
+ if return_dexgrasps:
226
+ dexgrasp_list.append(list())
227
+ continue
228
+
229
+ ## parse grasp parameters
230
+ model = model_list[i]
231
+ obj_pose = poses[i]
232
+ dexnet_model = dexnet_models[i]
233
+ grasps = grasp_list[i]
234
+ grasp_points = grasps[:, 13:16]
235
+ grasp_poses = grasps[:, 4:13].reshape([-1,3,3])
236
+ grasp_depths = grasps[:, 3]
237
+ grasp_widths = grasps[:, 1]
238
+
239
+ ## crop scene, remove outlier
240
+ xmin, xmax = model[:,0].min(), model[:,0].max()
241
+ ymin, ymax = model[:,1].min(), model[:,1].max()
242
+ zmin, zmax = model[:,2].min(), model[:,2].max()
243
+ xlim = ((scene_points[:,0] > xmin-outlier) & (scene_points[:,0] < xmax+outlier))
244
+ ylim = ((scene_points[:,1] > ymin-outlier) & (scene_points[:,1] < ymax+outlier))
245
+ zlim = ((scene_points[:,2] > zmin-outlier) & (scene_points[:,2] < zmax+outlier))
246
+ workspace = scene_points[xlim & ylim & zlim]
247
+
248
+ # transform scene to gripper frame
249
+ target = (workspace[np.newaxis,:,:] - grasp_points[:,np.newaxis,:])
250
+ target = np.matmul(target, grasp_poses)
251
+
252
+ # compute collision mask
253
+ mask1 = ((target[:,:,2]>-height/2) & (target[:,:,2]<height/2))
254
+ mask2 = ((target[:,:,0]>-depth_base) & (target[:,:,0]<grasp_depths[:,np.newaxis]))
255
+ mask3 = (target[:,:,1]>-(grasp_widths[:,np.newaxis]/2+finger_width))
256
+ mask4 = (target[:,:,1]<-grasp_widths[:,np.newaxis]/2)
257
+ mask5 = (target[:,:,1]<(grasp_widths[:,np.newaxis]/2+finger_width))
258
+ mask6 = (target[:,:,1]>grasp_widths[:,np.newaxis]/2)
259
+ mask7 = ((target[:,:,0]>-(depth_base+finger_width)) & (target[:,:,0]<-depth_base))
260
+
261
+ left_mask = (mask1 & mask2 & mask3 & mask4)
262
+ right_mask = (mask1 & mask2 & mask5 & mask6)
263
+ bottom_mask = (mask1 & mask3 & mask5 & mask7)
264
+ inner_mask = (mask1 & mask2 &(~mask4) & (~mask6))
265
+ collision_mask = np.any((left_mask | right_mask | bottom_mask), axis=-1)
266
+ empty_mask = (np.sum(inner_mask, axis=-1) < empty_thresh)
267
+ collision_mask = (collision_mask | empty_mask)
268
+ collision_mask_list.append(collision_mask)
269
+ empty_mask_list.append(empty_mask)
270
+
271
+ ## generate grasps in dex-net format
272
+ if return_dexgrasps:
273
+ dexgrasps = list()
274
+ for grasp_id,_ in enumerate(grasps):
275
+ grasp_point = grasp_points[grasp_id]
276
+ R = grasp_poses[grasp_id]
277
+ width = grasp_widths[grasp_id]
278
+ depth = grasp_depths[grasp_id]
279
+ points_in_gripper = target[grasp_id][inner_mask[grasp_id]]
280
+ if empty_mask[grasp_id]:
281
+ dexgrasps.append(None)
282
+ continue
283
+ center = np.array([depth, 0, 0]).reshape([3, 1]) # gripper coordinate
284
+ center = np.dot(grasp_poses[grasp_id], center).reshape([3])
285
+ center = (center + grasp_point).reshape([1,3]) # camera coordinate
286
+ center = transform_points(center, np.linalg.inv(obj_pose)).reshape([3]) # object coordinate
287
+ R = np.dot(obj_pose[:3,:3].T, R)
288
+ binormal, approach_angle = matrix_to_dexnet_params(R)
289
+ grasp = ParallelJawPtGrasp3D(ParallelJawPtGrasp3D.configuration_from_params(
290
+ center, binormal, width, approach_angle), depth)
291
+ dexgrasps.append(grasp)
292
+ dexgrasp_list.append(dexgrasps)
293
+
294
+ if return_dexgrasps:
295
+ return collision_mask_list, empty_mask_list, dexgrasp_list
296
+ else:
297
+ return collision_mask_list, empty_mask_list
298
+
299
+ def eval_grasp(grasp_group, models, dexnet_models, poses, config, table=None, voxel_size=0.008, TOP_K = 50):
300
+ '''
301
+ **Input:**
302
+
303
+ - grasp_group: GraspGroup instance for evaluation.
304
+
305
+ - models: in model coordinate
306
+
307
+ - dexnet_models: models in dexnet format
308
+
309
+ - poses: from model to camera coordinate
310
+
311
+ - config: dexnet config.
312
+
313
+ - table: in camera coordinate
314
+
315
+ - voxel_size: float of the voxel size.
316
+
317
+ - TOP_K: int of the number of top grasps to evaluate.
318
+ '''
319
+ num_models = len(models)
320
+ ## grasp nms
321
+ grasp_group = grasp_group.nms(0.03, 30.0/180*np.pi)
322
+
323
+ ## assign grasps to object
324
+ # merge and sample scene
325
+ model_trans_list = list()
326
+ seg_mask = list()
327
+ for i,model in enumerate(models):
328
+ model_trans = transform_points(model, poses[i])
329
+ seg = i * np.ones(model_trans.shape[0], dtype=np.int32)
330
+ model_trans_list.append(model_trans)
331
+ seg_mask.append(seg)
332
+ seg_mask = np.concatenate(seg_mask, axis=0)
333
+ scene = np.concatenate(model_trans_list, axis=0)
334
+
335
+ # assign grasps
336
+ indices = compute_closest_points(grasp_group.translations, scene)
337
+ model_to_grasp = seg_mask[indices]
338
+ pre_grasp_list = list()
339
+ for i in range(num_models):
340
+ grasp_i = grasp_group[model_to_grasp==i]
341
+ grasp_i.sort_by_score()
342
+ pre_grasp_list.append(grasp_i[:10].grasp_group_array)
343
+ all_grasp_list = np.vstack(pre_grasp_list)
344
+ remain_mask = np.argsort(all_grasp_list[:,0])[::-1]
345
+ min_score = all_grasp_list[remain_mask[min(49,len(remain_mask) - 1)],0]
346
+
347
+ grasp_list = []
348
+ for i in range(num_models):
349
+ remain_mask_i = pre_grasp_list[i][:,0] >= min_score
350
+ grasp_list.append(pre_grasp_list[i][remain_mask_i])
351
+ # grasp_list = pre_grasp_list
352
+
353
+ ## collision detection
354
+ if table is not None:
355
+ scene = np.concatenate([scene, table])
356
+
357
+ collision_mask_list, empty_list, dexgrasp_list = collision_detection(
358
+ grasp_list, model_trans_list, dexnet_models, poses, scene, outlier=0.05, return_dexgrasps=True)
359
+
360
+ ## evaluate grasps
361
+ # score configurations
362
+ force_closure_quality_config = dict()
363
+ fc_list = np.array([1.2, 1.0, 0.8, 0.6, 0.4, 0.2])
364
+ for value_fc in fc_list:
365
+ value_fc = round(value_fc, 2)
366
+ config['metrics']['force_closure']['friction_coef'] = value_fc
367
+ force_closure_quality_config[value_fc] = GraspQualityConfigFactory.create_config(config['metrics']['force_closure'])
368
+ # get grasp scores
369
+ score_list = list()
370
+
371
+ for i in range(num_models):
372
+ dexnet_model = dexnet_models[i]
373
+ collision_mask = collision_mask_list[i]
374
+ dexgrasps = dexgrasp_list[i]
375
+ scores = list()
376
+ num_grasps = len(dexgrasps)
377
+ for grasp_id in range(num_grasps):
378
+ if collision_mask[grasp_id]:
379
+ scores.append(-1.)
380
+ continue
381
+ if dexgrasps[grasp_id] is None:
382
+ scores.append(-1.)
383
+ continue
384
+ grasp = dexgrasps[grasp_id]
385
+ score = get_grasp_score(grasp, dexnet_model, fc_list, force_closure_quality_config)
386
+ scores.append(score)
387
+ score_list.append(np.array(scores))
388
+
389
+ return grasp_list, score_list, collision_mask_list
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/pose.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = 'Minghao Gou'
2
+ __version__ = '1.0'
3
+ """
4
+ define the pose class and functions associated with this class.
5
+ """
6
+
7
+ import numpy as np
8
+ from . import trans3d
9
+ from transforms3d.euler import euler2quat
10
+
11
+ class Pose:
12
+ def __init__(self,id,x,y,z,alpha,beta,gamma):
13
+ self.id = id
14
+ self.x = x
15
+ self.y = y
16
+ self.z = z
17
+ # alpha, bata, gamma is in degree
18
+ self.alpha = alpha
19
+ self.beta = beta
20
+ self.gamma = gamma
21
+ self.quat = self.get_quat()
22
+ self.mat_4x4 = self.get_mat_4x4()
23
+ self.translation = self.get_translation()
24
+
25
+ def __repr__(self):
26
+ return '\nPose id=%d,x=%f,y=%f,z=%f,alpha=%f,beta=%f,gamma=%f' %(self.id,self.x,self.y,self.z,self.alpha,self.beta,self.gamma)+'\n'+'translation:'+self.translation.__repr__() + '\nquat:'+self.quat.__repr__()+'\nmat_4x4:'+self.mat_4x4.__repr__()
27
+
28
+ def get_id(self):
29
+ """
30
+ **Output:**
31
+
32
+ - return the id of this object
33
+ """
34
+ return self.id
35
+
36
+ def get_translation(self):
37
+ """
38
+ **Output:**
39
+
40
+ - Convert self.x, self.y, self.z into self.translation
41
+ """
42
+ return np.array([self.x,self.y,self.z])
43
+
44
+ def get_quat(self):
45
+ """
46
+ **Output:**
47
+
48
+ - Convert self.alpha, self.beta, self.gamma into self.quat
49
+ """
50
+ euler = np.array([self.alpha, self.beta, self.gamma]) / 180.0 * np.pi
51
+ quat = euler2quat(euler[0],euler[1],euler[2])
52
+ return quat
53
+
54
+ def get_mat_4x4(self):
55
+ """
56
+ **Output:**
57
+
58
+ - Convert self.x, self.y, self.z, self.alpha, self.beta and self.gamma into mat_4x4 pose
59
+ """
60
+ mat_4x4 = trans3d.get_mat(self.x,self.y,self.z,self.alpha,self.beta,self.gamma)
61
+ return mat_4x4
62
+
63
+ def pose_from_pose_vector(pose_vector):
64
+ """
65
+ **Input:**
66
+
67
+ - pose_vector: A list in the format of [id,x,y,z,alpha,beta,gamma]
68
+
69
+ **Output:**
70
+
71
+ - A pose class instance
72
+ """
73
+ return Pose(id = pose_vector[0],
74
+ x = pose_vector[1],
75
+ y = pose_vector[2],
76
+ z = pose_vector[3],
77
+ alpha = pose_vector[4],
78
+ beta = pose_vector[5],
79
+ gamma = pose_vector[6])
80
+
81
+ def pose_list_from_pose_vector_list(pose_vector_list):
82
+ """
83
+ **Input:**
84
+
85
+ - Pose vector list defined in xmlhandler.py
86
+
87
+ **Output:**
88
+
89
+ - list of poses.
90
+ """
91
+ pose_list = []
92
+ for pose_vector in pose_vector_list:
93
+ pose_list.append(pose_from_pose_vector(pose_vector))
94
+ return pose_list
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/rotation.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Author: chenxi-wang
2
+ Transformation matrices from/to viewpoints and dexnet gripper params.
3
+ """
4
+
5
+ import numpy as np
6
+ from math import pi
7
+
8
+ def rotation_matrix(alpha, beta, gamma):
9
+ '''
10
+ **Input:**
11
+
12
+ - alpha: float of alpha angle.
13
+
14
+ - beta: float of beta angle.
15
+
16
+ - gamma: float of the gamma angle.
17
+
18
+ **Output:**
19
+
20
+ - numpy array of shape (3, 3) of rotation matrix.
21
+ '''
22
+ Rx = np.array([[1, 0, 0],
23
+ [0, np.cos(alpha), -np.sin(alpha)],
24
+ [0, np.sin(alpha), np.cos(alpha)]])
25
+ Ry = np.array([[np.cos(beta), 0, np.sin(beta)],
26
+ [0, 1, 0],
27
+ [-np.sin(beta), 0, np.cos(beta)]])
28
+ Rz = np.array([[np.cos(gamma), -np.sin(gamma), 0],
29
+ [np.sin(gamma), np.cos(gamma), 0],
30
+ [0, 0, 1]])
31
+ R = Rz.dot(Ry).dot(Rx)
32
+ return R
33
+
34
+ def matrix_to_dexnet_params(matrix):
35
+ '''
36
+ **Input:**
37
+
38
+ - numpy array of shape (3, 3) of the rotation matrix.
39
+
40
+ **Output:**
41
+
42
+ - binormal: numpy array of shape (3,).
43
+
44
+ - angle: float of the angle.
45
+ '''
46
+ approach = matrix[:, 0]
47
+ binormal = matrix[:, 1]
48
+ axis_y = binormal
49
+ axis_x = np.array([axis_y[1], -axis_y[0], 0])
50
+ if np.linalg.norm(axis_x) == 0:
51
+ axis_x = np.array([1, 0, 0])
52
+ axis_x = axis_x / np.linalg.norm(axis_x)
53
+ axis_y = axis_y / np.linalg.norm(axis_y)
54
+ axis_z = np.cross(axis_x, axis_y)
55
+ R = np.c_[axis_x, np.c_[axis_y, axis_z]]
56
+ approach = R.T.dot(approach)
57
+ cos_t, sin_t = approach[0], -approach[2]
58
+ angle = np.arccos(max(min(cos_t,1),-1))
59
+ if sin_t < 0:
60
+ angle = pi * 2 - angle
61
+ return binormal, angle
62
+
63
+ def viewpoint_params_to_matrix(towards, angle):
64
+ '''
65
+ **Input:**
66
+
67
+ - towards: numpy array towards vector with shape (3,).
68
+
69
+ - angle: float of in-plane rotation.
70
+
71
+ **Output:**
72
+
73
+ - numpy array of the rotation matrix with shape (3, 3).
74
+ '''
75
+ axis_x = towards
76
+ axis_y = np.array([-axis_x[1], axis_x[0], 0])
77
+ if np.linalg.norm(axis_y) == 0:
78
+ axis_y = np.array([0, 1, 0])
79
+ axis_x = axis_x / np.linalg.norm(axis_x)
80
+ axis_y = axis_y / np.linalg.norm(axis_y)
81
+ axis_z = np.cross(axis_x, axis_y)
82
+ R1 = np.array([[1, 0, 0],
83
+ [0, np.cos(angle), -np.sin(angle)],
84
+ [0, np.sin(angle), np.cos(angle)]])
85
+ R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
86
+ matrix = R2.dot(R1)
87
+ return matrix.astype(np.float32)
88
+
89
+ def batch_viewpoint_params_to_matrix(batch_towards, batch_angle):
90
+ '''
91
+ **Input:**
92
+
93
+ - towards: numpy array towards vectors with shape (n, 3).
94
+
95
+ - angle: numpy array of in-plane rotations (n, ).
96
+
97
+ **Output:**
98
+
99
+ - numpy array of the rotation matrix with shape (n, 3, 3).
100
+ '''
101
+ axis_x = batch_towards
102
+ ones = np.ones(axis_x.shape[0], dtype=axis_x.dtype)
103
+ zeros = np.zeros(axis_x.shape[0], dtype=axis_x.dtype)
104
+ axis_y = np.stack([-axis_x[:,1], axis_x[:,0], zeros], axis=-1)
105
+ mask_y = (np.linalg.norm(axis_y, axis=-1) == 0)
106
+ axis_y[mask_y] = np.array([0, 1, 0])
107
+ axis_x = axis_x / np.linalg.norm(axis_x, axis=-1, keepdims=True)
108
+ axis_y = axis_y / np.linalg.norm(axis_y, axis=-1, keepdims=True)
109
+ axis_z = np.cross(axis_x, axis_y)
110
+ sin = np.sin(batch_angle)
111
+ cos = np.cos(batch_angle)
112
+ R1 = np.stack([ones, zeros, zeros, zeros, cos, -sin, zeros, sin, cos], axis=-1)
113
+ R1 = R1.reshape([-1,3,3])
114
+ R2 = np.stack([axis_x, axis_y, axis_z], axis=-1)
115
+ matrix = np.matmul(R2, R1)
116
+ return matrix.astype(np.float32)
117
+
118
+ def dexnet_params_to_matrix(binormal, angle):
119
+ '''
120
+ **Input:**
121
+
122
+ - binormal: numpy array of shape (3,).
123
+
124
+ - angle: float of the angle.
125
+
126
+ **Output:**
127
+
128
+ - numpy array of shape (3, 3) of the rotation matrix.
129
+ '''
130
+ axis_y = binormal
131
+ axis_x = np.array([axis_y[1], -axis_y[0], 0])
132
+ if np.linalg.norm(axis_x) == 0:
133
+ axis_x = np.array([1, 0, 0])
134
+ axis_x = axis_x / np.linalg.norm(axis_x)
135
+ axis_y = axis_y / np.linalg.norm(axis_y)
136
+ axis_z = np.cross(axis_x, axis_y)
137
+ R1 = np.array([[np.cos(angle), 0, np.sin(angle)],
138
+ [0, 1, 0],
139
+ [-np.sin(angle), 0, np.cos(angle)]])
140
+ R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
141
+ matrix = R2.dot(R1)
142
+ return matrix
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/trans3d.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transforms3d.quaternions import mat2quat, quat2mat
2
+ from transforms3d.euler import quat2euler, euler2quat
3
+ import numpy as np
4
+
5
+ def get_pose(pose):
6
+ pos, quat = pose_4x4_to_pos_quat(pose)
7
+ euler = np.array([quat2euler(quat)[0], quat2euler(quat)[1],quat2euler(quat)[2]])
8
+ euler = euler * 180.0 / np.pi
9
+ alpha, beta, gamma = euler[0], euler[1], euler[2]
10
+ x, y, z = pos[0], pos[1], pos[2]
11
+ return x,y,z, alpha, beta, gamma
12
+
13
+ def get_mat(x,y,z, alpha, beta, gamma):
14
+ """
15
+ Calls get_mat() to get the 4x4 matrix
16
+ """
17
+ try:
18
+ euler = np.array([alpha, beta, gamma]) / 180.0 * np.pi
19
+ quat = np.array(euler2quat(euler[0],euler[1],euler[2]))
20
+ pose = pos_quat_to_pose_4x4(np.array([x,y,z]), quat)
21
+ return pose
22
+ except Exception as e:
23
+ print(str(e))
24
+ pass
25
+
26
+ def pos_quat_to_pose_4x4(pos, quat):
27
+ """pose = pos_quat_to_pose_4x4(pos, quat)
28
+ Convert pos and quat into pose, 4x4 format
29
+
30
+ Args:
31
+ pos: length-3 position
32
+ quat: length-4 quaternion
33
+
34
+ Returns:
35
+ pose: numpy array, 4x4
36
+ """
37
+ pose = np.zeros([4, 4])
38
+ mat = quat2mat(quat)
39
+ pose[0:3, 0:3] = mat[:, :]
40
+ pose[0:3, -1] = pos[:]
41
+ pose[-1, -1] = 1
42
+ return pose
43
+
44
+
45
+ def pose_4x4_to_pos_quat(pose):
46
+ """
47
+ Convert pose, 4x4 format into pos and quat
48
+
49
+ Args:
50
+ pose: numpy array, 4x4
51
+ Returns:
52
+ pos: length-3 position
53
+ quat: length-4 quaternion
54
+
55
+ """
56
+ mat = pose[:3, :3]
57
+ quat = mat2quat(mat)
58
+ pos = np.zeros([3])
59
+ pos[0] = pose[0, 3]
60
+ pos[1] = pose[1, 3]
61
+ pos[2] = pose[2, 3]
62
+ return pos, quat
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/utils.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import open3d as o3d
3
+ import numpy as np
4
+ from PIL import Image
5
+ from transforms3d.euler import euler2mat
6
+
7
+ from .rotation import batch_viewpoint_params_to_matrix
8
+ from .xmlhandler import xmlReader
9
+
10
+ class CameraInfo():
11
+ ''' Author: chenxi-wang
12
+ Camera intrinsics for point cloud generation.
13
+ '''
14
+ def __init__(self, width, height, fx, fy, cx, cy, scale):
15
+ self.width = width
16
+ self.height = height
17
+ self.fx = fx
18
+ self.fy = fy
19
+ self.cx = cx
20
+ self.cy = cy
21
+ self.scale = scale
22
+
23
+ def get_camera_intrinsic(camera):
24
+ '''
25
+ **Input:**
26
+
27
+ - camera: string of type of camera, "realsense" or "kinect".
28
+
29
+ **Output:**
30
+
31
+ - numpy array of shape (3, 3) of the camera intrinsic matrix.
32
+ '''
33
+ param = o3d.camera.PinholeCameraParameters()
34
+ if camera == 'kinect':
35
+ param.intrinsic.set_intrinsics(1280,720,631.55,631.21,638.43,366.50)
36
+ elif camera == 'realsense':
37
+ param.intrinsic.set_intrinsics(1280,720,927.17,927.37,651.32,349.62)
38
+ intrinsic = param.intrinsic.intrinsic_matrix
39
+ return intrinsic
40
+
41
+ def create_point_cloud_from_depth_image(depth, camera, organized=True):
42
+ assert(depth.shape[0] == camera.height and depth.shape[1] == camera.width)
43
+ xmap = np.arange(camera.width)
44
+ ymap = np.arange(camera.height)
45
+ xmap, ymap = np.meshgrid(xmap, ymap)
46
+ points_z = depth / camera.scale
47
+ points_x = (xmap - camera.cx) * points_z / camera.fx
48
+ points_y = (ymap - camera.cy) * points_z / camera.fy
49
+ cloud = np.stack([points_x, points_y, points_z], axis=-1)
50
+ if not organized:
51
+ cloud = cloud.reshape([-1, 3])
52
+ return cloud
53
+
54
+ def generate_views(N, phi=(np.sqrt(5)-1)/2, center=np.zeros(3, dtype=np.float32), R=1):
55
+ ''' Author: chenxi-wang
56
+ View sampling on a sphere using Febonacci lattices.
57
+
58
+ **Input:**
59
+
60
+ - N: int, number of viewpoints.
61
+
62
+ - phi: float, constant angle to sample views, usually 0.618.
63
+
64
+ - center: numpy array of (3,), sphere center.
65
+
66
+ - R: float, sphere radius.
67
+
68
+ **Output:**
69
+
70
+ - numpy array of (N, 3), coordinates of viewpoints.
71
+ '''
72
+ idxs = np.arange(N, dtype=np.float32)
73
+ Z = (2 * idxs + 1) / N - 1
74
+ X = np.sqrt(1 - Z**2) * np.cos(2 * idxs * np.pi * phi)
75
+ Y = np.sqrt(1 - Z**2) * np.sin(2 * idxs * np.pi * phi)
76
+ views = np.stack([X,Y,Z], axis=1)
77
+ views = R * np.array(views) + center
78
+ return views
79
+
80
+ def generate_scene_model(dataset_root, scene_name, anno_idx, return_poses=False, align=False, camera='realsense'):
81
+ '''
82
+ Author: chenxi-wang
83
+
84
+ **Input:**
85
+
86
+ - dataset_root: str, graspnet dataset root
87
+
88
+ - scene_name: str, name of scene folder, e.g. scene_0000
89
+
90
+ - anno_idx: int, frame index from 0-255
91
+
92
+ - return_poses: bool, return object ids and 6D poses if set to True
93
+
94
+ - align: bool, transform to table coordinates if set to True
95
+
96
+ - camera: str, camera name (realsense or kinect)
97
+
98
+ **Output:**
99
+
100
+ - list of open3d.geometry.PointCloud.
101
+ '''
102
+ if align:
103
+ camera_poses = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'camera_poses.npy'))
104
+ camera_pose = camera_poses[anno_idx]
105
+ align_mat = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'cam0_wrt_table.npy'))
106
+ camera_pose = np.matmul(align_mat,camera_pose)
107
+ print('Scene {}, {}'.format(scene_name, camera))
108
+ scene_reader = xmlReader(os.path.join(dataset_root, 'scenes', scene_name, camera, 'annotations', '%04d.xml'%anno_idx))
109
+ posevectors = scene_reader.getposevectorlist()
110
+ obj_list = []
111
+ mat_list = []
112
+ model_list = []
113
+ pose_list = []
114
+ for posevector in posevectors:
115
+ obj_idx, pose = parse_posevector(posevector)
116
+ obj_list.append(obj_idx)
117
+ mat_list.append(pose)
118
+
119
+ for obj_idx, pose in zip(obj_list, mat_list):
120
+ plyfile = os.path.join(dataset_root, 'models', '%03d'%obj_idx, 'nontextured.ply')
121
+ model = o3d.io.read_point_cloud(plyfile)
122
+ points = np.array(model.points)
123
+ if align:
124
+ pose = np.dot(camera_pose, pose)
125
+ points = transform_points(points, pose)
126
+ model.points = o3d.utility.Vector3dVector(points)
127
+ model_list.append(model)
128
+ pose_list.append(pose)
129
+
130
+ if return_poses:
131
+ return model_list, obj_list, pose_list
132
+ else:
133
+ return model_list
134
+
135
+ def generate_scene_pointcloud(dataset_root, scene_name, anno_idx, align=False, camera='kinect'):
136
+ '''
137
+ Author: chenxi-wang
138
+
139
+ **Input:**
140
+
141
+ - dataset_root: str, graspnet dataset root
142
+
143
+ - scene_name: str, name of scene folder, e.g. scene_0000
144
+
145
+ - anno_idx: int, frame index from 0-255
146
+
147
+ - align: bool, transform to table coordinates if set to True
148
+
149
+ - camera: str, camera name (realsense or kinect)
150
+
151
+ **Output:**
152
+
153
+ - open3d.geometry.PointCloud.
154
+ '''
155
+ colors = np.array(Image.open(os.path.join(dataset_root, 'scenes', scene_name, camera, 'rgb', '%04d.png'%anno_idx)), dtype=np.float32) / 255.0
156
+ depths = np.array(Image.open(os.path.join(dataset_root, 'scenes', scene_name, camera, 'depth', '%04d.png'%anno_idx)))
157
+ intrinsics = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'camK.npy'))
158
+ fx, fy = intrinsics[0,0], intrinsics[1,1]
159
+ cx, cy = intrinsics[0,2], intrinsics[1,2]
160
+ s = 1000.0
161
+
162
+ if align:
163
+ camera_poses = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'camera_poses.npy'))
164
+ camera_pose = camera_poses[anno_idx]
165
+ align_mat = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'cam0_wrt_table.npy'))
166
+ camera_pose = align_mat.dot(camera_pose)
167
+
168
+ xmap, ymap = np.arange(colors.shape[1]), np.arange(colors.shape[0])
169
+ xmap, ymap = np.meshgrid(xmap, ymap)
170
+
171
+ points_z = depths / s
172
+ points_x = (xmap - cx) / fx * points_z
173
+ points_y = (ymap - cy) / fy * points_z
174
+
175
+ mask = (points_z > 0)
176
+ points = np.stack([points_x, points_y, points_z], axis=-1)
177
+ points = points[mask]
178
+ colors = colors[mask]
179
+ if align:
180
+ points = transform_points(points, camera_pose)
181
+
182
+ cloud = o3d.geometry.PointCloud()
183
+ cloud.points = o3d.utility.Vector3dVector(points)
184
+ cloud.colors = o3d.utility.Vector3dVector(colors)
185
+
186
+ return cloud
187
+
188
+ def rotation_matrix(rx, ry, rz):
189
+ '''
190
+ Author: chenxi-wang
191
+
192
+ **Input:**
193
+
194
+ - rx/ry/rz: float, rotation angle along x/y/z-axis
195
+
196
+ **Output:**
197
+
198
+ - numpy array of (3, 3), rotation matrix.
199
+ '''
200
+ Rx = np.array([[1, 0, 0],
201
+ [0, np.cos(rx), -np.sin(rx)],
202
+ [0, np.sin(rx), np.cos(rx)]])
203
+ Ry = np.array([[ np.cos(ry), 0, np.sin(ry)],
204
+ [ 0, 1, 0],
205
+ [-np.sin(ry), 0, np.cos(ry)]])
206
+ Rz = np.array([[np.cos(rz), -np.sin(rz), 0],
207
+ [np.sin(rz), np.cos(rz), 0],
208
+ [ 0, 0, 1]])
209
+ R = Rz.dot(Ry).dot(Rx)
210
+ return R
211
+
212
+ def transform_matrix(tx, ty, tz, rx, ry, rz):
213
+ '''
214
+ Author: chenxi-wang
215
+
216
+ **Input:**
217
+
218
+ - tx/ty/tz: float, translation along x/y/z-axis
219
+
220
+ - rx/ry/rz: float, rotation angle along x/y/z-axis
221
+
222
+ **Output:**
223
+
224
+ - numpy array of (4, 4), transformation matrix.
225
+ '''
226
+ trans = np.eye(4)
227
+ trans[:3,3] = np.array([tx, ty, tz])
228
+ rot_x = np.array([[1, 0, 0],
229
+ [0, np.cos(rx), -np.sin(rx)],
230
+ [0, np.sin(rx), np.cos(rx)]])
231
+ rot_y = np.array([[ np.cos(ry), 0, np.sin(ry)],
232
+ [ 0, 1, 0],
233
+ [-np.sin(ry), 0, np.cos(ry)]])
234
+ rot_z = np.array([[np.cos(rz), -np.sin(rz), 0],
235
+ [np.sin(rz), np.cos(rz), 0],
236
+ [ 0, 0, 1]])
237
+ trans[:3,:3] = rot_x.dot(rot_y).dot(rot_z)
238
+ return trans
239
+
240
+ def matrix_to_dexnet_params(matrix):
241
+ '''
242
+ Author: chenxi-wang
243
+
244
+ **Input:**
245
+
246
+ - numpy array of shape (3, 3) of the rotation matrix.
247
+
248
+ **Output:**
249
+
250
+ - binormal: numpy array of shape (3,).
251
+
252
+ - angle: float of the angle.
253
+ '''
254
+ approach = matrix[:, 0]
255
+ binormal = matrix[:, 1]
256
+ axis_y = binormal
257
+ axis_x = np.array([axis_y[1], -axis_y[0], 0])
258
+ if np.linalg.norm(axis_x) == 0:
259
+ axis_x = np.array([1, 0, 0])
260
+ axis_x = axis_x / np.linalg.norm(axis_x)
261
+ axis_y = axis_y / np.linalg.norm(axis_y)
262
+ axis_z = np.cross(axis_x, axis_y)
263
+ R = np.c_[axis_x, np.c_[axis_y, axis_z]]
264
+ approach = R.T.dot(approach)
265
+ cos_t, sin_t = approach[0], -approach[2]
266
+ angle = np.arccos(cos_t)
267
+ if sin_t < 0:
268
+ angle = np.pi * 2 - angle
269
+ return binormal, angle
270
+
271
+ def viewpoint_params_to_matrix(towards, angle):
272
+ '''
273
+ Author: chenxi-wang
274
+
275
+ **Input:**
276
+
277
+ - towards: numpy array towards vector with shape (3,).
278
+
279
+ - angle: float of in-plane rotation.
280
+
281
+ **Output:**
282
+
283
+ - numpy array of the rotation matrix with shape (3, 3).
284
+ '''
285
+ axis_x = towards
286
+ axis_y = np.array([-axis_x[1], axis_x[0], 0])
287
+ if np.linalg.norm(axis_y) == 0:
288
+ axis_y = np.array([0, 1, 0])
289
+ axis_x = axis_x / np.linalg.norm(axis_x)
290
+ axis_y = axis_y / np.linalg.norm(axis_y)
291
+ axis_z = np.cross(axis_x, axis_y)
292
+ R1 = np.array([[1, 0, 0],
293
+ [0, np.cos(angle), -np.sin(angle)],
294
+ [0, np.sin(angle), np.cos(angle)]])
295
+ R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
296
+ matrix = R2.dot(R1)
297
+ return matrix
298
+
299
+ def dexnet_params_to_matrix(binormal, angle):
300
+ '''
301
+ Author: chenxi-wang
302
+
303
+ **Input:**
304
+
305
+ - binormal: numpy array of shape (3,).
306
+
307
+ - angle: float of the angle.
308
+
309
+ **Output:**
310
+
311
+ - numpy array of shape (3, 3) of the rotation matrix.
312
+ '''
313
+ axis_y = binormal
314
+ axis_x = np.array([axis_y[1], -axis_y[0], 0])
315
+ if np.linalg.norm(axis_x) == 0:
316
+ axis_x = np.array([1, 0, 0])
317
+ axis_x = axis_x / np.linalg.norm(axis_x)
318
+ axis_y = axis_y / np.linalg.norm(axis_y)
319
+ axis_z = np.cross(axis_x, axis_y)
320
+ R1 = np.array([[np.cos(angle), 0, np.sin(angle)],
321
+ [0, 1, 0],
322
+ [-np.sin(angle), 0, np.cos(angle)]])
323
+ R2 = np.c_[axis_x, np.c_[axis_y, axis_z]]
324
+ matrix = R2.dot(R1)
325
+ return matrix
326
+
327
+ def transform_points(points, trans):
328
+ '''
329
+ Author: chenxi-wang
330
+
331
+ **Input:**
332
+
333
+ - points: numpy array of (N,3), point cloud
334
+
335
+ - trans: numpy array of (4,4), transformation matrix
336
+
337
+ **Output:**
338
+
339
+ - numpy array of (N,3), transformed points.
340
+ '''
341
+ ones = np.ones([points.shape[0],1], dtype=points.dtype)
342
+ points_ = np.concatenate([points, ones], axis=-1)
343
+ points_ = np.matmul(trans, points_.T).T
344
+ return points_[:,:3]
345
+
346
+ def get_model_grasps(datapath):
347
+ ''' Author: chenxi-wang
348
+ Load grasp labels from .npz files.
349
+ '''
350
+ label = np.load(datapath)
351
+ points = label['points']
352
+ offsets = label['offsets']
353
+ scores = label['scores']
354
+ collision = label['collision']
355
+ return points, offsets, scores, collision
356
+
357
+ def parse_posevector(posevector):
358
+ ''' Author: chenxi-wang
359
+ Decode posevector to object id and transformation matrix.
360
+ '''
361
+ mat = np.zeros([4,4],dtype=np.float32)
362
+ alpha, beta, gamma = posevector[4:7]
363
+ alpha = alpha / 180.0 * np.pi
364
+ beta = beta / 180.0 * np.pi
365
+ gamma = gamma / 180.0 * np.pi
366
+ mat[:3,:3] = euler2mat(alpha, beta, gamma)
367
+ mat[:3,3] = posevector[1:4]
368
+ mat[3,3] = 1
369
+ obj_idx = int(posevector[0])
370
+ return obj_idx, mat
371
+
372
+ def create_mesh_box(width, height, depth, dx=0, dy=0, dz=0):
373
+ ''' Author: chenxi-wang
374
+ Create box instance with mesh representation.
375
+ '''
376
+ box = o3d.geometry.TriangleMesh()
377
+ vertices = np.array([[0,0,0],
378
+ [width,0,0],
379
+ [0,0,depth],
380
+ [width,0,depth],
381
+ [0,height,0],
382
+ [width,height,0],
383
+ [0,height,depth],
384
+ [width,height,depth]])
385
+ vertices[:,0] += dx
386
+ vertices[:,1] += dy
387
+ vertices[:,2] += dz
388
+ triangles = np.array([[4,7,5],[4,6,7],[0,2,4],[2,6,4],
389
+ [0,1,2],[1,3,2],[1,5,7],[1,7,3],
390
+ [2,3,7],[2,7,6],[0,4,1],[1,4,5]])
391
+ box.vertices = o3d.utility.Vector3dVector(vertices)
392
+ box.triangles = o3d.utility.Vector3iVector(triangles)
393
+ return box
394
+
395
+ def create_table_cloud(width, height, depth, dx=0, dy=0, dz=0, grid_size=0.01):
396
+ '''
397
+ Author: chenxi-wang
398
+
399
+ **Input:**
400
+
401
+ - width/height/depth: float, table width/height/depth along x/z/y-axis in meters
402
+
403
+ - dx/dy/dz: float, offset along x/y/z-axis in meters
404
+
405
+ - grid_size: float, point distance along x/y/z-axis in meters
406
+
407
+ **Output:**
408
+
409
+ - open3d.geometry.PointCloud
410
+ '''
411
+ xmap = np.linspace(0, width, int(width/grid_size))
412
+ ymap = np.linspace(0, depth, int(depth/grid_size))
413
+ zmap = np.linspace(0, height, int(height/grid_size))
414
+ xmap, ymap, zmap = np.meshgrid(xmap, ymap, zmap, indexing='xy')
415
+ xmap += dx
416
+ ymap += dy
417
+ zmap += dz
418
+ points = np.stack([xmap, ymap, zmap], axis=-1)
419
+ points = points.reshape([-1, 3])
420
+ cloud = o3d.geometry.PointCloud()
421
+ cloud.points = o3d.utility.Vector3dVector(points)
422
+ return cloud
423
+
424
+ def create_axis(length,grid_size = 0.01):
425
+ num = int(length / grid_size)
426
+ xmap = np.linspace(0,length,num)
427
+ ymap = np.linspace(0,2*length,num)
428
+ zmap = np.linspace(0,3*length,num)
429
+ x_p = np.vstack([xmap.T,np.zeros((1,num)),np.zeros((1,num))])
430
+ y_p = np.vstack([np.zeros((1,num)),ymap.T,np.zeros((1,num))])
431
+ z_p = np.vstack([np.zeros((1,num)),np.zeros((1,num)),zmap.T])
432
+ p = np.hstack([x_p,y_p,z_p])
433
+ # print('p',p.shape)
434
+ cloud = o3d.geometry.PointCloud()
435
+ cloud.points = o3d.utility.Vector3dVector(p.T)
436
+ return cloud
437
+
438
+ def plot_axis(R,center,length,grid_size = 0.01):
439
+ num = int(length / grid_size)
440
+ xmap = np.linspace(0,length,num)
441
+ ymap = np.linspace(0,2*length,num)
442
+ zmap = np.linspace(0,3*length,num)
443
+ x_p = np.vstack([xmap.T,np.zeros((1,num)),np.zeros((1,num))])
444
+ y_p = np.vstack([np.zeros((1,num)),ymap.T,np.zeros((1,num))])
445
+ z_p = np.vstack([np.zeros((1,num)),np.zeros((1,num)),zmap.T])
446
+ p = np.hstack([x_p,y_p,z_p])
447
+ # print('p',p.shape)
448
+ p = np.dot(R, p).T + center
449
+ cloud = o3d.geometry.PointCloud()
450
+ cloud.points = o3d.utility.Vector3dVector(p)
451
+ return cloud
452
+
453
+ def plot_gripper_pro_max(center, R, width, depth, score=1, color=None):
454
+ '''
455
+ Author: chenxi-wang
456
+
457
+ **Input:**
458
+
459
+ - center: numpy array of (3,), target point as gripper center
460
+
461
+ - R: numpy array of (3,3), rotation matrix of gripper
462
+
463
+ - width: float, gripper width
464
+
465
+ - score: float, grasp quality score
466
+
467
+ **Output:**
468
+
469
+ - open3d.geometry.TriangleMesh
470
+ '''
471
+ x, y, z = center
472
+ height=0.004
473
+ finger_width = 0.004
474
+ tail_length = 0.04
475
+ depth_base = 0.02
476
+
477
+ if color is not None:
478
+ color_r, color_g, color_b = color
479
+ else:
480
+ color_r = score # red for high score
481
+ color_g = 0
482
+ color_b = 1 - score # blue for low score
483
+
484
+ left = create_mesh_box(depth+depth_base+finger_width, finger_width, height)
485
+ right = create_mesh_box(depth+depth_base+finger_width, finger_width, height)
486
+ bottom = create_mesh_box(finger_width, width, height)
487
+ tail = create_mesh_box(tail_length, finger_width, height)
488
+
489
+ left_points = np.array(left.vertices)
490
+ left_triangles = np.array(left.triangles)
491
+ left_points[:,0] -= depth_base + finger_width
492
+ left_points[:,1] -= width/2 + finger_width
493
+ left_points[:,2] -= height/2
494
+
495
+ right_points = np.array(right.vertices)
496
+ right_triangles = np.array(right.triangles) + 8
497
+ right_points[:,0] -= depth_base + finger_width
498
+ right_points[:,1] += width/2
499
+ right_points[:,2] -= height/2
500
+
501
+ bottom_points = np.array(bottom.vertices)
502
+ bottom_triangles = np.array(bottom.triangles) + 16
503
+ bottom_points[:,0] -= finger_width + depth_base
504
+ bottom_points[:,1] -= width/2
505
+ bottom_points[:,2] -= height/2
506
+
507
+ tail_points = np.array(tail.vertices)
508
+ tail_triangles = np.array(tail.triangles) + 24
509
+ tail_points[:,0] -= tail_length + finger_width + depth_base
510
+ tail_points[:,1] -= finger_width / 2
511
+ tail_points[:,2] -= height/2
512
+
513
+ vertices = np.concatenate([left_points, right_points, bottom_points, tail_points], axis=0)
514
+ vertices = np.dot(R, vertices.T).T + center
515
+ triangles = np.concatenate([left_triangles, right_triangles, bottom_triangles, tail_triangles], axis=0)
516
+ colors = np.array([ [color_r,color_g,color_b] for _ in range(len(vertices))])
517
+
518
+ gripper = o3d.geometry.TriangleMesh()
519
+ gripper.vertices = o3d.utility.Vector3dVector(vertices)
520
+ gripper.triangles = o3d.utility.Vector3iVector(triangles)
521
+ gripper.vertex_colors = o3d.utility.Vector3dVector(colors)
522
+ return gripper
523
+
524
+
525
+ def find_scene_by_model_id(dataset_root, model_id_list):
526
+ picked_scene_names = []
527
+ scene_names = ['scene_'+str(i).zfill(4) for i in range(190)]
528
+ for scene_name in scene_names:
529
+ try:
530
+ scene_reader = xmlReader(os.path.join(dataset_root, 'scenes', scene_name, 'kinect', 'annotations', '0000.xml'))
531
+ except:
532
+ continue
533
+ posevectors = scene_reader.getposevectorlist()
534
+ for posevector in posevectors:
535
+ obj_idx, _ = parse_posevector(posevector)
536
+ if obj_idx in model_id_list:
537
+ picked_scene_names.append(scene_name)
538
+ print(obj_idx, scene_name)
539
+ break
540
+ return picked_scene_names
541
+
542
+ def generate_scene(scene_idx, anno_idx, return_poses=False, align=False, camera='realsense'):
543
+ camera_poses = np.load(os.path.join('scenes','scene_%04d' %(scene_idx,),camera, 'camera_poses.npy'))
544
+ camera_pose = camera_poses[anno_idx]
545
+ if align:
546
+ align_mat = np.load(os.path.join('camera_poses', '{}_alignment.npy'.format(camera)))
547
+ camera_pose = align_mat.dot(camera_pose)
548
+ camera_split = 'data' if camera == 'realsense' else 'data_kinect'
549
+ # print('Scene {}, {}'.format(scene_idx, camera_split))
550
+ scene_reader = xmlReader(os.path.join(scenedir % (scene_idx, camera), 'annotations', '%04d.xml'%(anno_idx)))
551
+ posevectors = scene_reader.getposevectorlist()
552
+ obj_list = []
553
+ mat_list = []
554
+ model_list = []
555
+ pose_list = []
556
+ for posevector in posevectors:
557
+ obj_idx, mat = parse_posevector(posevector)
558
+ obj_list.append(obj_idx)
559
+ mat_list.append(mat)
560
+
561
+ for obj_idx, mat in zip(obj_list, mat_list):
562
+ model = o3d.io.read_point_cloud(os.path.join(modeldir, '%03d'%obj_idx, 'nontextured.ply'))
563
+ points = np.array(model.points)
564
+ pose = np.dot(camera_pose, mat)
565
+ points = transform_points(points, pose)
566
+ model.points = o3d.utility.Vector3dVector(points)
567
+ model_list.append(model)
568
+ pose_list.append(pose)
569
+
570
+ if return_poses:
571
+ return model_list, obj_list, pose_list
572
+ else:
573
+ return model_list
574
+
575
+ def get_obj_pose_list(camera_pose, pose_vectors):
576
+ import numpy as np
577
+ obj_list = []
578
+ mat_list = []
579
+ pose_list = []
580
+ for posevector in pose_vectors:
581
+ obj_idx, mat = parse_posevector(posevector)
582
+ obj_list.append(obj_idx)
583
+ mat_list.append(mat)
584
+
585
+ for obj_idx, mat in zip(obj_list, mat_list):
586
+ pose = np.dot(camera_pose, mat)
587
+ pose_list.append(pose)
588
+
589
+ return obj_list, pose_list
590
+
591
+ def batch_rgbdxyz_2_rgbxy_depth(points, camera):
592
+ '''
593
+ **Input:**
594
+
595
+ - points: np.array(-1,3) of the points in camera frame
596
+
597
+ - camera: string of the camera type
598
+
599
+ **Output:**
600
+
601
+ - coords: float of xy in pixel frame [-1, 2]
602
+
603
+ - depths: float of the depths of pixel frame [-1]
604
+ '''
605
+ intrinsics = get_camera_intrinsic(camera)
606
+ fx, fy = intrinsics[0,0], intrinsics[1,1]
607
+ cx, cy = intrinsics[0,2], intrinsics[1,2]
608
+ s = 1000.0
609
+ depths = s * points[:,2] # point_z
610
+ ###################################
611
+ # x and y should be inverted here #
612
+ ###################################
613
+ # y = point[0] / point[2] * fx + cx
614
+ # x = point[1] / point[2] * fy + cy
615
+ # cx = 640, cy = 360
616
+ coords_x = points[:,0] / points[:,2] * fx + cx
617
+ coords_y = points[:,1] / points[:,2] * fy + cy
618
+ coords = np.stack([coords_x, coords_y], axis=-1)
619
+ return coords, depths
620
+
621
+ def get_batch_key_points(centers, Rs, widths):
622
+ '''
623
+ **Input:**
624
+
625
+ - centers: np.array(-1,3) of the translation
626
+
627
+ - Rs: np.array(-1,3,3) of the rotation matrix
628
+
629
+ - widths: np.array(-1) of the grasp width
630
+
631
+ **Output:**
632
+
633
+ - key_points: np.array(-1,4,3) of the key point of the grasp
634
+ '''
635
+ import numpy as np
636
+ depth_base = 0.02
637
+ height = 0.02
638
+ key_points = np.zeros((centers.shape[0],4,3),dtype = np.float32)
639
+ key_points[:,:,0] -= depth_base
640
+ key_points[:,1:,1] -= widths[:,np.newaxis] / 2
641
+ key_points[:,2,2] += height / 2
642
+ key_points[:,3,2] -= height / 2
643
+ key_points = np.matmul(Rs, key_points.transpose(0,2,1)).transpose(0,2,1)
644
+ key_points = key_points + centers[:,np.newaxis,:]
645
+ return key_points
646
+
647
+ def batch_key_points_2_tuple(key_points, scores, object_ids, camera):
648
+ '''
649
+ **Input:**
650
+
651
+ - key_points: np.array(-1,4,3) of grasp key points, definition is shown in key_points.png
652
+
653
+ - scores: numpy array of batch grasp scores.
654
+
655
+ - camera: string of 'realsense' or 'kinect'.
656
+
657
+ **Output:**
658
+
659
+ - np.array([center_x,center_y,open_x,open_y,height])
660
+ '''
661
+ import numpy as np
662
+ centers, _ = batch_rgbdxyz_2_rgbxy_depth(key_points[:,0,:], camera)
663
+ opens, _ = batch_rgbdxyz_2_rgbxy_depth(key_points[:,1,:], camera)
664
+ lefts, _ = batch_rgbdxyz_2_rgbxy_depth(key_points[:,2,:], camera)
665
+ rights, _ = batch_rgbdxyz_2_rgbxy_depth(key_points[:,3,:], camera)
666
+ heights = np.linalg.norm(lefts - rights, axis=-1, keepdims=True)
667
+ tuples = np.concatenate([centers, opens, heights, scores[:, np.newaxis], object_ids[:, np.newaxis]], axis=-1).astype(np.float32)
668
+ return tuples
669
+
670
+ def framexy_depth_2_xyz(pixel_x, pixel_y, depth, camera):
671
+ '''
672
+ **Input:**
673
+
674
+ - pixel_x: int of the pixel x coordinate.
675
+
676
+ - pixel_y: int of the pixle y coordicate.
677
+
678
+ - depth: float of depth. The unit is millimeter.
679
+
680
+ - camera: string of type of camera. "realsense" or "kinect".
681
+
682
+ **Output:**
683
+
684
+ - x, y, z: float of x, y and z coordinates in camera frame. The unit is millimeter.
685
+ '''
686
+ intrinsics = get_camera_intrinsic(camera)
687
+ fx, fy = intrinsics[0,0], intrinsics[1,1]
688
+ cx, cy = intrinsics[0,2], intrinsics[1,2]
689
+ z = depth # mm
690
+ x = z / fx * (pixel_x - cx) # mm
691
+ y = z / fy * (pixel_y - cy) # mm
692
+ return x, y, z
693
+
694
+ def batch_framexy_depth_2_xyz(pixel_x, pixel_y, depth, camera):
695
+ '''
696
+ **Input:**
697
+
698
+ - pixel_x: numpy array of int of the pixel x coordinate. shape: (-1,)
699
+
700
+ - pixel_y: numpy array of int of the pixle y coordicate. shape: (-1,)
701
+
702
+ - depth: numpy array of float of depth. The unit is millimeter. shape: (-1,)
703
+
704
+ - camera: string of type of camera. "realsense" or "kinect".
705
+
706
+ **Output:**
707
+
708
+ x, y, z: numpy array of float of x, y and z coordinates in camera frame. The unit is millimeter.
709
+ '''
710
+ intrinsics = get_camera_intrinsic(camera)
711
+ fx, fy = intrinsics[0,0], intrinsics[1,1]
712
+ cx, cy = intrinsics[0,2], intrinsics[1,2]
713
+ z = depth # mm
714
+ x = z / fx * (pixel_x - cx) # mm
715
+ y = z / fy * (pixel_y - cy) # mm
716
+ return x, y, z
717
+
718
+ def center_depth(depths, center, open_point, upper_point):
719
+ '''
720
+ **Input:**
721
+
722
+ - depths: numpy array of the depths.
723
+
724
+ - center: numpy array of the center point.
725
+
726
+ - open_point: numpy array of the open point.
727
+
728
+ - upper_point: numpy array of the upper point.
729
+
730
+ **Output:**
731
+
732
+ - depth: float of the grasp depth.
733
+ '''
734
+ return depths[int(round(center[1])), int(round(center[0]))]
735
+
736
+ def batch_center_depth(depths, centers, open_points, upper_points):
737
+ '''
738
+ **Input:**
739
+
740
+ - depths: numpy array of the depths.
741
+
742
+ - centers: numpy array of the center points of shape(-1, 2).
743
+
744
+ - open_points: numpy array of the open points of shape(-1, 2).
745
+
746
+ - upper_points: numpy array of the upper points of shape(-1, 2).
747
+
748
+ **Output:**
749
+
750
+ - depths: numpy array of the grasp depth of shape (-1).
751
+ '''
752
+ x = np.round(centers[:,0]).astype(np.int32)
753
+ y = np.round(centers[:,1]).astype(np.int32)
754
+ return depths[y, x]
755
+
756
+ def key_point_2_rotation(center_xyz, open_point_xyz, upper_point_xyz):
757
+ '''
758
+ **Input:**
759
+
760
+ - center_xyz: numpy array of the center point.
761
+
762
+ - open_point_xyz: numpy array of the open point.
763
+
764
+ - upper_point_xyz: numpy array of the upper point.
765
+
766
+ **Output:**
767
+
768
+ - rotation: numpy array of the rotation matrix.
769
+ '''
770
+ open_point_vector = open_point_xyz - center_xyz
771
+ upper_point_vector = upper_point_xyz - center_xyz
772
+ unit_open_point_vector = open_point_vector / np.linalg.norm(open_point_vector)
773
+ unit_upper_point_vector = upper_point_vector / np.linalg.norm(upper_point_vector)
774
+ rotation = np.hstack((
775
+ np.array([[0],[0],[1.0]]),
776
+ unit_open_point_vector.reshape((-1, 1)),
777
+ unit_upper_point_vector.reshape((-1, 1))
778
+ ))
779
+ return rotation
780
+
781
+ def batch_key_point_2_rotation(centers_xyz, open_points_xyz, upper_points_xyz):
782
+ '''
783
+ **Input:**
784
+
785
+ - centers_xyz: numpy array of the center points of shape (-1, 3).
786
+
787
+ - open_points_xyz: numpy array of the open points of shape (-1, 3).
788
+
789
+ - upper_points_xyz: numpy array of the upper points of shape (-1, 3).
790
+
791
+ **Output:**
792
+
793
+ - rotations: numpy array of the rotation matrix of shape (-1, 3, 3).
794
+ '''
795
+ # print('open_points_xyz:{}'.format(open_points_xyz))
796
+ # print('upper_points_xyz:{}'.format(upper_points_xyz))
797
+ open_points_vector = open_points_xyz - centers_xyz # (-1, 3)
798
+ upper_points_vector = upper_points_xyz - centers_xyz # (-1, 3)
799
+ open_point_norm = np.linalg.norm(open_points_vector, axis = 1).reshape(-1, 1)
800
+ upper_point_norm = np.linalg.norm(upper_points_vector, axis = 1).reshape(-1, 1)
801
+ # print('open_point_norm:{}, upper_point_norm:{}'.format(open_point_norm, upper_point_norm))
802
+ unit_open_points_vector = open_points_vector / np.hstack((open_point_norm, open_point_norm, open_point_norm)) # (-1, 3)
803
+ unit_upper_points_vector = upper_points_vector / np.hstack((upper_point_norm, upper_point_norm, upper_point_norm)) # (-1, 3)
804
+ num = open_points_vector.shape[0]
805
+ x_axis = np.hstack((np.zeros((num, 1)), np.zeros((num, 1)), np.ones((num, 1)))).astype(np.float32).reshape(-1, 3, 1)
806
+ rotations = np.dstack((x_axis, unit_open_points_vector.reshape((-1, 3, 1)), unit_upper_points_vector.reshape((-1, 3, 1))))
807
+ return rotations
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/vis.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import numpy as np
4
+ import open3d as o3d
5
+ from transforms3d.euler import euler2mat, quat2mat
6
+ from .utils import generate_scene_model, generate_scene_pointcloud, generate_views, get_model_grasps, plot_gripper_pro_max, transform_points
7
+ from .rotation import viewpoint_params_to_matrix, batch_viewpoint_params_to_matrix
8
+
9
+ def create_table_cloud(width, height, depth, dx=0, dy=0, dz=0, grid_size=0.01):
10
+ '''
11
+ Author: chenxi-wang
12
+
13
+ **Input:**
14
+
15
+ - width/height/depth: float, table width/height/depth along x/z/y-axis in meters
16
+
17
+ - dx/dy/dz: float, offset along x/y/z-axis in meters
18
+
19
+ - grid_size: float, point distance along x/y/z-axis in meters
20
+
21
+ **Output:**
22
+
23
+ - open3d.geometry.PointCloud
24
+ '''
25
+ xmap = np.linspace(0, width, int(width/grid_size))
26
+ ymap = np.linspace(0, depth, int(depth/grid_size))
27
+ zmap = np.linspace(0, height, int(height/grid_size))
28
+ xmap, ymap, zmap = np.meshgrid(xmap, ymap, zmap, indexing='xy')
29
+ xmap += dx
30
+ ymap += dy
31
+ zmap += dz
32
+ points = np.stack([xmap, -ymap, -zmap], axis=-1)
33
+ points = points.reshape([-1, 3])
34
+ cloud = o3d.geometry.PointCloud()
35
+ cloud.points = o3d.utility.Vector3dVector(points)
36
+ return cloud
37
+
38
+
39
+ def get_camera_parameters(camera='kinect'):
40
+ '''
41
+ author: Minghao Gou
42
+
43
+ **Input:**
44
+
45
+ - camera: string of type of camera: 'kinect' or 'realsense'
46
+
47
+ **Output:**
48
+
49
+ - open3d.camera.PinholeCameraParameters
50
+ '''
51
+ import open3d as o3d
52
+ param = o3d.camera.PinholeCameraParameters()
53
+ param.extrinsic = np.eye(4,dtype=np.float64)
54
+ # param.intrinsic = o3d.camera.PinholeCameraIntrinsic()
55
+ if camera == 'kinect':
56
+ param.intrinsic.set_intrinsics(1280,720,631.5,631.2,639.5,359.5)
57
+ elif camera == 'realsense':
58
+ param.intrinsic.set_intrinsics(1280,720,927.17,927.37,639.5,359.5)
59
+ return param
60
+
61
+ def visAnno(dataset_root, scene_name, anno_idx, camera, num_grasp=10, th=0.3, align_to_table=True, max_width=0.08, save_folder='save_fig', show=False, per_obj=False):
62
+ '''
63
+ Author: chenxi-wang
64
+
65
+ **Input:**
66
+
67
+ - dataset_root: str, graspnet dataset root
68
+
69
+ - scene_name: str, name of scene folder, e.g. scene_0000
70
+
71
+ - anno_idx: int, frame index from 0-255
72
+
73
+ - camera: str, camera name (realsense or kinect)
74
+
75
+ - num_grasp: int, number of sampled grasps
76
+
77
+ - th: float, threshold of friction coefficient
78
+
79
+ - align_to_table: bool, transform to table coordinates if set to True
80
+
81
+ - max_width: float, only visualize grasps with width<=max_width
82
+
83
+ - save_folder: str, folder to save screen captures
84
+
85
+ - show: bool, show visualization in open3d window if set to True
86
+
87
+ - per_obj: bool, show grasps on each object
88
+ '''
89
+ model_list, obj_list, pose_list = generate_scene_model(dataset_root, scene_name, anno_idx, return_poses=True, align=align_to_table, camera=camera)
90
+ point_cloud = generate_scene_pointcloud(dataset_root, scene_name, anno_idx, align=align_to_table, camera=camera)
91
+
92
+ table = create_table_cloud(1.0, 0.02, 1.0, dx=-0.5, dy=-0.5, dz=0, grid_size=0.01)
93
+ num_views, num_angles, num_depths = 300, 12, 4
94
+ views = generate_views(num_views)
95
+ collision_label = np.load('{}/collision_label/{}/collision_labels.npz'.format(dataset_root,scene_name))
96
+
97
+ vis = o3d.visualization.Visualizer()
98
+ vis.create_window(width = 1280, height = 720)
99
+ ctr = vis.get_view_control()
100
+ param = get_camera_parameters(camera=camera)
101
+
102
+ if align_to_table:
103
+ cam_pos = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'cam0_wrt_table.npy'))
104
+ param.extrinsic = np.linalg.inv(cam_pos).tolist()
105
+
106
+ grippers = []
107
+ vis.add_geometry(point_cloud)
108
+ for i, (obj_idx, trans) in enumerate(zip(obj_list, pose_list)):
109
+ sampled_points, offsets, scores, _ = get_model_grasps('%s/grasp_label/%03d_labels.npz'%(dataset_root, obj_idx))
110
+ collision = collision_label['arr_{}'.format(i)]
111
+
112
+ cnt = 0
113
+ point_inds = np.arange(sampled_points.shape[0])
114
+ np.random.shuffle(point_inds)
115
+
116
+ for point_ind in point_inds:
117
+ target_point = sampled_points[point_ind]
118
+ offset = offsets[point_ind]
119
+ score = scores[point_ind]
120
+ view_inds = np.arange(300)
121
+ np.random.shuffle(view_inds)
122
+ flag = False
123
+ for v in view_inds:
124
+ if flag: break
125
+ view = views[v]
126
+ angle_inds = np.arange(12)
127
+ np.random.shuffle(angle_inds)
128
+ for a in angle_inds:
129
+ if flag: break
130
+ depth_inds = np.arange(4)
131
+ np.random.shuffle(depth_inds)
132
+ for d in depth_inds:
133
+ if flag: break
134
+ angle, depth, width = offset[v, a, d]
135
+ if score[v, a, d] > th or score[v, a, d] < 0:
136
+ continue
137
+ if width > max_width:
138
+ continue
139
+ if collision[point_ind, v, a, d]:
140
+ continue
141
+ R = viewpoint_params_to_matrix(-view, angle)
142
+ t = transform_points(target_point[np.newaxis,:], trans).squeeze()
143
+ R = np.dot(trans[:3,:3], R)
144
+ gripper = plot_gripper_pro_max(t, R, width, depth, 1.1-score[v, a, d])
145
+ grippers.append(gripper)
146
+ flag = True
147
+ if flag:
148
+ cnt += 1
149
+ if cnt == num_grasp:
150
+ break
151
+
152
+ if per_obj:
153
+ for gripper in grippers:
154
+ vis.add_geometry(gripper)
155
+ ctr.convert_from_pinhole_camera_parameters(param)
156
+ vis.poll_events()
157
+ filename = os.path.join(save_folder, '{}_{}_pointcloud_{}.png'.format(scene_name, camera, obj_idx))
158
+ if not os.path.exists(save_folder):
159
+ os.mkdir(save_folder)
160
+ vis.capture_screen_image(filename, do_render=True)
161
+
162
+ for gripper in grippers:
163
+ vis.remove_geometry(gripper)
164
+ grippers = []
165
+
166
+ if not per_obj:
167
+ for gripper in grippers:
168
+ vis.add_geometry(gripper)
169
+ ctr.convert_from_pinhole_camera_parameters(param)
170
+ vis.poll_events()
171
+ filename = os.path.join(save_folder, '{}_{}_pointcloud.png'.format(scene_name, camera))
172
+ if not os.path.exists(save_folder):
173
+ os.mkdir(save_folder)
174
+ vis.capture_screen_image(filename, do_render=True)
175
+ if show:
176
+ o3d.visualization.draw_geometries([point_cloud, *grippers])
177
+
178
+ vis.remove_geometry(point_cloud)
179
+ vis.add_geometry(table)
180
+ for model in model_list:
181
+ vis.add_geometry(model)
182
+ ctr.convert_from_pinhole_camera_parameters(param)
183
+ vis.poll_events()
184
+ filename = os.path.join(save_folder, '{}_{}_model.png'.format(scene_name, camera))
185
+ vis.capture_screen_image(filename, do_render=True)
186
+ if show:
187
+ o3d.visualization.draw_geometries([table, *model_list, *grippers])
188
+
189
+
190
+ def vis6D(dataset_root, scene_name, anno_idx, camera, align_to_table=True, save_folder='save_fig', show=False, per_obj=False):
191
+ '''
192
+ **Input:**
193
+
194
+ - dataset_root: str, graspnet dataset root
195
+
196
+ - scene_name: str, name of scene folder, e.g. scene_0000
197
+
198
+ - anno_idx: int, frame index from 0-255
199
+
200
+ - camera: str, camera name (realsense or kinect)
201
+
202
+ - align_to_table: bool, transform to table coordinates if set to True
203
+
204
+ - save_folder: str, folder to save screen captures
205
+
206
+ - show: bool, show visualization in open3d window if set to True
207
+
208
+ - per_obj: bool, show pose of each object
209
+ '''
210
+ model_list, obj_list, pose_list = generate_scene_model(dataset_root, scene_name, anno_idx, return_poses=True, align=align_to_table, camera=camera)
211
+ point_cloud = generate_scene_pointcloud(dataset_root, scene_name, anno_idx, align=align_to_table, camera=camera)
212
+ point_cloud = point_cloud.voxel_down_sample(voxel_size=0.005)
213
+
214
+ vis = o3d.visualization.Visualizer()
215
+ vis.create_window(width = 1280, height = 720)
216
+ ctr = vis.get_view_control()
217
+ param = get_camera_parameters(camera=camera)
218
+
219
+ if align_to_table:
220
+ cam_pos = np.load(os.path.join(dataset_root, 'scenes', scene_name, camera, 'cam0_wrt_table.npy'))
221
+ param.extrinsic = np.linalg.inv(cam_pos).tolist()
222
+
223
+ vis.add_geometry(point_cloud)
224
+ if per_obj:
225
+ for i,model in zip(obj_list,model_list):
226
+ vis.add_geometry(model)
227
+ ctr.convert_from_pinhole_camera_parameters(param)
228
+ vis.poll_events()
229
+ filename = os.path.join(save_folder, '{}_{}_6d_{}.png'.format(scene_name, camera, i))
230
+ vis.capture_screen_image(filename, do_render=True)
231
+ vis.remove_geometry(model)
232
+ else:
233
+ for model in model_list:
234
+ vis.add_geometry(model)
235
+ ctr.convert_from_pinhole_camera_parameters(param)
236
+ vis.poll_events()
237
+ filename = os.path.join(save_folder, '{}_{}_6d.png'.format(scene_name, camera))
238
+ vis.capture_screen_image(filename, do_render=True)
239
+ if show:
240
+ o3d.visualization.draw_geometries([point_cloud, *model_list])
241
+
242
+
243
+
244
+ def visObjGrasp(dataset_root, obj_idx, num_grasp=10, th=0.5, max_width=0.08, save_folder='save_fig', show=False):
245
+ '''
246
+ Author: chenxi-wang
247
+
248
+ **Input:**
249
+
250
+ - dataset_root: str, graspnet dataset root
251
+
252
+ - obj_idx: int, index of object model
253
+
254
+ - num_grasp: int, number of sampled grasps
255
+
256
+ - th: float, threshold of friction coefficient
257
+
258
+ - max_width: float, only visualize grasps with width<=max_width
259
+
260
+ - save_folder: str, folder to save screen captures
261
+
262
+ - show: bool, show visualization in open3d window if set to True
263
+ '''
264
+ plyfile = os.path.join(dataset_root, 'models', '%03d'%obj_idx, 'nontextured.ply')
265
+ model = o3d.io.read_point_cloud(plyfile)
266
+
267
+ num_views, num_angles, num_depths = 300, 12, 4
268
+ views = generate_views(num_views)
269
+
270
+ vis = o3d.visualization.Visualizer()
271
+ vis.create_window(width = 1280, height = 720)
272
+ ctr = vis.get_view_control()
273
+ param = get_camera_parameters(camera='kinect')
274
+
275
+ cam_pos = np.load(os.path.join(dataset_root, 'scenes', 'scene_0000', 'kinect', 'cam0_wrt_table.npy'))
276
+ param.extrinsic = np.linalg.inv(cam_pos).tolist()
277
+
278
+ sampled_points, offsets, scores, _ = get_model_grasps('%s/grasp_label/%03d_labels.npz'%(dataset_root, obj_idx))
279
+
280
+ cnt = 0
281
+ point_inds = np.arange(sampled_points.shape[0])
282
+ np.random.shuffle(point_inds)
283
+ grippers = []
284
+
285
+ for point_ind in point_inds:
286
+ target_point = sampled_points[point_ind]
287
+ offset = offsets[point_ind]
288
+ score = scores[point_ind]
289
+ view_inds = np.arange(300)
290
+ np.random.shuffle(view_inds)
291
+ flag = False
292
+ for v in view_inds:
293
+ if flag: break
294
+ view = views[v]
295
+ angle_inds = np.arange(12)
296
+ np.random.shuffle(angle_inds)
297
+ for a in angle_inds:
298
+ if flag: break
299
+ depth_inds = np.arange(4)
300
+ np.random.shuffle(depth_inds)
301
+ for d in depth_inds:
302
+ if flag: break
303
+ angle, depth, width = offset[v, a, d]
304
+ if score[v, a, d] > th or score[v, a, d] < 0 or width > max_width:
305
+ continue
306
+ R = viewpoint_params_to_matrix(-view, angle)
307
+ t = target_point
308
+ gripper = plot_gripper_pro_max(t, R, width, depth, 1.1-score[v, a, d])
309
+ grippers.append(gripper)
310
+ flag = True
311
+ if flag:
312
+ cnt += 1
313
+ if cnt == num_grasp:
314
+ break
315
+
316
+ vis.add_geometry(model)
317
+ for gripper in grippers:
318
+ vis.add_geometry(gripper)
319
+ ctr.convert_from_pinhole_camera_parameters(param)
320
+ vis.poll_events()
321
+ filename = os.path.join(save_folder, 'object_{}_grasp.png'.format(obj_idx))
322
+ vis.capture_screen_image(filename, do_render=True)
323
+ if show:
324
+ o3d.visualization.draw_geometries([model, *grippers])
325
+
326
+ def vis_rec_grasp(rec_grasp_tuples,numGrasp,image_path,save_path,show=False):
327
+ '''
328
+ author: Minghao Gou
329
+
330
+ **Input:**
331
+
332
+ - rec_grasp_tuples: np.array of rectangle grasps
333
+
334
+ - numGrasp: int of total grasps number to show
335
+
336
+ - image_path: string of path of the image
337
+
338
+ - image_path: string of the path to save the image
339
+
340
+ - show: bool of whether to show the image
341
+
342
+ **Output:**
343
+
344
+ - no output but display the rectangle grasps in image
345
+ '''
346
+ import cv2
347
+ import numpy as np
348
+ import os
349
+ img = cv2.imread(image_path)
350
+ if len(rec_grasp_tuples) > numGrasp:
351
+ np.random.shuffle(rec_grasp_tuples)
352
+ rec_grasp_tuples = rec_grasp_tuples[0:numGrasp]
353
+ for rec_grasp_tuple in rec_grasp_tuples:
354
+ center_x,center_y,open_x,open_y,height,score = rec_grasp_tuple
355
+ center = np.array([center_x,center_y])
356
+ left = np.array([open_x,open_y])
357
+ axis = left - center
358
+ normal = np.array([-axis[1],axis[0]])
359
+ normal = normal / np.linalg.norm(normal) * height / 2
360
+ p1 = center + normal + axis
361
+ p2 = center + normal - axis
362
+ p3 = center - normal - axis
363
+ p4 = center - normal + axis
364
+ cv2.line(img, (int(p1[0]),int(p1[1])), (int(p2[0]),int(p2[1])), (0,0,255), 1, 8)
365
+ cv2.line(img, (int(p2[0]),int(p2[1])), (int(p3[0]),int(p3[1])), (255,0,0), 3, 8)
366
+ cv2.line(img, (int(p3[0]),int(p3[1])), (int(p4[0]),int(p4[1])), (0,0,255), 1, 8)
367
+ cv2.line(img, (int(p4[0]),int(p4[1])), (int(p1[0]),int(p1[1])), (255,0,0), 3, 8)
368
+ cv2.imwrite(save_path,img)
369
+ if show:
370
+ cv2.imshow('grasp',img)
371
+ cv2.waitKey(0)
372
+ cv2.destroyAllWindows()
373
+
374
+
375
+ if __name__ == '__main__':
376
+ camera = 'kinect'
377
+ dataset_root = '../'
378
+ scene_name = 'scene_0000'
379
+ anno_idx = 0
380
+ obj_idx = 0
381
+ visAnno(dataset_root, scene_name, anno_idx, camera, num_grasp=1, th=0.5, align_to_table=True, max_width=0.08, save_folder='save_fig', show=False)
382
+ vis6D(dataset_root, scene_name, anno_idx, camera, align_to_table=True, save_folder='save_fig', show=False)
383
+ visObjGrasp(dataset_root, obj_idx, num_grasp=10, th=0.5, save_folder='save_fig', show=False)
third_party/tuntunclaw/graspnet-baseline/graspnetAPI/graspnetAPI/utils/xmlhandler.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = 'Minghao Gou'
2
+ __version__ = '1.0'
3
+
4
+ from xml.etree.ElementTree import Element, SubElement, tostring
5
+ import xml.etree.ElementTree as ET
6
+ import xml.dom.minidom
7
+ from transforms3d.quaternions import mat2quat, quat2axangle
8
+ from transforms3d.euler import quat2euler
9
+ import numpy as np
10
+ from .trans3d import get_mat, pos_quat_to_pose_4x4
11
+ import os
12
+ from .pose import pose_list_from_pose_vector_list
13
+
14
+
15
+ class xmlWriter():
16
+ def __init__(self, topfromreader=None):
17
+ self.topfromreader = topfromreader
18
+ self.poselist = []
19
+ self.objnamelist = []
20
+ self.objpathlist = []
21
+ self.objidlist = []
22
+ def addobject(self, pose, objname, objpath, objid):
23
+ # pose is the 4x4 matrix representation of 6d pose
24
+ self.poselist.append(pose)
25
+ self.objnamelist.append(objname)
26
+ self.objpathlist.append(objpath)
27
+ self.objidlist.append(objid)
28
+
29
+ def objectlistfromposevectorlist(self, posevectorlist, objdir, objnamelist, objidlist):
30
+ self.poselist = []
31
+ self.objnamelist = []
32
+ self.objidlist = []
33
+ self.objpathlist = []
34
+ for i in range(len(posevectorlist)):
35
+ id, x, y, z, alpha, beta, gamma = posevectorlist[i]
36
+ objname = objnamelist[objidlist[i]]
37
+ self.addobject(get_mat(x, y, z, alpha, beta, gamma),
38
+ objname, os.path.join(objdir, objname), id)
39
+
40
+ def writexml(self, xmlfilename='scene.xml'):
41
+ if self.topfromreader is not None:
42
+ self.top = self.topfromreader
43
+ else:
44
+ self.top = Element('scene')
45
+ for i in range(len(self.poselist)):
46
+ obj_entry = SubElement(self.top, 'obj')
47
+
48
+ obj_name = SubElement(obj_entry, 'obj_id')
49
+ obj_name.text = str(self.objidlist[i])
50
+
51
+ obj_name = SubElement(obj_entry, 'obj_name')
52
+ obj_name.text = self.objnamelist[i]
53
+
54
+ obj_path = SubElement(obj_entry, 'obj_path')
55
+ obj_path.text = self.objpathlist[i]
56
+ pose = self.poselist[i]
57
+ pose_in_world = SubElement(obj_entry, 'pos_in_world')
58
+ pose_in_world.text = '{:.4f} {:.4f} {:.4f}'.format(
59
+ pose[0, 3], pose[1, 3], pose[2, 3])
60
+
61
+ rotationMatrix = pose[0:3, 0:3]
62
+ quat = mat2quat(rotationMatrix)
63
+
64
+ ori_in_world = SubElement(obj_entry, 'ori_in_world')
65
+ ori_in_world.text = '{:.4f} {:.4f} {:.4f} {:.4f}'.format(
66
+ quat[0], quat[1], quat[2], quat[3])
67
+ xmlstr = xml.dom.minidom.parseString(
68
+ tostring(self.top)).toprettyxml(indent=' ')
69
+ # remove blank line
70
+ xmlstr = "".join([s for s in xmlstr.splitlines(True) if s.strip()])
71
+ with open(xmlfilename, 'w') as f:
72
+ f.write(xmlstr)
73
+ #print('log:write annotation file '+xmlfilename)
74
+
75
+
76
+ class xmlReader():
77
+ def __init__(self, xmlfilename):
78
+ self.xmlfilename = xmlfilename
79
+ etree = ET.parse(self.xmlfilename)
80
+ self.top = etree.getroot()
81
+
82
+ def showinfo(self):
83
+ print('Resumed object(s) already stored in '+self.xmlfilename+':')
84
+ for i in range(len(self.top)):
85
+ print(self.top[i][1].text)
86
+
87
+ def gettop(self):
88
+ return self.top
89
+
90
+ def getposevectorlist(self):
91
+ # posevector foramat: [objectid,x,y,z,alpha,beta,gamma]
92
+ posevectorlist = []
93
+ for i in range(len(self.top)):
94
+ objectid = int(self.top[i][0].text)
95
+ objectname = self.top[i][1].text
96
+ objectpath = self.top[i][2].text
97
+ translationtext = self.top[i][3].text.split()
98
+ translation = []
99
+ for text in translationtext:
100
+ translation.append(float(text))
101
+ quattext = self.top[i][4].text.split()
102
+ quat = []
103
+ for text in quattext:
104
+ quat.append(float(text))
105
+ alpha, beta, gamma = quat2euler(quat)
106
+ x, y, z = translation
107
+ alpha *= (180.0 / np.pi)
108
+ beta *= (180.0 / np.pi)
109
+ gamma *= (180.0 / np.pi)
110
+ posevectorlist.append([objectid, x, y, z, alpha, beta, gamma])
111
+ return posevectorlist
112
+
113
+ def get_pose_list(self):
114
+ pose_vector_list = self.getposevectorlist()
115
+ return pose_list_from_pose_vector_list(pose_vector_list)
116
+
117
+ def empty_pose_vector(objectid):
118
+ # [object id,x,y,z,alpha,beta,gamma]
119
+ # alpha, beta and gamma are in degree
120
+ return [objectid, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0]
121
+
122
+
123
+ def empty_pose_vector_list(objectidlist):
124
+ pose_vector_list = []
125
+ for id in objectidlist:
126
+ pose_vector_list.append(empty_pose_vector(id))
127
+ return pose_vector_list
128
+
129
+
130
+ def getposevectorlist(objectidlist, is_resume, num_frame, frame_number, xml_dir):
131
+ if not is_resume or (not os.path.exists(os.path.join(xml_dir, '%04d.xml' % num_frame))):
132
+ print('log:create empty pose vector list')
133
+ return empty_pose_vector_list(objectidlist)
134
+ else:
135
+ print('log:resume pose vector from ' +
136
+ os.path.join(xml_dir, '%04d.xml' % num_frame))
137
+ xmlfile = os.path.join(xml_dir, '%04d.xml' % num_frame)
138
+ mainxmlReader = xmlReader(xmlfile)
139
+ xmlposevectorlist = mainxmlReader.getposevectorlist()
140
+ posevectorlist = []
141
+ for objectid in objectidlist:
142
+ posevector = [objectid, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
143
+ for xmlposevector in xmlposevectorlist:
144
+ if xmlposevector[0] == objectid:
145
+ posevector = xmlposevector
146
+ posevectorlist.append(posevector)
147
+ return posevectorlist
148
+
149
+
150
+ def getframeposevectorlist(objectidlist, is_resume, frame_number, xml_dir):
151
+ frameposevectorlist = []
152
+ for num_frame in range(frame_number):
153
+ if not is_resume or (not os.path.exists(os.path.join(xml_dir,'%04d.xml' % num_frame))):
154
+ posevectorlist=getposevectorlist(objectidlist,False,num_frame,frame_number,xml_dir)
155
+ else:
156
+ posevectorlist=getposevectorlist(objectidlist,True,num_frame,frame_number,xml_dir)
157
+ frameposevectorlist.append(posevectorlist)
158
+ return frameposevectorlist
third_party/tuntunclaw/manipulator_grasp/arm/__init__.py ADDED
File without changes
third_party/tuntunclaw/manipulator_grasp/utils/__init__.py ADDED
File without changes
third_party/tuntunclaw/manipulator_grasp/utils/mj.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple, Union
2
+ import numpy as np
3
+ import spatialmath as sm
4
+ import spatialmath.base as smb
5
+ import mujoco as mj
6
+ from .rtb import make_tf
7
+
8
+
9
+ def set_body_pose(model: mj.MjModel, data: mj.MjData, body_name: Union[int, str], xpos: np.ndarray) -> None:
10
+ body_id = (
11
+ body_name if isinstance(body_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_BODY, body_name)
12
+ )
13
+ data.body(body_id).xpos = xpos[:3]
14
+
15
+ def get_body_pose(model: mj.MjModel, data: mj.MjData, body_name: Union[int, str]) -> sm.SE3:
16
+ body_id = (
17
+ body_name if isinstance(body_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_BODY, body_name)
18
+ )
19
+ t = data.body(body_id).xpos
20
+ q = data.body(body_id).xquat
21
+ return make_tf(pos=t, ori=q)
22
+
23
+
24
+ def set_joint_q(model: mj.MjModel, data: mj.MjData, joint_name: Union[int, str], q: Union[np.ndarray, float],
25
+ unit: str = "rad") -> None:
26
+ joint_id = (
27
+ joint_name if isinstance(joint_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, joint_name)
28
+ )
29
+
30
+ if unit == 'deg':
31
+ q = np.deg2rad(q)
32
+
33
+ q_inds = get_joint_qpos_inds(model, data, joint_id)
34
+ data.qpos[q_inds] = q
35
+
36
+
37
+ def get_joint_q(model: mj.MjModel, data: mj.MjData, joint_name: Union[int, str]) -> np.ndarray:
38
+ joint_id = (
39
+ joint_name if isinstance(joint_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, joint_name)
40
+ )
41
+ q_inds = get_joint_qpos_inds(model, data, joint_id)
42
+ return data.qpos[q_inds]
43
+
44
+
45
+ def get_joint_qpos_inds(model: mj.MjModel, data: mj.MjData, joint_name: Union[int, str]) -> np.ndarray:
46
+ joint_id = (
47
+ joint_name if isinstance(joint_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, joint_name)
48
+ )
49
+ addr = get_joint_qpos_addr(model, joint_id)
50
+ joint_dim = get_joint_dim(model, data, joint_id)
51
+ return np.array(range(addr, addr + joint_dim))
52
+
53
+
54
+ def get_joint_qpos_addr(model: mj.MjModel, joint_name: Union[int, str]) -> int:
55
+ joint_id = (
56
+ joint_name if isinstance(joint_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, joint_name)
57
+ )
58
+ return model.jnt_qposadr[joint_id]
59
+
60
+
61
+ def get_joint_dim(model: mj.MjModel, data: mj.MjData, joint_name: Union[str, int]) -> int:
62
+ joint_id = (
63
+ joint_name if isinstance(joint_name, int) else mj.mj_name2id(model, mj.mjtObj.mjOBJ_JOINT, joint_name)
64
+ )
65
+ return len(data.joint(joint_id).qpos)
66
+
67
+
68
+ def set_free_joint_pose(model: mj.MjModel, data: mj.MjData, joint_name: Union[int, str], T: sm.SE3) -> None:
69
+ t = T.t
70
+ q = sm.base.r2q(T.R).data
71
+ T_new = np.append(t, q)
72
+ set_joint_q(model, data, joint_name, T_new)
73
+
74
+
75
+ def attach(model: mj.MjModel, data: mj.MjData, equality_name: str, free_joint_name: str, T: sm.SE3,
76
+ eq_data=np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]),
77
+ eq_solimp: np.ndarray = np.array([[0.99, 0.99, 0.001, 0.5, 1]]),
78
+ eq_solref: np.ndarray = np.array([0.0001, 1])
79
+ ) -> None:
80
+ eq_id = mj.mj_name2id(model, mj.mjtObj.mjOBJ_EQUALITY, equality_name)
81
+
82
+ if eq_id is None:
83
+ raise ValueError(
84
+ f"Equality constraint with name '{equality_name}' not found in the model."
85
+ )
86
+
87
+ data.eq_active[eq_id] = 0
88
+
89
+ set_free_joint_pose(model, data, free_joint_name, T)
90
+
91
+ model.equality(equality_name).data = eq_data
92
+
93
+ model.equality(equality_name).solimp = eq_solimp
94
+ model.equality(equality_name).solref = eq_solref
95
+
96
+ data.eq_active[eq_id] = 1