YuXingyao commited on
Commit
e289681
·
0 Parent(s):

fresh start

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +25 -0
  2. .gitignore +177 -0
  3. Dockerfile +76 -0
  4. LICENSE +674 -0
  5. README.md +4 -0
  6. __init__.py +0 -0
  7. app.py +656 -0
  8. app/AppLayout.py +291 -0
  9. app/DataProcessor/DataProcessor.py +25 -0
  10. app/DataProcessor/ImageProcessor.py +23 -0
  11. app/DataProcessor/MultiImageProcessor.py +23 -0
  12. app/DataProcessor/PointCloudProcessor.py +44 -0
  13. app/DataProcessor/SingleImageProcessor.py +14 -0
  14. app/DataProcessor/TxtProcessor.py +5 -0
  15. app/DataProcessor/__init__.py +14 -0
  16. app/GeneratingMethod/ConditionedGenerating.py +246 -0
  17. app/GeneratingMethod/UnconditionedGenerating.py +138 -0
  18. app/GeneratingMethod/__init__.py +4 -0
  19. app/ModelBuilder.py +126 -0
  20. app/ModelDirector/MVRDirector.py +18 -0
  21. app/ModelDirector/ModelDirector.py +55 -0
  22. app/ModelDirector/PointCloudDirector.py +12 -0
  23. app/ModelDirector/SVRDirector.py +12 -0
  24. app/ModelDirector/SketchDirector.py +12 -0
  25. app/ModelDirector/TextDirector.py +12 -0
  26. app/ModelDirector/__init__.py +8 -0
  27. app/__init__.py +3 -0
  28. app/inference.py +65 -0
  29. construct_brep.py +431 -0
  30. environment.yml +10 -0
  31. eval/__init__.py +0 -0
  32. eval/check_data_deduplicate.py +247 -0
  33. eval/check_deduplicate_dis.py +317 -0
  34. eval/check_valid.py +159 -0
  35. eval/eval_brepgen.py +409 -0
  36. eval/eval_complexity.py +194 -0
  37. eval/eval_cond.sh +13 -0
  38. eval/eval_condition.py +479 -0
  39. eval/eval_lfd.sh +11 -0
  40. eval/eval_pc_set.py +44 -0
  41. eval/eval_uncond.sh +15 -0
  42. eval/eval_unique_novel.py +395 -0
  43. eval/eval_validity.py +81 -0
  44. eval/lfd/evaluation_scripts/README.md +75 -0
  45. eval/lfd/evaluation_scripts/compute_lfd.py +137 -0
  46. eval/lfd/evaluation_scripts/compute_lfd_check_data.py +193 -0
  47. eval/lfd/evaluation_scripts/compute_lfd_feat/compute_lfd_feat_multiprocess.py +158 -0
  48. eval/lfd/evaluation_scripts/compute_lfd_feat/dummy-1920x1080.conf +25 -0
  49. eval/lfd/evaluation_scripts/compute_lfd_feat/lfd_me.py +133 -0
  50. eval/lfd/evaluation_scripts/lfd_all_compute/lfd.py +123 -0
.gitattributes ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ app/examples/mvr.png filter=lfs diff=lfs merge=lfs -text
2
+ app/examples/pc_examples/00052336/pc.ply filter=lfs diff=lfs merge=lfs -text
3
+ app/examples/pc_examples/00052336/pc.png filter=lfs diff=lfs merge=lfs -text
4
+ app/examples/pc_examples/00058704/pc.ply filter=lfs diff=lfs merge=lfs -text
5
+ app/examples/pc_examples/00058704/pc.png filter=lfs diff=lfs merge=lfs -text
6
+ app/examples/pc_examples/00181288/pc.ply filter=lfs diff=lfs merge=lfs -text
7
+ app/examples/pc_examples/00181288/pc.png filter=lfs diff=lfs merge=lfs -text
8
+ app/examples/pc_examples/00200380/pc.ply filter=lfs diff=lfs merge=lfs -text
9
+ app/examples/pc_examples/00200380/pc.png filter=lfs diff=lfs merge=lfs -text
10
+ app/examples/pc_examples/00268284/pc.ply filter=lfs diff=lfs merge=lfs -text
11
+ app/examples/pc_examples/00268284/pc.png filter=lfs diff=lfs merge=lfs -text
12
+ app/examples/pc_examples/00352224/pc.ply filter=lfs diff=lfs merge=lfs -text
13
+ app/examples/pc_examples/00352224/pc.png filter=lfs diff=lfs merge=lfs -text
14
+ app/examples/pc_examples/00423708/pc.ply filter=lfs diff=lfs merge=lfs -text
15
+ app/examples/pc_examples/00423708/pc.png filter=lfs diff=lfs merge=lfs -text
16
+ app/examples/pc_examples/00471383/pc.ply filter=lfs diff=lfs merge=lfs -text
17
+ app/examples/pc_examples/00471383/pc.png filter=lfs diff=lfs merge=lfs -text
18
+ app/examples/pc_examples/00480992/pc.ply filter=lfs diff=lfs merge=lfs -text
19
+ app/examples/pc_examples/00480992/pc.png filter=lfs diff=lfs merge=lfs -text
20
+ app/examples/pc_examples/00518919/pc.ply filter=lfs diff=lfs merge=lfs -text
21
+ app/examples/pc_examples/00518919/pc.png filter=lfs diff=lfs merge=lfs -text
22
+ app/examples/pc_examples/00773954/pc.ply filter=lfs diff=lfs merge=lfs -text
23
+ app/examples/pc_examples/00773954/pc.png filter=lfs diff=lfs merge=lfs -text
24
+ app/examples/pc_examples/00847353/pc.ply filter=lfs diff=lfs merge=lfs -text
25
+ app/examples/pc_examples/00847353/pc.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
+ .gradio
176
+ outputs/
177
+ .vscode
Dockerfile ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+
5
+ ENV FORCE_CUDA="1"
6
+ ENV CUDA_HOME="/usr/local/cuda-12.4"
7
+ ARG TORCH_CUDA_ARCH_LIST="7.5+PTX"
8
+ ENV LD_LIBRARY_PATH="${CUDA_HOME}/lib64:${LD_LIBRARY_PATH}"
9
+ ENV PATH="/usr/local/cuda/bin:/usr/local/cuda-12/bin:${CUDA_HOME}/bin:${PATH}"
10
+ ENV HF_HOME="/data/.huggingface"
11
+
12
+ ###########################
13
+ # Prepare the environment #
14
+ ###########################
15
+ WORKDIR /code
16
+
17
+ RUN apt-get update && apt-get install -y \
18
+ wget \
19
+ bzip2 \
20
+ ca-certificates \
21
+ curl \
22
+ libglib2.0-0 \
23
+ libx11-6 \
24
+ git \
25
+ vim \
26
+ cmake \
27
+ make \
28
+ g++-9 \
29
+ libgl-dev \
30
+ freeglut3 \
31
+ freeglut3-dev \
32
+ libosmesa6-dev \
33
+ libglu1-mesa-dev \
34
+ libglu1-mesa \
35
+ xserver-xorg-video-dummy \
36
+ && rm -rf /var/lib/apt/lists/*
37
+
38
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-py310_24.5.0-0-Linux-x86_64.sh -O /tmp/miniconda.sh \
39
+ && bash /tmp/miniconda.sh -b -p /opt/conda \
40
+ && rm /tmp/miniconda.sh
41
+
42
+ ENV PATH="/opt/conda/bin:${PATH}"
43
+ COPY ./environment.yml /code/environment.yml
44
+ COPY ./pointnet2_ops_lib /code/pointnet2_ops_lib
45
+
46
+ RUN conda env create -f environment.yml
47
+
48
+ COPY ./requirements.txt /code/requirements.txt
49
+
50
+ SHELL ["/bin/bash", "-c"]
51
+ RUN source activate HoLa-Brep && \
52
+ export CUDA_HOME=/usr/local/cuda-12.4 && \
53
+ export FORCE_CUDA=1 && \
54
+ python -m pip install --no-cache-dir torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu124
55
+
56
+ RUN conda list -n HoLa-Brep | grep pytorch
57
+
58
+ RUN source activate HoLa-Brep && \
59
+ export CUDA_HOME=/usr/local/cuda-12.4 && \
60
+ export FORCE_CUDA=1 && \
61
+ python -m pip install --no-cache-dir -r /code/requirements.txt
62
+
63
+ ###########
64
+ # Run app #
65
+ ###########
66
+ RUN useradd -m -u 1000 user
67
+ USER user
68
+ ENV HOME="/home/user"
69
+ ENV PYTHONPATH="/home/user/HoLa-Brep:/data:${PYTHONPATH}"
70
+ EXPOSE 7860
71
+ ENV GRADIO_SERVER_NAME="0.0.0.0"
72
+ WORKDIR ${HOME}/HoLa-Brep
73
+
74
+ COPY --chown=user . ${HOME}/HoLa-Brep
75
+
76
+ CMD ["/bin/bash", "-c", "source activate HoLa-Brep && python app.py"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ title: HoLa-BRep
3
+ sdk: docker
4
+ ---
__init__.py ADDED
File without changes
app.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Frontend
2
+ import sys
3
+ import gradio as gr
4
+ from pathlib import Path
5
+ import os
6
+ sys.path.insert(0, "/data")
7
+ from app.AppLayout import *
8
+ from app.GeneratingMethod import *
9
+ from app.ModelDirector import *
10
+ from app.DataProcessor import *
11
+
12
+ os.environ["HF_HOME"] = "/data/.huggingface"
13
+ os.environ["TORCH_HOME"] = "/data/.cache/torch"
14
+
15
+ # Theme
16
+ theme = gr.themes.Soft(
17
+ primary_hue="slate",
18
+ text_size="lg",
19
+ font=['IBM Plex Sans', 'ui-sans-serif', 'system-ui', gr.themes.GoogleFont('sans-serif')],
20
+ ).set(
21
+ block_background_fill='*primary_200',
22
+ button_primary_background_fill='*primary_100',
23
+ body_background_fill='*secondary_50',
24
+ )
25
+
26
+ force_light = """
27
+ function refresh() {
28
+ const url = new URL(window.location);
29
+
30
+ if (url.searchParams.get('__theme') !== 'light') {
31
+ url.searchParams.set('__theme', 'light');
32
+ window.location.href = url.href;
33
+ }
34
+ }
35
+ """
36
+
37
+ # 自定义CSS样式
38
+ custom_css = """
39
+ .gr-tabs.gr-tab-label {
40
+ text-align: center;
41
+ }
42
+ button[role="tab"] {
43
+ font-size: 20px;
44
+ }
45
+ div[role="tablist"] {
46
+ height: var(--size-12);
47
+ }
48
+
49
+ #top-row {
50
+ display: flex;
51
+ justify-content: space-between;
52
+ align-items: center;
53
+ width: 100%;
54
+ }
55
+ #button-group {
56
+ display: flex;
57
+ gap: 10px;
58
+ justify-content: flex-end;
59
+ }
60
+ .small-button {
61
+ max-width: 80px;
62
+ padding: 6px 10px;
63
+ font-size: 14px;
64
+ }
65
+
66
+ @media (min-width: 1024px) {
67
+ div[role="tablist"] {
68
+ /* 电脑端居中 */
69
+ justify-content: center;
70
+ }
71
+ }
72
+
73
+ .tabs {
74
+ margin-top: 20px;
75
+ }
76
+
77
+ div[data-testid="markdown"] span p:not(:first-child) {
78
+ margin-top: unset;
79
+ }
80
+ div[data-testid="markdown"] pre code {
81
+ font-family: 'IBM Plex Sans', 'ui-sans-serif', 'system-ui', 'sans-serif';
82
+ font-size: 14px;
83
+ }
84
+
85
+ /* 媒体查询 */
86
+ @media (max-width: 768px) {
87
+ button[role="tab"] {
88
+ font-size: 15px;
89
+ }
90
+ p.title1 {
91
+ font-size: 46px !important;
92
+ letter-spacing: unset !important;
93
+ }
94
+ p.title2 {
95
+ font-size: 21px !important;
96
+ }
97
+ p.title4 {
98
+ font-size: 16px !important;
99
+ }
100
+ p.title5 {
101
+ font-size: 12px !important;
102
+ }
103
+ }
104
+
105
+ h2.heading {
106
+ font-size: 23px;
107
+ }
108
+
109
+ @media (max-width: 550px) {
110
+ .title3-responsive {
111
+ gap: 0 !important;
112
+ }
113
+ .title3-responsive span:first-child,
114
+ .title3-responsive span:last-child {
115
+ width: 20px !important;
116
+ }
117
+ .title3-responsive span:nth-child(2) {
118
+ padding: 2px 6px !important;
119
+ font-size: 12px;
120
+ }
121
+ }
122
+
123
+ @media (min-width: 551px) and (max-width: 768px) {
124
+ .title3-responsive {
125
+ gap: 0 !important;
126
+ }
127
+ .title3-responsive span:first-child,
128
+ .title3-responsive span:last-child {
129
+ width: 50px !important;
130
+ }
131
+ .title3-responsive span:nth-child(2) {
132
+ font-size: 15px;
133
+ }
134
+ }
135
+
136
+ @media (min-width: 769px) and (max-width: 1024px) {
137
+ .title3-responsive span:first-child,
138
+ .title3-responsive span:last-child {
139
+ width: 70px !important;
140
+ }
141
+ .title3-responsive span:nth-child(2) {
142
+ font-size: 20px;
143
+ }
144
+ }
145
+
146
+ @media (max-width: 768px) {
147
+ .mobile-break {
148
+ display: block;
149
+ }
150
+ }
151
+ @media (min-width: 769px) {
152
+ .mobile-break {
153
+ display: none;
154
+ }
155
+ }
156
+ """
157
+
158
+ DEMO_NUM = 4
159
+ WIREFRAME_FILE = 0
160
+ SOLID_FILE = 1
161
+ STEP_FILE = 2
162
+
163
+ BACKEND_CONDITION_DICT = {
164
+ 'Unconditional': 'uncond',
165
+ 'Point Cloud' : 'pc',
166
+ 'Text' : 'txt',
167
+ 'Sketch' : 'sketch',
168
+ 'SVR' : 'single_img',
169
+ 'MVR': 'multi_img'
170
+ }
171
+
172
+ # Dynamically registered functions
173
+ def switch_model(user_state: dict, generate_mode: str, model_index: int, offset: int):
174
+ model_index = (model_index + offset) % DEMO_NUM
175
+ generate_mode = BACKEND_CONDITION_DICT[generate_mode]
176
+ # Check if the condition has been generated
177
+ if generate_mode not in user_state.keys():
178
+ return model_index, gr.update(value='empty.obj', label=f'Wireframe{model_index + 1}'), gr.update(value='empty.obj', label=f'Solid{model_index + 1}'), gr.update( value=["app/examples/empty_examples/sample.stl", "app/examples/empty_examples/sample.ply", "app/examples/empty_examples/sample.step"], label=f'Models{model_index + 1}')
179
+
180
+ # Check if model_index exceeds the number of current valid models
181
+ if model_index >= len(user_state[generate_mode]):
182
+ return model_index, gr.update(value='empty.obj', label=f'Wireframe{model_index + 1}'), gr.update(value='empty.obj', label=f'Solid{model_index + 1}'), gr.update( value=["app/examples/empty_examples/sample.stl", "app/examples/empty_examples/sample.ply", "app/examples/empty_examples/sample.step"], label=f'Models{model_index + 1}')
183
+
184
+ wireframe_model = user_state[generate_mode][model_index][WIREFRAME_FILE]
185
+ solid_model = user_state[generate_mode][model_index][SOLID_FILE]
186
+ if not (os.path.exists(wireframe_model) and os.path.exists(solid_model)):
187
+ gr.Warning("The operation is too frequent!", title="Frequent Operation")
188
+ return gr.update(), gr.update(), gr.update(), gr.update()
189
+ return model_index, gr.Model3D(wireframe_model, label=f'Wireframe{model_index + 1}'), gr.Model3D(solid_model, label=f'Solid{model_index + 1}'), gr.Files(user_state[generate_mode][model_index], label=f'Models{model_index + 1}', interactive=False)
190
+
191
+
192
+ def set_generating_type(mode):
193
+ return gr.Text(mode, visible=False)
194
+
195
+ def make_Chinese_descriptions():
196
+ return (title_cn,
197
+ description_cn,
198
+ UncondLayout().get_Chinese_note(),
199
+ PCLayout().get_Chinese_note(),
200
+ SketchLayout().get_Chinese_note(),
201
+ TextLayout().get_Chinese_note(),
202
+ SVRLayout().get_Chinese_note(),
203
+ MVRLayout().get_Chinese_note(),
204
+ notification_mvr_cn,
205
+ gr.update(label="无条件"),
206
+ gr.update(label="点云"),
207
+ gr.update(label="草图"),
208
+ gr.update(label="文本"),
209
+ gr.update(label="单视图"),
210
+ gr.update(label="多视图"),
211
+ gr.update(label="多视图输入注意事项:"),
212
+ gr.update(value="生成"),
213
+ gr.update(value="生成"),
214
+ gr.update(value="生成"),
215
+ gr.update(value="生成"),
216
+ gr.update(value="生成"),
217
+ gr.update(value="生成"),
218
+ gr.update(value="上一个"),
219
+ gr.update(value="下一个"),
220
+ gr.update(label="实体"),
221
+ gr.update(label="线框"),
222
+ gr.update(label="下载"),
223
+ citation_cn
224
+ )
225
+
226
+ def make_English_descriptions():
227
+ return (title_en,
228
+ description_en,
229
+ UncondLayout().get_English_note(),
230
+ PCLayout().get_English_note(),
231
+ SketchLayout().get_English_note(),
232
+ TextLayout().get_English_note(),
233
+ SVRLayout().get_English_note(),
234
+ MVRLayout().get_English_note(),
235
+ notification_mvr_en,
236
+ gr.update(label="Unconditional"),
237
+ gr.update(label="Point Cloud"),
238
+ gr.update(label="Sketch"),
239
+ gr.update(label="Text"),
240
+ gr.update(label="SVR"),
241
+ gr.update(label="MVR"),
242
+ gr.update(label="MVR input notification:"),
243
+ gr.update(value="generate"),
244
+ gr.update(value="generate"),
245
+ gr.update(value="generate"),
246
+ gr.update(value="generate"),
247
+ gr.update(value="generate"),
248
+ gr.update(value="generate"),
249
+ gr.update(value="Last"),
250
+ gr.update(value="Next"),
251
+ gr.update(label="Solid"),
252
+ gr.update(label="Wireframe"),
253
+ gr.update(label="Download"),
254
+ citation_en
255
+ )
256
+
257
+ # Declarations for pre-rendering
258
+ model_solid = gr.Model3D(label=f'Solid1', value='empty.obj', key="Solid")
259
+ model_wireframe = gr.Model3D(label=f'Wireframe1', value='empty.obj', key="Wireframe")
260
+ step_file = gr.File(label=f'Step', file_count='single', file_types=['.step'], interactive=False, visible=False)
261
+ download_files = gr.Files(label=f"Models1", value=["app/examples/empty_examples/sample.stl", "app/examples/empty_examples/sample.ply", "app/examples/empty_examples/sample.step"], interactive=False, key="Downloads")
262
+
263
+ input_tab = gr.Tabs()
264
+
265
+ generating_type = gr.Text("Unconditional",visible=False)
266
+
267
+ title_en = gr.Markdown(
268
+ """
269
+ <h1 style='display: block; position: relative; text-align: center; text-rendering: optimizelegibility;'>
270
+ <p class='title1' style='font-size: 100px; text-align: center;'>
271
+ HoLa-BRep
272
+ </p>
273
+ <p class='title2' style='font-size: 32px; text-align: center;'>
274
+ HoLa: B-Rep Generation using a Holistic Latent Representation
275
+ </p>
276
+ <p class='title3-responsive' style='font-size: 22px; text-align: center; display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: nowrap;'>
277
+ <span style="width: 100px; height: 1px; background-color: #999;"></span>
278
+ <span style="color: #3b3891; padding: 4px 8px; border-radius: 8px; font-weight: bold;">
279
+ ACM Trans. on Graphics (SIGGRAPH) 2025
280
+ </span>
281
+ <span style="width: 100px; height: 1px; background-color: #999;"></span>
282
+ </p>
283
+ <p class='title4' style='font-size: 20px; text-align: center;'>
284
+ Yilin Liu, Duoteng Xu, Xingyao Yu, Xiang Xu, Daniel Cohen-Or, Hao Zhang, Hui Huang*
285
+ </p>
286
+ <p class='title5' style='font-size: 20px; text-align: center;'>
287
+ (Visual Computing Research Center, Shenzhen University)
288
+ </p>
289
+ </h1>
290
+ """
291
+ )
292
+ title_cn = gr.Markdown(
293
+ """
294
+ <h1 style='display: block; position: relative; text-align: center; text-rendering: optimizelegibility;'>
295
+ <p class='title1' style='font-size: 100px; text-align: center;'>
296
+ HoLa-BRep
297
+ </p>
298
+ <p class='title2' style='font-size: 32px; text-align: center;'>
299
+ HoLa: B-Rep Generation using a Holistic Latent Representation
300
+ </p>
301
+ <p class='title3-responsive' style='font-size: 22px; text-align: center; display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: nowrap;'>
302
+ <span style="width: 100px; height: 1px; background-color: #999;"></span>
303
+ <span style="color: #3b3891; padding: 4px 8px; border-radius: 8px; font-weight: bold;">
304
+ ACM Trans. on Graphics (SIGGRAPH) 2025
305
+ </span>
306
+ <span style="width: 100px; height: 1px; background-color: #999;"></span>
307
+ </p>
308
+ <p class='title4' style='font-size: 20px; text-align: center;'>
309
+ <span>刘奕林, 许铎腾, 余星耀, 徐翔, </span>
310
+ <br class="mobile-break">
311
+ <span>Daniel Cohen-Or, 张皓, 黄惠*</span>
312
+ </p>
313
+ <p class='title5' style='font-size: 20px; text-align: center;'>
314
+ (深圳大学可视计算研究中心)
315
+ </p>
316
+ </h1>
317
+ """
318
+ )
319
+
320
+ description_en = gr.Markdown(
321
+ """
322
+ # <h2 class='heading'>What is HoLa-BRep?</h2>
323
+ HoLa-BRep is a generative model that produces CAD models in boundary representation (BRep) based on various conditions, including point cloud, single-view image, multi-view images, single-view sketch or text description.
324
+ It contains **1 unified** BRep variational encoder (VAE) to encode a BRep model's topological and geometric information into a holistic latent space, and a latent diffusion model (LDM) to generate such latent from multiple modalities.
325
+ Compared with the state-of-the-art method, HoLa-BRep only has 1 unified VAE and the corresponding latent space and 1 LDM for generation, so it is easier to train the model without any inter-dependency of the model. This is extremely useful when incorporating more modalities and even mix-modality training.
326
+
327
+ # <h2 class='heading'>How to use it?</h2>
328
+ + Please refer to the example below for more details. You can select the desired **modality** below and upload your own data.
329
+ + We generate **4** plausible BRep models for each input(**about 3 minutes**) and visualize them in the 3D viewer.
330
+ + Try to explore the generated BRep models by rotating, zooming, and panning the 3D viewer, or **download** either the wireframe, surface mesh, or solid BRep model as OBJ or STEP files.
331
+
332
+ # <h2 class='heading'>Project page</h2>
333
+ + https://vcc.tech/research/2025/HolaBRep
334
+ """
335
+ )
336
+ description_cn = gr.Markdown(
337
+ """
338
+ # <h2 class='heading'>HoLa-BRep是什么?</h2>
339
+ HoLa-BRep 是一个多模态CAD生成模型,它支持输入点云、单视角图像、多视角图像、单视角草图或文本描述等多种模态条件,生成边界表示 (BRep) 的 CAD 模型。
340
+ 它包含**1个统一**的 BRep变分自编码器 (VAE),可将 BRep 模型的拓扑和几何信息编码到一个结构化的低维隐空间,以及一个隐式扩散模型(LDM)用于从多种模态生成这种BRep结构化嵌入。
341
+ 与目前国内外领先技术相比,HoLa-BRep 只有1个 自编码器和1个扩散模型的特性极大地减少了训练的复杂程度并且利于向更大规模的训练拓展。同时这种单个结构化隐空间的设计模式也解决了现有方法多个模型相互依赖复杂的问题。在结合更多模态甚至混合模态训练时能显著提升训练效率。
342
+
343
+ # <h2 class='heading'>如何使用?</h2>
344
+ + 请参考下面的示例。您可以在下面选择所需的**模式**并上传自己的数据。
345
+ + 我们会为每个输入生成 4 个可选的 BRep 模型(**大约3分钟**),并在 3D 查看器中可视化。
346
+ + 你可以通过旋转、缩放和平移等操作查看生成的 BRep 模型,也可以将线框、曲面网格或实体 BRep 模型下载为 OBJ 或 STEP 文件。
347
+
348
+ # <h2 class='heading'>项目主页</h2>
349
+ + https://vcc.tech/research/2025/HolaBRep
350
+ """
351
+ )
352
+
353
+ citation_en = gr.Markdown(
354
+ value=
355
+ """
356
+ <h2 class='heading' style='margin-top: 16px;'>Citation</h2>
357
+
358
+ If our work is helpful for your research or applications, please cite us via:
359
+ <br>
360
+ ```
361
+ @article{HolaBRep25,
362
+ title={HoLa: B-Rep Generation using a Holistic Latent Representation},
363
+ author={Yilin Liu and Duoteng Xu and Xinyao Yu and Xiang Xu and Daniel Cohen-Or and Hao Zhang and Hui Huang},
364
+ journal={ACM Transactions on Graphics (SIGGRAPH)},
365
+ volume={44},
366
+ number={4},
367
+ year={2025},
368
+ }
369
+ ```
370
+ """,
371
+ height=300,
372
+ )
373
+
374
+ citation_cn = gr.Markdown(
375
+ value=
376
+ """
377
+ <h2 class='heading' style='margin-top: 16px;'>引用</h2>
378
+
379
+ 如果我们的工作对您的研究或者应用有帮助,请通过以下方式进行引用:
380
+ <br>
381
+
382
+ ```
383
+ @article{HolaBRep25,
384
+ title={HoLa: B-Rep Generation using a Holistic Latent Representation},
385
+ author={Yilin Liu and Duoteng Xu and Xinyao Yu and Xiang Xu and Daniel Cohen-Or and Hao Zhang and Hui Huang},
386
+ journal={ACM Transactions on Graphics (SIGGRAPH)},
387
+ volume={44},
388
+ number={4},
389
+ year={2025},
390
+ }
391
+ ```
392
+ """,
393
+ height=300,
394
+ )
395
+
396
+ notification_mvr_en = gr.Markdown("**You can take and upload photos of objects as shown below.**")
397
+ notification_mvr_cn = gr.Markdown("**您可以按如下方式拍摄并上传物体照片**")
398
+
399
+ descriptions = []
400
+
401
+ # Main body
402
+ with gr.Blocks(js=force_light, theme=theme, css=custom_css) as inference:
403
+ with gr.Row(elem_id="top-row"):
404
+ gr.HTML(
405
+ """
406
+ <div style="text-align: left;">
407
+ <a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FYuXingyao%2FHoLa-BRep">
408
+ <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FYuXingyao%2FHoLa-BRep&labelColor=%23d9e3f0&countColor=%23555555" />
409
+ </a>
410
+ </div>
411
+ """
412
+ )
413
+
414
+ with gr.Row(elem_id="button-group"):
415
+ btn_cn = gr.Button("中文", elem_classes="small-button")
416
+ btn_en = gr.Button("English", elem_classes="small-button")
417
+ btn_cn.click(fn=make_Chinese_descriptions, outputs=descriptions)
418
+ btn_en.click(fn=make_English_descriptions, outputs=descriptions)
419
+
420
+ title_en.render()
421
+ descriptions.append(title_en)
422
+
423
+ description_en.render()
424
+ descriptions.append(description_en)
425
+
426
+ user_state = gr.BrowserState({
427
+ "user_id" : None,
428
+ "user_output_dir" : None,
429
+ })
430
+
431
+ generating_type.render()
432
+
433
+ with gr.Row():
434
+ # Input Column
435
+ with gr.Column() as input_col:
436
+ with gr.Tabs() as input_tab:
437
+ with gr.Tab("Unconditional") as uncond_tab:
438
+ uncond_layout = UncondLayout()
439
+ uncond_description = uncond_layout.get_English_note()
440
+ descriptions.append(uncond_description)
441
+ uncond_input_components = uncond_layout.get_input_components()
442
+
443
+ uncond_button = gr.Button("Generate")
444
+ uncond_button.click(
445
+ fn=UncondGeneratingMethod().generate(),
446
+ inputs=[*uncond_input_components, user_state],
447
+ outputs=[model_wireframe, model_solid, step_file, download_files, user_state]
448
+ )
449
+
450
+ with gr.Tab("Point Cloud") as pc_tab:
451
+ pc_layout = PCLayout()
452
+ pc_description = pc_layout.get_English_note()
453
+ descriptions.append(pc_description)
454
+ pc_input_components = pc_layout.get_input_components()
455
+
456
+ pc_button = gr.Button("Generate")
457
+ pc_button.click(
458
+ fn=ConditionedGeneratingMethod(PointCloudDirector(), PointCloudProcessor(), DEMO_NUM).generate(),
459
+ inputs=[user_state, *pc_input_components],
460
+ outputs=[user_state, model_wireframe, model_solid, step_file, download_files]
461
+ )
462
+
463
+ with gr.Tab("Sketch") as sketch_tab:
464
+ sketch_layout = SketchLayout()
465
+ sketch_description = sketch_layout.get_English_note()
466
+ descriptions.append(sketch_description)
467
+ sketch_input_components = sketch_layout.get_input_components()
468
+
469
+ sketch_button = gr.Button("Generate")
470
+ sketch_button.click(
471
+ fn=ConditionedGeneratingMethod(SketchDirector(), SingleImageProcessor(), DEMO_NUM).generate(),
472
+ inputs=[user_state, *sketch_input_components],
473
+ outputs=[user_state, model_wireframe, model_solid, step_file, download_files]
474
+ )
475
+
476
+ with gr.Tab("Text") as text_tab:
477
+ text_layout = TextLayout()
478
+ text_description = text_layout.get_English_note()
479
+ descriptions.append(text_description)
480
+ text_input_components = text_layout.get_input_components()
481
+
482
+ text_button = gr.Button("Generate")
483
+ text_button.click(
484
+ fn=ConditionedGeneratingMethod(TextDirector(), TextProcessor(), DEMO_NUM).generate(),
485
+ inputs=[user_state, *text_input_components],
486
+ outputs=[user_state, model_wireframe, model_solid, step_file, download_files]
487
+ )
488
+
489
+ with gr.Tab("SVR") as svr_tab:
490
+ svr_layout = SVRLayout()
491
+ svr_description = svr_layout.get_English_note()
492
+ descriptions.append(svr_description)
493
+ svr_input_components = svr_layout.get_input_components()
494
+
495
+ svr_button = gr.Button("Generate")
496
+ svr_button.click(
497
+ fn=ConditionedGeneratingMethod(SVRDirector(), SingleImageProcessor(), DEMO_NUM).generate(),
498
+ inputs=[user_state, *svr_input_components],
499
+ outputs=[user_state, model_wireframe, model_solid, step_file, download_files]
500
+ )
501
+
502
+ with gr.Tab("MVR") as mvr_tab:
503
+ mvr_layout = MVRLayout()
504
+ mvr_description = mvr_layout.get_English_note()
505
+ descriptions.append(mvr_description)
506
+ with gr.Accordion("MVR input notification:", open=False) as mvr_notification:
507
+ notification_mvr_en.render()
508
+ gr.Image(value='app/examples/mvr.png',show_download_button=False, show_label=False,show_share_button=False,interactive=False)
509
+
510
+ with gr.Row():
511
+ mvr_input_components = mvr_layout.get_input_components()
512
+ mvr_button = gr.Button("Generate")
513
+ mvr_button.click(
514
+ fn=ConditionedGeneratingMethod(MVRDirector(), MultiImageProcessor(), DEMO_NUM).generate(),
515
+ inputs=[user_state, *mvr_input_components],
516
+ outputs=[user_state, model_wireframe, model_solid, step_file, download_files]
517
+ )
518
+
519
+ uncond_tab.select(fn=set_generating_type, inputs=gr.Text(uncond_tab.label, visible=False), outputs=generating_type)
520
+ pc_tab.select(fn=set_generating_type, inputs=gr.Text(pc_tab.label, visible=False), outputs=generating_type)
521
+ sketch_tab.select(fn=set_generating_type, inputs=gr.Text(sketch_tab.label, visible=False), outputs=generating_type)
522
+ svr_tab.select(fn=set_generating_type, inputs=gr.Text(svr_tab.label, visible=False), outputs=generating_type)
523
+ mvr_tab.select(fn=set_generating_type, inputs=gr.Text(mvr_tab.label, visible=False), outputs=generating_type)
524
+ text_tab.select(fn=set_generating_type, inputs=gr.Text(text_tab.label, visible=False), outputs=generating_type)
525
+
526
+ descriptions.append(notification_mvr_en)
527
+ descriptions.append(uncond_tab)
528
+ descriptions.append(pc_tab)
529
+ descriptions.append(sketch_tab)
530
+ descriptions.append(text_tab)
531
+ descriptions.append(svr_tab)
532
+ descriptions.append(mvr_tab)
533
+ descriptions.append(mvr_notification)
534
+ descriptions.append(uncond_button)
535
+ descriptions.append(pc_button)
536
+ descriptions.append(sketch_button)
537
+ descriptions.append(text_button)
538
+ descriptions.append(svr_button)
539
+ descriptions.append(mvr_button)
540
+
541
+
542
+ # Output demonstration
543
+ with gr.Column() as output_col:
544
+ with gr.Tabs():
545
+ with gr.Tab("Solid") as solid_tab:
546
+ model_solid.render()
547
+ with gr.Tab("Wireframe") as wireframe_tab:
548
+ model_wireframe.render()
549
+ with gr.Tab("Download") as download_tab:
550
+ step_file.render()
551
+ download_files.render()
552
+
553
+
554
+ model_index = gr.Number(value=0, visible=False)
555
+ with gr.Row() as switch_row:
556
+ last_button = gr.Button("Last")
557
+ next_button = gr.Button("Next")
558
+
559
+ last_button.click(
560
+ fn=switch_model,
561
+ inputs=[user_state, generating_type, model_index, gr.Number(-1, visible=False)],
562
+ outputs=[model_index, model_wireframe, model_solid, download_files])
563
+ next_button.click(
564
+ fn=switch_model,
565
+ inputs=[user_state, generating_type, model_index, gr.Number(1, visible=False)],
566
+ outputs=[model_index, model_wireframe, model_solid, download_files])
567
+
568
+ descriptions.append(last_button)
569
+ descriptions.append(next_button)
570
+ descriptions.append(solid_tab)
571
+ descriptions.append(wireframe_tab)
572
+ descriptions.append(download_tab)
573
+
574
+ # Examples
575
+ @gr.render(inputs=[generating_type], triggers=[generating_type.change, inference.load])
576
+ def show_examples(generate_mode):
577
+ if generate_mode == "Unconditional":
578
+ pass
579
+
580
+ elif generate_mode == "Point Cloud":
581
+ pc_samples=[
582
+ [Path("app/examples/pc_examples") / sample_number / "pc.png"] for sample_number in os.listdir("app/examples/pc_examples") if sample_number != "take_photo.py"
583
+ ]
584
+ with gr.Row():
585
+ def dummy_pc_func(pic_path):
586
+ return Path(pic_path[0]).with_suffix(".ply").as_posix()
587
+ for i in range(len(pc_samples)):
588
+ with gr.Column(min_width=100):
589
+ dummy_image = gr.Image(type="filepath", format="png", visible=False)
590
+ point_cloud_data = gr.Dataset(
591
+ label=f"Example{i+1}",
592
+ components=[dummy_image],
593
+ samples=[pc_samples[i]],
594
+ layout="table"
595
+ )
596
+ point_cloud_data.click(dummy_pc_func, inputs=point_cloud_data, outputs=pc_input_components)
597
+
598
+ elif generate_mode == "Text":
599
+ text_data = gr.Dataset(
600
+ components=text_input_components,
601
+ samples=[
602
+ ["The object is a rectangular prism with two protruding L-shaped sections on opposite sides."],
603
+ ["This design creates a rectangular plate with rounded edges. The plate measures about 0.3214 units in length, 0.75 units in width, and 0.0429 units in height. The rounded edges give the plate a smooth, aesthetically pleasing appearance."],
604
+ ["The U-shaped bracket has a flat top and a curved bottom. The design begins by creating a new coordinate system with specific Euler angles and a translation vector. A two-dimensional sketch is then drawn, forming a complex shape with multiple lines and arcs. This sketch is scaled down, rotated, and translated to align with the coordinate system. The sketch is extruded to create a three-dimensional model. The final dimensions of the bracket are approximately 0.7 units in length, 0.75 units in width, and 0.19 units in height. The bracket is designed to integrate seamlessly with other components, providing a sturdy and functional structure."]
605
+ ],
606
+ layout='table',
607
+ label="Examples",
608
+ headers=["Prompt"]
609
+ )
610
+ def dummy_func(text):
611
+ return gr.Text(text[0])
612
+ text_data.click(fn=dummy_func, inputs=text_data, outputs=text_input_components)
613
+
614
+ elif generate_mode == "Sketch":
615
+ with gr.Row():
616
+ for i in range(12):
617
+ with gr.Column(min_width=100):
618
+ example = gr.Examples(
619
+ inputs=sketch_input_components,
620
+ examples=[
621
+ [f"app/examples/sketch_examples/{i + 1}.png"]
622
+ ],
623
+ label=f"Example{i+1}"
624
+ )
625
+
626
+ elif generate_mode == "SVR":
627
+ with gr.Row():
628
+ for i in range(12):
629
+ with gr.Column(min_width=100):
630
+ example = gr.Examples(
631
+ inputs=svr_input_components,
632
+ examples=[
633
+ [f"app/examples/svr_examples/{i + 1}.png"]
634
+ ],
635
+ label=f"Example{i+1}"
636
+ )
637
+
638
+ elif generate_mode == "MVR":
639
+ with gr.Row():
640
+ for i in range(4):
641
+ file_num = ["00017462", "00131007", "00189220", "00218887"]
642
+ with gr.Column():
643
+ example = gr.Examples(
644
+ inputs=mvr_input_components,
645
+ examples=[
646
+ [f"app/examples/mvr_examples/{file_num[i]}_img0.png", f"app/examples/mvr_examples/{file_num[i]}_img1.png", f"app/examples/mvr_examples/{file_num[i]}_img2.png", f"app/examples/mvr_examples/{file_num[i]}_img3.png"],
647
+ ],
648
+ label=f"Example{i+1}"
649
+ )
650
+
651
+ citation_en.render()
652
+ descriptions.append(citation_en)
653
+
654
+
655
+ if __name__ == "__main__":
656
+ inference.launch(allowed_paths=['/data'], server_name='0.0.0.0', server_port=7860)
app/AppLayout.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ import gradio as gr
4
+ from typing import List, Callable
5
+ from abc import ABC, abstractmethod
6
+
7
+ # Tab Interface
8
+ class AppLayout(ABC):
9
+ @abstractmethod
10
+ def get_English_note(self) -> gr.Markdown:
11
+ pass
12
+
13
+ @abstractmethod
14
+ def get_Chinese_note(self):
15
+ pass
16
+
17
+ @abstractmethod
18
+ def get_input_components(self) -> List[gr.Component]:
19
+ pass
20
+
21
+
22
+ # Concrete Implementation
23
+ class UncondLayout(AppLayout):
24
+
25
+ def get_English_note(self):
26
+ return gr.Markdown(
27
+ """
28
+ **Note:**
29
+
30
+ + We generate 4 BRep models from sampled noise in Gaussian distribution.
31
+ + The model is trained on ABC dataset with a complexity range of 10~100 surface primitives.
32
+ + Compared with the state-of-the-art BRep generation methods, HoLa-BRep has a 20%-40% improvement in the validity ratio of the generated models on both the DeepCAD dataset and the ABC dataset.
33
+ + Try to adjust the seed for various results.
34
+
35
+ <br>
36
+ <br>
37
+ <br>
38
+ <br>
39
+ <br>
40
+ <br>
41
+ <br>
42
+ <br>
43
+ """
44
+ )
45
+
46
+ def get_Chinese_note(self):
47
+ return gr.Markdown(
48
+ """
49
+ **无条件生成介绍:**
50
+
51
+ + 我们从高斯分布的采样噪声中生成 4 个 BRep 模型。
52
+ + 模型在 ABC 数据集上进行训练,复杂度范围为 10~100 个表面基元。
53
+ + 与最先进的 BRep 生成方法相比,HoLa-BRep 在 DeepCAD 数据集和 ABC 数据集上生成模型的有效率提高了 20%-40%。
54
+ + 请随意调整采样种子,以获得不同的结果。
55
+
56
+ <br>
57
+ <br>
58
+ <br>
59
+ <br>
60
+ <br>
61
+ <br>
62
+ <br>
63
+ <br>
64
+ """
65
+ )
66
+
67
+ def get_input_components(self) -> List[gr.Component]:
68
+ return [
69
+ gr.Number(
70
+ label="Seed",
71
+ value=int(time.time()),
72
+ minimum=0,
73
+ maximum=2**31-1,
74
+ step=1
75
+ ),
76
+ ]
77
+
78
+
79
+ class TextLayout(AppLayout):
80
+
81
+ def get_English_note(self):
82
+ return gr.Markdown(
83
+ """
84
+ **Note:**
85
+
86
+ + Text can be either abstract or descriptive.
87
+ + We use a frozen gte-large-en-v1.5 to extract the feature from the text description.
88
+ + While we use the existing Text2CAD dataset which contains more descriptive text, the out of distribution abstract text prompt also works.
89
+
90
+ <br>
91
+ <br>
92
+ """
93
+ )
94
+ def get_Chinese_note(self):
95
+ return gr.Markdown(
96
+ """
97
+ **文本条件生成介绍:**
98
+
99
+ + HoLa-BRep支持简单抽象的文本和复杂的描述性文本。
100
+ + 我们使用冻结的gte-large-en-v1.5从文本描述中提取特征。
101
+ + 虽然我们使用的是包含更多复杂描述性文本的Text2CAD 数据集,但HoLa-BRep同样适用于简单抽象的文本输入。
102
+ + **当前文本输入仅支持英文,敬请谅解。**
103
+
104
+ <br>
105
+ """
106
+ )
107
+
108
+ def get_input_components(self) -> List[gr.Component]:
109
+ return [
110
+ gr.Textbox(lines = 8,max_length=1024, label="Text"),
111
+ ]
112
+
113
+
114
+ class PCLayout(AppLayout):
115
+
116
+ def get_English_note(self):
117
+ return gr.Markdown(
118
+ """
119
+ **Note:**
120
+
121
+ + The input point cloud should be in .ply format with the position in -1~+1 and normal vectors.
122
+ + The input point cloud can be either sparse or dense. We will downsample the point cloud into 2048 points.
123
+ + After test-time augmentation the validity of the generated B-Rep model can reach ~98%.
124
+ + We use a small and trainable PointNet++ to extract the feature from the point cloud.
125
+ + This checkpoint is only for a clean point cloud without any noise.
126
+ + Point cloud contains less ambiguity and usually yields the best conditional generation results compared to other modalities.
127
+ """
128
+ )
129
+ def get_Chinese_note(self):
130
+ return gr.Markdown(
131
+ """
132
+ **点云条件生成介绍:**
133
+
134
+ + HoLa-BRep接受.ply 格式的点云输入,且坐标值应该归一化到-1~+1并带有法向信息。
135
+ + HoLa-BRep接受稀疏或密集点云,网络处理点云时会将其降采样到2048 个点。
136
+ + 经过测试时增强后点云条件生成的有效性可达98%以上。
137
+ + 我们使用一个小型可训练的 PointNet++ 从点云中提取特征。
138
+ + 目前开放权重仅���持没有任何噪声的点云。
139
+ + 三维点云作为条件输入具有更少的歧义性,与其他条件相比通常能产生最佳的生成结果。
140
+ """
141
+ )
142
+
143
+ def get_input_components(self):
144
+ return [
145
+ gr.File(
146
+ label='PC',
147
+ file_count='single',
148
+ ),
149
+ ]
150
+
151
+
152
+ class SketchLayout(AppLayout):
153
+
154
+ def get_English_note(self):
155
+ return gr.Markdown(
156
+ """
157
+ **Note:**
158
+
159
+ + The input sketch is in 1:1 ratio and on a white background, it will be further downsampled to 224*224 before feeding into the network.
160
+ + The input sketch should be a perspective projection rather than an orthogonal projection.
161
+ + We use a frozen DINOv2 to extract the feature from the sketch image.
162
+ + We obtained the training sketches using wireframe rendering in OpenCascade.
163
+
164
+ <br>
165
+ <br>
166
+ """
167
+ )
168
+
169
+ def get_Chinese_note(self):
170
+ return gr.Markdown(
171
+ """
172
+ **线框图条件生成介绍:**
173
+
174
+ + 输入线框图的长宽比应为1:1,背景为白色,系统处理时会降采样到224*224分辨率。
175
+ + 输入的线框图应该是透视投影,而不是正交投影。
176
+ + 我们使用冻结的 DINOv2 从线框图图像中提取特征。
177
+ + 我们使用 OpenCascade 中的线框渲染来获取训练线框图。
178
+
179
+ <br>
180
+ <br>
181
+ """
182
+ )
183
+
184
+ def get_input_components(self) -> List[gr.Component]:
185
+ return [
186
+ gr.Image(
187
+ label='Sketch',
188
+ type='filepath',
189
+ sources=["upload"],
190
+ interactive=True,
191
+ )
192
+ ]
193
+
194
+
195
+ class SVRLayout(AppLayout):
196
+
197
+ def get_English_note(self):
198
+ return gr.Markdown(
199
+ """
200
+ **Note:**
201
+
202
+ + The input image is in 1:1 ratio and on a white background, it will be further downsampled to 224*224 before feeding into the network.
203
+ + Keep the object in grey for better generation results.
204
+ + We use a frozen DINOv2 to extract the feature from the sketch image.
205
+ + We obtained the training images using solid rendering in OpenCascade.
206
+
207
+ <br>
208
+ <br>
209
+ """
210
+ )
211
+
212
+ def get_Chinese_note(self):
213
+ return gr.Markdown(
214
+ """
215
+ **单视角图片条件生成介绍:**
216
+
217
+ + 输入图片的长宽比应为1:1,背景为白色,系统处理时会降采样到224*224分辨率。
218
+ + 为了获得更好的生成效果,请将对象保持为灰色。
219
+ + 我们使用冻结的 DINOv2 从草图图像中提取特征。
220
+ + 我们使用 OpenCascade 中的实体渲染来获取训练图像。
221
+
222
+ <br>
223
+ <br>
224
+ """
225
+ )
226
+
227
+ def get_input_components(self) -> List[gr.Component]:
228
+ return [
229
+ gr.Image(
230
+ label='Image',
231
+ type='filepath',
232
+ sources=["upload"],
233
+ interactive=True,
234
+ ),
235
+ ]
236
+
237
+
238
+ class MVRLayout(AppLayout):
239
+
240
+ def get_English_note(self):
241
+ return gr.Markdown(
242
+ """
243
+ **Note:**
244
+
245
+ + Similar to the single-view condition, the input image should be in 1:1 ratio and 4 fixed angles, **see the camera pose schematic**.
246
+ + Image features are extracted by a frozen DINOv2 and averaged after adding the positional encoding on the camera **pose** embedding.
247
+ """
248
+ )
249
+
250
+ def get_Chinese_note(self):
251
+ return gr.Markdown(
252
+ """
253
+ **多视角图片条件生成介绍:**
254
+
255
+ + 与单视角条件类似,输入图像应为 1:1长宽比和4 个固定角度,**见相机位姿示意图**。
256
+ + 图像特征由冻结的 DINOv2 提取,并在对相机**位姿**特征进行位置编码后取平均值。
257
+
258
+ """
259
+ )
260
+
261
+ def get_input_components(self) -> List[gr.Component]:
262
+ return [
263
+ gr.Image(
264
+ label='View1',
265
+ type='filepath',
266
+ interactive=True,
267
+ sources=["upload"]
268
+ ),
269
+ gr.Image(
270
+ label='View2',
271
+ type='filepath',
272
+ interactive=True,
273
+ sources=["upload"]
274
+
275
+ ),
276
+ gr.Image(
277
+ label='View3',
278
+ type='filepath',
279
+ interactive=True,
280
+ sources=["upload"]
281
+
282
+ ),
283
+
284
+ gr.Image(
285
+ label='View4',
286
+ type='filepath',
287
+ interactive=True,
288
+ sources=["upload"]
289
+
290
+ ),
291
+ ]
app/DataProcessor/DataProcessor.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import open3d as o3d
4
+ import torchvision.transforms as T
5
+ from PIL import Image
6
+ from pathlib import Path
7
+ from abc import abstractmethod, ABC
8
+
9
+ class DataProcessor(ABC):
10
+ NUM_PROPOSALS = 16
11
+
12
+ def __init__(self, device=None):
13
+ if device is None:
14
+ self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ else:
16
+ self._device = device
17
+
18
+ def process(self, input_data):
19
+ data = dict()
20
+ data["conditions"] = self.process_input_data(input_data)
21
+ return data
22
+
23
+ @abstractmethod
24
+ def process_input_data(self, input_data):
25
+ pass
app/DataProcessor/ImageProcessor.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torchvision.transforms as T
4
+
5
+ from pathlib import Path
6
+ from PIL import Image
7
+ from pathlib import Path
8
+ from app.DataProcessor.DataProcessor import DataProcessor
9
+
10
+ class ImageProcessor(DataProcessor):
11
+ def _get_img_tensor(self, image_file: Path) -> torch.Tensor:
12
+ """
13
+ Return a (3, 224, 224) shape tensor
14
+ """
15
+ transform = T.Compose([
16
+ T.ToPILImage(),
17
+ T.Resize((224, 224)),
18
+ T.ToTensor(),
19
+ T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
20
+ ])
21
+ img = np.array(Image.open(Path(image_file)).convert("RGB"))
22
+ img = transform(img).to(self._device)
23
+ return img
app/DataProcessor/MultiImageProcessor.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torchvision.transforms as T
4
+
5
+ from pathlib import Path
6
+ from typing import Tuple
7
+ from app.DataProcessor.ImageProcessor import ImageProcessor
8
+
9
+ class MultiImageProcessor(ImageProcessor):
10
+ def process_input_data(self, image_files: Tuple[str]):
11
+ multi_imgs = None
12
+ for one_imgage in image_files:
13
+ single_img = self._get_img_tensor(Path(one_imgage))[None, None, ...]
14
+ if multi_imgs is None:
15
+ multi_imgs = single_img
16
+ else:
17
+ multi_imgs = torch.cat((multi_imgs, single_img), axis=1)
18
+ multi_imgs = multi_imgs.repeat(self.NUM_PROPOSALS, 1, 1, 1, 1)
19
+ img_id = torch.tensor([list(range(len(image_files)))], device=self._device).repeat(self.NUM_PROPOSALS, 1)
20
+ return {
21
+ "imgs" : multi_imgs,
22
+ "img_id" : img_id
23
+ }
app/DataProcessor/PointCloudProcessor.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import open3d as o3d
4
+ from pathlib import Path
5
+ from app.DataProcessor.DataProcessor import DataProcessor
6
+
7
+ '''
8
+ Raw Data should be a Pathlike or str path, accept file path only
9
+ '''
10
+ class PointCloudProcessor(DataProcessor):
11
+ PC_DOWNSAMPLE_NUM = 4096
12
+ def process_input_data(self, pc_file_path):
13
+ points_tensor = self._get_point_cloud_tensor(Path(pc_file_path[0]))
14
+ return {"points" : points_tensor[None, None, :, :].repeat(self.NUM_PROPOSALS, 1, 1, 1)}
15
+
16
+ def _get_point_cloud_tensor(self, input_file: Path | str) -> torch.Tensor:
17
+ # Read point cloud
18
+ pcd = o3d.io.read_point_cloud(input_file)
19
+ points = np.array(pcd.points)
20
+
21
+ # Check normals
22
+ if pcd.has_normals():
23
+ normals = np.array(pcd.normals)
24
+ else:
25
+ normals = np.zeros_like(points)
26
+
27
+ # Concatenate points and normals
28
+ points = np.concatenate([self._normalize_points(points), normals], axis=1)
29
+
30
+ # Downsample
31
+ index = np.random.choice(points.shape[0], self.PC_DOWNSAMPLE_NUM, replace=False)
32
+ points = points[index]
33
+
34
+ return torch.tensor(points, dtype=torch.float32).to(self._device)
35
+
36
+ def _normalize_points(self, points):
37
+ bbox_min = np.min(points, axis=0)
38
+ bbox_max = np.max(points, axis=0)
39
+ center = (bbox_min + bbox_max) / 2
40
+ points -= center
41
+ scale = np.max(bbox_max - bbox_min)
42
+ points /= scale
43
+ points *= 0.9 * 2
44
+ return points
app/DataProcessor/SingleImageProcessor.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from pathlib import Path
4
+ from app.DataProcessor.ImageProcessor import ImageProcessor
5
+
6
+ class SingleImageProcessor(ImageProcessor):
7
+ def process_input_data(self, image_file : Path | str):
8
+ img = self._get_img_tensor(Path(image_file[0]))
9
+ img = img[None, None, :].repeat(self.NUM_PROPOSALS, 1, 1, 1, 1)
10
+ img_id = torch.tensor([[0]], device=self._device).repeat(self.NUM_PROPOSALS, 1)
11
+ return {
12
+ "imgs" : img,
13
+ "img_id" : img_id
14
+ }
app/DataProcessor/TxtProcessor.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from app.DataProcessor.DataProcessor import DataProcessor
2
+
3
+ class TextProcessor(DataProcessor):
4
+ def process_input_data(self, text: str):
5
+ return { "txt" : [text[0]] * self.NUM_PROPOSALS}
app/DataProcessor/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .DataProcessor import DataProcessor
2
+ from .ImageProcessor import ImageProcessor
3
+ from .MultiImageProcessor import MultiImageProcessor
4
+ from .PointCloudProcessor import PointCloudProcessor
5
+ from .SingleImageProcessor import SingleImageProcessor
6
+ from .TxtProcessor import TextProcessor
7
+
8
+ # __init__.py
9
+
10
+ # This package contains modules for processing data in the HoLa-Brep-Space application.
11
+ # Import necessary classes or functions here for easier access.
12
+
13
+
14
+ __all__ = ["DataProcessor", "ImageProcessor", "MultiImageProcessor", "PointCloudProcessor", "SingleImageProcessor", "TextProcessor"]
app/GeneratingMethod/ConditionedGenerating.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import uuid
4
+ import torch
5
+ import gradio as gr
6
+ import numpy as np
7
+ import ray
8
+ import time
9
+
10
+ from pathlib import Path
11
+
12
+ from diffusion.utils import export_edges
13
+ from construct_brep import construct_brep_from_datanpz
14
+ from app.DataProcessor import DataProcessor
15
+ from app.ModelDirector import ModelDirector
16
+
17
+ _EDGE_FILE = 0
18
+ _SOLID_FILE = 1
19
+ _STEP_FILE = 2
20
+
21
+ class ConditionedGeneratingMethod():
22
+ def __init__(
23
+ self,
24
+ model_building_director: ModelDirector,
25
+ dataprocessor: DataProcessor,
26
+ model_num_to_return: int,
27
+ model_seed: int = 0,
28
+ output_main_dir: Path | str = Path('./outputs')
29
+ ):
30
+ self.director = model_building_director
31
+ self.dataprocessor = dataprocessor
32
+ self.model_num_to_return = model_num_to_return
33
+ self.model_seed = model_seed
34
+ self.output_main_dir = output_main_dir
35
+
36
+ def generate(self):
37
+ def generating_method(browser_state: dict, *inputs):
38
+ try:
39
+ # Some checks
40
+ assert len(inputs) > 0
41
+ self._user_state_check(browser_state)
42
+ self._empty_input_check(inputs)
43
+
44
+ # Inference device(also shouldn't appear here)
45
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
46
+
47
+ # Process user input data
48
+ tensor_data = self.dataprocessor.process(inputs)
49
+
50
+ # Basic configuration of a model
51
+ self.director.config_setup()
52
+ model_builder = self.director.buider
53
+
54
+ # Should be refactored in the future since picking an output folder is not the responsibility of a model
55
+ diffusion_output_dir = self._get_diffusion_output_dir(browser_state, self.director.get_generating_condition())
56
+ postprocess_output_dir = self._get_postprocess_output_dir(browser_state, self.director.get_generating_condition())
57
+
58
+ model_builder.setup_output_dir(diffusion_output_dir)
59
+ model_builder.setup_seed(self.model_seed)
60
+
61
+ model_builder.make_model(device)
62
+ model = model_builder.model
63
+
64
+ #############
65
+ # Inference #
66
+ #############
67
+ gr.Info("Start diffusing", title="Runtime Info")
68
+ with torch.no_grad():
69
+ pred_results = model.inference(self.dataprocessor.NUM_PROPOSALS, device, v_data=tensor_data, v_log=True)
70
+
71
+ # Save intermediate files for post-processing
72
+ for i, result in enumerate(pred_results):
73
+ diffusion_output_subdir = diffusion_output_dir / f"00_{i:02d}"
74
+ diffusion_output_subdir.mkdir(parents=True, exist_ok=True)
75
+
76
+ export_edges(result["pred_edge"], (diffusion_output_subdir / "edge.obj").as_posix())
77
+
78
+ np.savez_compressed(
79
+ file = (diffusion_output_subdir / "data.npz").as_posix(),
80
+ pred_face_adj_prob = result["pred_face_adj_prob"],
81
+ pred_face_adj = result["pred_face_adj"].cpu().numpy(),
82
+ pred_face = result["pred_face"],
83
+ pred_edge = result["pred_edge"],
84
+ pred_edge_face_connectivity = result["pred_edge_face_connectivity"],
85
+ )
86
+ gr.Info("Finished diffusing", title="Runtime Info")
87
+
88
+ ###################
89
+ # Post-Processing #
90
+ ###################
91
+ # Multi-thread preparation
92
+ gr.Info("Start post-processing!", title="Runtime Info")
93
+ if not ray.is_initialized():
94
+ ray.init(
95
+ num_cpus=2,
96
+ )
97
+
98
+ construct_brep_from_datanpz_ray = ray.remote(num_cpus=1, max_retries=0)(construct_brep_from_datanpz)
99
+ diffusion_results = sorted(os.listdir(diffusion_output_dir))
100
+
101
+ tasks = [
102
+ construct_brep_from_datanpz_ray.remote(
103
+ data_root=diffusion_output_dir,
104
+ out_root=postprocess_output_dir,
105
+ folder_name=model_number,
106
+ v_drop_num=1,
107
+ use_cuda=False,
108
+ from_scratch=True,
109
+ is_log=False,
110
+ is_ray=True,
111
+ is_optimize_geom=True,
112
+ isdebug=False,
113
+ is_save_data=True
114
+ )
115
+ for model_number in diffusion_results
116
+ ]
117
+
118
+ results = []
119
+ success_count = 0
120
+ while tasks and success_count < self.model_num_to_return:
121
+ done_ids, tasks = ray.wait(tasks, num_returns=1, timeout=30)
122
+ for done_id in done_ids:
123
+ try:
124
+ result = ray.get(done_id)
125
+ results.append(result)
126
+
127
+ # Delay just a bit to ensure file handles are released
128
+ time.sleep(0.2)
129
+
130
+ # Check for 'success.txt' in output folders
131
+ for done_folder in postprocess_output_dir.iterdir():
132
+ output_files = os.listdir(done_folder)
133
+ if 'success.txt' in output_files:
134
+ success_count += 1
135
+
136
+ except Exception as e:
137
+ print(f"Task failed or timed out: {e}")
138
+ results.append(None)
139
+
140
+ if success_count >= self.model_num_to_return:
141
+ # Make sure the files are written successfully
142
+ time.sleep(5.0)
143
+ break
144
+ time.sleep(5.0)
145
+ gr.Info("Finished post-processing!", title="Runtime Info")
146
+ # Get valid model serial numbers
147
+ valid_models = self._get_valid_models(postprocess_output_dir)
148
+
149
+ #####################
150
+ # Update User State #
151
+ #####################
152
+ browser_state = self._update_user_state(browser_state, postprocess_output_dir, valid_models)
153
+
154
+ # Check if there's no valid output
155
+ self._postprocess_output_check(valid_models)
156
+
157
+
158
+ # Multi-thread processing may return valid models more than 4
159
+ gr.Info(f"{len(valid_models) if len(valid_models) < 4 else 4} valid models generated!", title="Finish generating")
160
+ condition = self.director.get_generating_condition()
161
+
162
+ # Return the first model as the default demonstration
163
+ edge_file = browser_state[condition][0][_EDGE_FILE]
164
+ solid_file = browser_state[condition][0][_SOLID_FILE]
165
+ step_file = browser_state[condition][0][_STEP_FILE]
166
+
167
+ return browser_state, edge_file, solid_file, step_file, browser_state[condition][0]
168
+
169
+ except EmptyInputException as input_e:
170
+ gr.Warning(str(input_e), title="Empty Input")
171
+
172
+ except GeneraingException as generating_e:
173
+ gr.Warning(str(generating_e), title="No Valid Generation")
174
+
175
+ except UnicodeEncodeError as uni_error:
176
+ gr.Warning("We sincerely apologize, but we currently only support English.", title="English Support Only")
177
+
178
+ except FileNotFoundError as file_e:
179
+ gr.Warning("The operation is too frequent!", title="Frequent Operation")
180
+
181
+ except Exception as e:
182
+ print(e)
183
+ gr.Warning("Something bad happened. Please try some other models", title="Unknown Error")
184
+
185
+ return browser_state, gr.update(), gr.update(), gr.update(), gr.update()
186
+
187
+ return generating_method
188
+
189
+ def _update_user_state(self, browser_state, postprocess_output_dir, valid_model):
190
+ # Unstable. May be refactored in the future
191
+ condition = self.director.get_generating_condition()
192
+ browser_state[condition] = list()
193
+ for i, model_number in enumerate(valid_model):
194
+ if (postprocess_output_dir / model_number / 'debug_face_loop' / 'optimized_edge.obj').exists():
195
+ edge = (postprocess_output_dir / model_number / 'debug_face_loop' / 'optimized_edge.obj').as_posix()
196
+ else:
197
+ edge = (postprocess_output_dir / model_number / 'debug_face_loop' / 'edge.obj').as_posix() # Hard coding is not good.
198
+ solid = (postprocess_output_dir / model_number / 'recon_brep.stl').as_posix()
199
+ step = (postprocess_output_dir / model_number / 'recon_brep.step').as_posix()
200
+ browser_state[condition].append([edge, solid, step])
201
+ return browser_state
202
+
203
+ def _postprocess_output_check(self, valid_model):
204
+ if len(valid_model) <= 0:
205
+ raise GeneraingException("No Valid Model Generated!")
206
+
207
+ def _empty_input_check(self, inputs):
208
+ for input_component in inputs:
209
+ if input_component is None:
210
+ raise EmptyInputException("Empty input exists!")
211
+
212
+ def _user_state_check(self, state_dict):
213
+ if state_dict['user_id'] is None:
214
+ state_dict['user_id'] = uuid.uuid4()
215
+ if state_dict['user_output_dir'] is None:
216
+ state_dict['user_output_dir'] = Path(self.output_main_dir) / f"user_{state_dict['user_id']}"
217
+ os.makedirs(state_dict['user_output_dir'], exist_ok=True)
218
+
219
+ def _get_valid_models(self, postprocess_output: Path):
220
+ # Get valid **model number** after post-processing
221
+ output_folders = [model_folder for model_folder in os.listdir(postprocess_output) if 'success.txt' in os.listdir(postprocess_output / model_folder)]
222
+ return output_folders
223
+
224
+ def _get_diffusion_output_dir(self, state_dict, condition):
225
+ # Create and clean the diffusion output directory
226
+ diffusion_output_dir = Path(state_dict['user_output_dir']) / condition
227
+ os.makedirs(diffusion_output_dir, exist_ok=True)
228
+ if len(os.listdir(diffusion_output_dir)) > 0:
229
+ shutil.rmtree(diffusion_output_dir)
230
+ return diffusion_output_dir
231
+
232
+ def _get_postprocess_output_dir(self, state_dict, condition):
233
+ # Create and clean the post-process output directory
234
+ postprocess_output_dir = Path(state_dict['user_output_dir']) / f'{condition}_post'
235
+ os.makedirs(postprocess_output_dir, exist_ok=True)
236
+ if len(os.listdir(postprocess_output_dir)) > 0:
237
+ shutil.rmtree(postprocess_output_dir)
238
+ return postprocess_output_dir
239
+
240
+ class GeneraingException(Exception):
241
+ """Custom exception if generating failed."""
242
+ pass
243
+
244
+ class EmptyInputException(Exception):
245
+ """Custom exception if the input is empty."""
246
+ pass
app/GeneratingMethod/UnconditionedGenerating.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import uuid
5
+ import gradio as gr
6
+
7
+ from pathlib import Path
8
+ from typing import Tuple
9
+
10
+ from app.inference import inference_batch_postprocess
11
+
12
+ # Should be refactored in the future
13
+ class UncondGeneratingMethod():
14
+ def __init__(self, output_main_dir=Path('./outputs')):
15
+ self.output_main_dir = output_main_dir
16
+
17
+ def generate(self):
18
+ def generate_uncond(seed, state: gr.BrowserState):
19
+ try:
20
+ state = check_user_output_dir(state, self.output_main_dir)
21
+
22
+ generate_output = Path(state['user_output_dir']) / 'unconditional'
23
+ os.makedirs(generate_output, exist_ok=True)
24
+ if len(os.listdir(generate_output)) > 0:
25
+ shutil.rmtree(generate_output)
26
+ os.makedirs(generate_output, exist_ok=True)
27
+
28
+ # Get the generated model
29
+ command = [
30
+ "python", "-m", "diffusion.train_diffusion",
31
+ "trainer.evaluate=true",
32
+ "trainer.batch_size=1000",
33
+ "trainer.gpu=1",
34
+ f"trainer.test_output_dir={generate_output.as_posix()}",
35
+ "trainer.resume_from_checkpoint=YuXingyao/HoLa-Brep/Diffusion_uncond_1100k.ckpt",
36
+ "trainer.num_worker=1",
37
+ "trainer.accelerator=\"32-true\"",
38
+ "trainer.exp_name=test",
39
+ "dataset.name=Dummy_dataset",
40
+ "dataset.length=32",
41
+ "dataset.num_max_faces=30",
42
+ "dataset.condition=None",
43
+ f"dataset.random_seed={seed}",
44
+ "model.name=Diffusion_condition",
45
+ "model.autoencoder_weights=YuXingyao/HoLa-Brep/AE_deepcad_1100k.ckpt",
46
+ "model.autoencoder=AutoEncoder_1119_light",
47
+ "model.with_intersection=true",
48
+ "model.in_channels=6",
49
+ "model.dim_shape=768",
50
+ "model.dim_latent=8",
51
+ "model.gaussian_weights=1e-6",
52
+ "model.pad_method=random",
53
+ "model.diffusion_latent=768",
54
+ "model.diffusion_type=epsilon",
55
+ "model.gaussian_weights=1e-6",
56
+ "model.condition=None",
57
+ "model.num_max_faces=30",
58
+ "model.beta_schedule=linear",
59
+ "model.addition_tag=false",
60
+ "model.name=Diffusion_condition"
61
+ ]
62
+ env = os.environ.copy()
63
+ env["CUDA_VISIBLE_DEVICES"] = "0"
64
+
65
+ gr.Info("Start diffusing", title="Runtime Info")
66
+ subprocess.run(command, check=True, env=env)
67
+ gr.Info("Finished diffusing", title="Runtime Info")
68
+
69
+ # Post-process the generated model
70
+ postprocess_output = Path(state['user_output_dir']) / 'unconditional_post'
71
+ os.makedirs(postprocess_output, exist_ok=True)
72
+ if len(os.listdir(postprocess_output)) > 0:
73
+ shutil.rmtree(postprocess_output)
74
+ os.makedirs(postprocess_output, exist_ok=True)
75
+
76
+ gr.Info("Start post-processing.", title="Runtime Info")
77
+ inference_batch_postprocess(
78
+ file_dir=generate_output.as_posix(),
79
+ output_dir=postprocess_output.as_posix(),
80
+ num_cpus=2,
81
+ drop_num=0
82
+ )
83
+ gr.Info("Finished post-processing!", title="Runtime Info")
84
+ valid_models = get_valid_models(postprocess_output)
85
+
86
+ # Should have valid outputs
87
+ if len(valid_models) <= 0:
88
+ raise UncondGeneraingException("No Valid Model Generated!")
89
+
90
+ # Update the user state
91
+ state["uncond"] = list()
92
+ for i, model_number in enumerate(valid_models):
93
+ if (postprocess_output / model_number / 'debug_face_loop' / 'optimized_edge.obj').exists():
94
+ edge = (postprocess_output / model_number / 'debug_face_loop' / 'optimized_edge.obj').as_posix()
95
+ else:
96
+ edge = (postprocess_output / model_number / 'debug_face_loop' / 'edge.obj').as_posix() # Hard coding is not good.
97
+ solid = (postprocess_output / model_number / 'recon_brep.stl').as_posix()
98
+ step = (postprocess_output / model_number / 'recon_brep.step').as_posix()
99
+ state["uncond"].append([edge, solid, step])
100
+
101
+ gr.Info(f"{len(valid_models) if len(valid_models) < 4 else 4} valid models generated!", title="Finish generating")
102
+
103
+ edge_file = state["uncond"][0][0]
104
+ solid_file = state["uncond"][0][1]
105
+ step_file = state["uncond"][0][2]
106
+ return edge_file, solid_file, step_file, state["uncond"][0], state
107
+ except UncondEmptyInputException as input_e:
108
+ gr.Warning(str(input_e), title="Empty Input")
109
+
110
+ except UncondGeneraingException as generating_e:
111
+ gr.Warning(str(generating_e), title="No Valid Generation")
112
+
113
+ except Exception as e:
114
+ print(e)
115
+ gr.Warning("Something bad happened. Please try some other models", title="Unknown Error")
116
+ return gr.update(), gr.update(), gr.update(), gr.update(), state
117
+
118
+ return generate_uncond
119
+
120
+ def get_valid_models(postprocess_output: Path) -> Tuple[Path, Path, Path]:
121
+ output_folders = [model_folder for model_folder in os.listdir(postprocess_output) if 'success.txt' in os.listdir(postprocess_output / model_folder)]
122
+ return output_folders
123
+
124
+ def check_user_output_dir(state: dict, output_dir):
125
+ if state['user_id'] is None:
126
+ state['user_id'] = uuid.uuid4()
127
+ if state['user_output_dir'] is None:
128
+ state['user_output_dir'] = Path(output_dir) / f"user_{state['user_id']}"
129
+ os.makedirs(state['user_output_dir'], exist_ok=True)
130
+ return state
131
+
132
+ class UncondGeneraingException(Exception):
133
+ """Custom exception if generating failed."""
134
+ pass
135
+
136
+ class UncondEmptyInputException(Exception):
137
+ """Custom exception if the input is empty."""
138
+ pass
app/GeneratingMethod/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .ConditionedGenerating import ConditionedGeneratingMethod
2
+ from .UnconditionedGenerating import UncondGeneratingMethod
3
+
4
+ __all__ = ["ConditionedGeneratingMethod", "UncondGeneratingMethod"]
app/ModelBuilder.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from pathlib import Path
3
+ from typing import Optional
4
+ from lightning_fabric import seed_everything
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ from diffusion.diffusion_model import Diffusion_condition
8
+
9
+
10
+ '''
11
+ Steps to make a model:
12
+ 1. Set up the model structure depending on the modal
13
+ 2. Set up AutoEncoder weights
14
+ 3. Set up Diffusor weights
15
+ *. Set up the condition flag (Should be deleted in the future)
16
+ 4. Pick a random seed
17
+ **. Designate the output folder (Also should be deleted in the future, this is not the responsibility of a model!)
18
+ '''
19
+ class ModelBuilder():
20
+ NUM_PROPOSALS = 32
21
+ def __init__(self):
22
+ self.reset()
23
+
24
+ def set_up_model_template(self, model_class: Diffusion_condition):
25
+ # This shouldn't exist due to the Diffusion_condition's inheritence
26
+ self._model_class = model_class
27
+
28
+ # Theoretically, this function should be the true Builder API
29
+ # def set_up_modal(self, modal: Diffusion_condition):
30
+ # # Set up the modal for the model(pc, txt, sketch, svr, mvr)
31
+ # self._model_instance = modal
32
+
33
+ def setup_autoencoder_weights(self, weights_path: Path | str):
34
+ self._config["autoencoder_weights"] = weights_path
35
+
36
+ def setup_diffusion_weights(self, weights_path: Path | str):
37
+ self._config["diffusion_weights"] = weights_path
38
+
39
+ def setup_condition(self, condition: str):
40
+ self._config["condition"] = [condition]
41
+
42
+ def setup_seed(self, seed: Optional[int] = None):
43
+ if seed is not None:
44
+ seed_everything(seed)
45
+ else:
46
+ seed_everything(0)
47
+
48
+ def setup_output_dir(self, output_dir: Path | str):
49
+ self._config["output_dir"] = output_dir
50
+
51
+ def make_model(self, device: Optional[torch.device] = None):
52
+ # Torch condition
53
+ torch.backends.cudnn.benchmark = False
54
+ torch.set_float32_matmul_precision("medium")
55
+
56
+ # Device
57
+ if device is None:
58
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
59
+
60
+ # Set up modal for the model
61
+ # (Need to be refactored in the future)
62
+ self._model_instance = self._model_class(self._config)
63
+
64
+ # Load diffusion weights
65
+ repo_id = Path(self._config["diffusion_weights"]).parent.as_posix()
66
+ model_name = Path(self._config["diffusion_weights"]).name
67
+ model_weights = hf_hub_download(repo_id=repo_id, filename=model_name)
68
+ diffusion_weights = torch.load(model_weights, map_location=device, weights_only=False)["state_dict"]
69
+ diffusion_weights = {k: v for k, v in diffusion_weights.items() if "ae_model" not in k}
70
+ diffusion_weights = {k[6:]: v for k, v in diffusion_weights.items() if "model" in k}
71
+
72
+ # Load Autoencoder weights
73
+ AE_repo_id = Path(self._config["autoencoder_weights"]).parent.as_posix()
74
+ AE_model_name = Path(self._config["autoencoder_weights"]).name
75
+ AE_model_weights = hf_hub_download(repo_id=AE_repo_id, filename=AE_model_name)
76
+ autoencoder_weights = torch.load(AE_model_weights, map_location=device, weights_only=False)["state_dict"]
77
+ autoencoder_weights = {k[6:]: v for k, v in autoencoder_weights.items() if "model" in k}
78
+ autoencoder_weights = {"ae_model."+k: v for k, v in autoencoder_weights.items()}
79
+
80
+ # Combine ae with diffusor
81
+ diffusion_weights.update(autoencoder_weights)
82
+ diffusion_weights = {k: v for k, v in diffusion_weights.items() if "camera_embedding" not in k}
83
+
84
+ self._model_instance.load_state_dict(diffusion_weights, strict=False)
85
+ self._model_instance.to(device)
86
+ self._model_instance.eval()
87
+
88
+ return self._model_instance
89
+
90
+ def reset(self):
91
+ self._model_class = Diffusion_condition # This shouldn't exist. See set_up_model_template()
92
+ self._model_instance = None
93
+ # Basic model config()
94
+ self._config = {
95
+ "name": "Diffusion_condition",
96
+ "train_decoder": False,
97
+ "stored_z": False,
98
+ "use_mean": True,
99
+ "diffusion_latent": 768,
100
+ "diffusion_type": "epsilon",
101
+ "loss": "l2",
102
+ "pad_method": "random",
103
+ "num_max_faces": 30,
104
+ "beta_schedule": "squaredcos_cap_v2",
105
+ "beta_start": 0.0001,
106
+ "beta_end": 0.02,
107
+ "variance_type": "fixed_small",
108
+ "addition_tag": False,
109
+ "autoencoder": "AutoEncoder_1119_light",
110
+ "with_intersection": True,
111
+ "dim_latent": 8,
112
+ "dim_shape": 768,
113
+ "sigmoid": False,
114
+ "in_channels": 6,
115
+ "gaussian_weights": 1e-6,
116
+ "norm": "layer",
117
+ "autoencoder_weights": "",
118
+ "is_aug": False,
119
+ "condition": [],
120
+ "cond_prob": []
121
+ }
122
+
123
+ @property
124
+ def model(self):
125
+ model = self._model_instance
126
+ return model
app/ModelDirector/MVRDirector.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusion.diffusion_model import Diffusion_condition_mvr
2
+ from app.ModelDirector import ModelDirector
3
+
4
+
5
+ class MVRDirector(ModelDirector):
6
+ def get_ae_weights(self):
7
+ return 'YuXingyao/HoLa-Brep/AE_deepcad_1100k.ckpt'
8
+
9
+ def get_diffusion_weights(self):
10
+ return 'YuXingyao/HoLa-Brep/Diffusion_mvr_sq30_800k.ckpt'
11
+
12
+ def get_generating_condition(self):
13
+ return 'multi_img'
14
+ def config_setup(self):
15
+ # Bad smell, turly. Gonna refactor in the future... Hopefully...
16
+ super().config_setup()
17
+ self._builder.set_up_model_template(Diffusion_condition_mvr)
18
+
app/ModelDirector/ModelDirector.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Callable
2
+ from abc import ABC, abstractmethod
3
+ from app import ModelBuilder
4
+
5
+ '''
6
+ Direct the ModelBuilder to build a model depending on the modal the user choose
7
+ '''
8
+ class ModelDirector(ABC):
9
+ def __init__(
10
+ self,
11
+ builder: ModelBuilder = None,
12
+ additional_setup_fn: Optional[Callable[['ModelBuilder'], None]] = None
13
+ ):
14
+ if builder is None:
15
+ self._builder = ModelBuilder()
16
+ else:
17
+ self._builder = builder
18
+ self._additional_setup_fn = additional_setup_fn
19
+ self._ae_weights = self.get_ae_weights()
20
+ self._diffusion_weights = self.get_diffusion_weights()
21
+ self._condition = self.get_generating_condition()
22
+
23
+ def config_setup(self):
24
+ self._builder.setup_autoencoder_weights(self._ae_weights)
25
+ self._builder.setup_diffusion_weights(self._diffusion_weights)
26
+
27
+ # User defined setup
28
+ if self._additional_setup_fn:
29
+ self._additional_setup_fn(self._builder)
30
+
31
+ self._builder.setup_condition(self._condition)
32
+
33
+ @property
34
+ def buider(self):
35
+ return self._builder
36
+
37
+ @abstractmethod
38
+ def get_ae_weights(self):
39
+ pass
40
+
41
+ @abstractmethod
42
+ def get_diffusion_weights(self):
43
+ pass
44
+
45
+ @abstractmethod
46
+ def get_generating_condition(self):
47
+ pass
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
app/ModelDirector/PointCloudDirector.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.ModelDirector import ModelDirector
2
+
3
+ class PointCloudDirector(ModelDirector):
4
+ def get_ae_weights(self):
5
+ return 'YuXingyao/HoLa-Brep/AE_deepcad_1100k.ckpt'
6
+
7
+ def get_diffusion_weights(self):
8
+ return 'YuXingyao/HoLa-Brep/Diffusion_pc_sq30_1600k.ckpt'
9
+
10
+ def get_generating_condition(self):
11
+ return 'pc'
12
+
app/ModelDirector/SVRDirector.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.ModelDirector import ModelDirector
2
+
3
+ class SVRDirector(ModelDirector):
4
+ def get_ae_weights(self):
5
+ return 'YuXingyao/HoLa-Brep/AE_deepcad_1100k.ckpt'
6
+
7
+ def get_diffusion_weights(self):
8
+ return 'YuXingyao/HoLa-Brep/Diffusion_svr_sq30_1500k.ckpt'
9
+
10
+ def get_generating_condition(self):
11
+ return 'single_img'
12
+
app/ModelDirector/SketchDirector.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.ModelDirector import ModelDirector
2
+
3
+ class SketchDirector(ModelDirector):
4
+ def get_ae_weights(self):
5
+ return 'YuXingyao/HoLa-Brep/AE_deepcad_1100k.ckpt'
6
+
7
+ def get_diffusion_weights(self):
8
+ return 'YuXingyao/HoLa-Brep/Diffusion_sketch_sq30_1500k.ckpt'
9
+
10
+ def get_generating_condition(self):
11
+ return 'sketch'
12
+
app/ModelDirector/TextDirector.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.ModelDirector import ModelDirector
2
+
3
+ class TextDirector(ModelDirector):
4
+ def get_ae_weights(self):
5
+ return 'YuXingyao/HoLa-Brep/AE_deepcad_1100k.ckpt'
6
+
7
+ def get_diffusion_weights(self):
8
+ return 'YuXingyao/HoLa-Brep/Diffusion_txt_sq30_1000k.ckpt'
9
+
10
+ def get_generating_condition(self):
11
+ return 'txt'
12
+
app/ModelDirector/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .ModelDirector import ModelDirector
2
+ from .MVRDirector import MVRDirector
3
+ from .PointCloudDirector import PointCloudDirector
4
+ from .SketchDirector import SketchDirector
5
+ from .SVRDirector import SVRDirector
6
+ from .TextDirector import TextDirector
7
+
8
+ __all__ = ["ModelDirector", "MVRDirector", "PointCloudDirector", "SketchDirector", "SVRDirector", "TextDirector"]
app/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .ModelBuilder import ModelBuilder
2
+
3
+ # Maybe I can add something to make this module better. BUT IT WORKS NOW.
app/inference.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import ray
3
+ import time
4
+ from pathlib import Path
5
+
6
+ from construct_brep import construct_brep_from_datanpz
7
+
8
+ # This file still exists just because a UNSPEAKABLE evil class depends on it
9
+
10
+ def inference_batch_postprocess(file_dir: Path ,output_dir: Path, num_cpus: int=4, drop_num: int=2, timeout: int=60):
11
+ print("Start post-processing")
12
+
13
+ if not ray.is_initialized():
14
+ ray.init(
15
+ num_cpus=num_cpus,
16
+ )
17
+
18
+ construct_brep_from_datanpz_ray = ray.remote(num_cpus=1, max_retries=0)(construct_brep_from_datanpz)
19
+
20
+ all_folders = sorted(os.listdir(file_dir))
21
+
22
+ tasks = [
23
+ construct_brep_from_datanpz_ray.remote(
24
+ data_root=file_dir,
25
+ out_root=output_dir,
26
+ folder_name=model_number,
27
+ v_drop_num=1,
28
+ use_cuda=False,
29
+ from_scratch=True,
30
+ is_log=False,
31
+ is_ray=True,
32
+ is_optimize_geom=True,
33
+ isdebug=False,
34
+ is_save_data=True
35
+ )
36
+ for model_number in all_folders
37
+ ]
38
+
39
+
40
+ results = []
41
+ success_count = 0
42
+ while tasks and success_count < 4:
43
+ done_ids, tasks = ray.wait(tasks, num_returns=1, timeout=60)
44
+ for done_id in done_ids:
45
+ try:
46
+ result = ray.get(done_id)
47
+ results.append(result)
48
+
49
+ # Delay just a bit to ensure file handles are released
50
+ time.sleep(0.2)
51
+ # Check for 'success.txt' in output folders
52
+ for done_folder in Path(output_dir).iterdir():
53
+ output_files = os.listdir(done_folder)
54
+ if 'success.txt' in output_files:
55
+ success_count += 1
56
+
57
+ except Exception as e:
58
+ print(f"Task failed or timed out: {e}")
59
+ results.append(None)
60
+ if success_count >= 4:
61
+ # Make sure the files are written successfully
62
+ time.sleep(5.0)
63
+ break
64
+ time.sleep(5.0)
65
+ print("Finished post-processing")
construct_brep.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import itertools
3
+ import math
4
+ import os, sys, shutil, traceback
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ from OCC.Core import Message
10
+ from OCC.Core.Geom import Geom_BSplineSurface
11
+ from OCC.Core.IFSelect import IFSelect_ReturnStatus
12
+ from OCC.Core.IGESControl import IGESControl_Writer
13
+ from OCC.Core.Interface import Interface_Static
14
+ from OCC.Core.Message import Message_PrinterOStream, Message_Alarm
15
+ from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_AsIs, STEPControl_ManifoldSolidBrep, \
16
+ STEPControl_FacetedBrep, STEPControl_ShellBasedSurfaceModel
17
+ from OCC.Core.ShapeFix import ShapeFix_ShapeTolerance
18
+ from OCC.Core.TopAbs import TopAbs_SHAPE
19
+ from OCC.Core.TopoDS import TopoDS_Face
20
+ from OCC.Extend.DataExchange import read_step_file
21
+
22
+ from diffusion.utils import *
23
+
24
+ import ray
25
+ import argparse
26
+ import trimesh
27
+
28
+ import time
29
+
30
+
31
+ def get_data(v_filename):
32
+ # specify the key to get the face points, edge points and edge_face_connectivity in data.npz
33
+ # data_npz = np.load(os.path.join(data_root, folder_name, 'data.npz'), allow_pickle=True)['arr_0'].item()
34
+ data_npz = np.load(v_filename, allow_pickle=True)
35
+ if 'sample_points_faces' in data_npz and 'edge_face_connectivity' in data_npz:
36
+ face_points = data_npz['sample_points_faces'] # Face sample points (num_faces*20*20*3)
37
+ edge_points = data_npz['sample_points_lines'] # Edge sample points (num_lines*20*3)
38
+ edge_face_connectivity = data_npz['edge_face_connectivity'] # (num_intersection, (id_edge, id_face1, id_face2))
39
+ elif 'pred_face' in data_npz and 'pred_edge_face_connectivity' in data_npz:
40
+ face_points = data_npz['pred_face']
41
+ edge_points = data_npz['pred_edge']
42
+ edge_face_connectivity = data_npz['pred_edge_face_connectivity']
43
+ elif 'pred_face' in data_npz and 'face_edge_adj' in data_npz:
44
+ face_points = data_npz['pred_face'].astype(np.float32)
45
+ edge_points = data_npz['pred_edge'].astype(np.float32)
46
+ face_edge_adj = data_npz['face_edge_adj']
47
+ edge_face_connectivity = []
48
+ N = face_points.shape[0]
49
+ for i in range(N):
50
+ for j in range(i + 1, N):
51
+ intersection = list(set(face_edge_adj[i]).intersection(set(face_edge_adj[j])))
52
+ if len(intersection) > 0:
53
+ edge_face_connectivity.append([intersection[0], i, j])
54
+ edge_face_connectivity = np.array(edge_face_connectivity)
55
+
56
+ else:
57
+ raise ValueError(f"Unknown data npz format {v_filename}")
58
+
59
+ face_points = face_points[..., :3]
60
+ edge_points = edge_points[..., :3]
61
+ shape = Shape(face_points, edge_points, edge_face_connectivity, False)
62
+ return shape
63
+
64
+
65
+ def get_candidate_shapes(num_drop, v_faces, v_curves, v_conn):
66
+ if num_drop == 0:
67
+ new_faces = [item for item in v_faces]
68
+ new_curves = [item for item in v_curves]
69
+ new_edge_face_connectivity = [item for item in v_conn]
70
+ return [(new_faces, new_curves, new_edge_face_connectivity)]
71
+ num_faces = len(v_faces)
72
+ candidate_shapes = []
73
+ drop_ids = list(itertools.combinations(range(num_faces), num_drop))
74
+
75
+ for drop_id in drop_ids:
76
+ preserved_ids = np.array(list(set(range(num_faces)) - set(drop_id)))
77
+ prev_id_to_new_id = {prev_id: new_id for new_id, prev_id in enumerate(preserved_ids)}
78
+ new_faces = [v_faces[idx] for idx in preserved_ids]
79
+ new_curves = [item for item in v_curves]
80
+ new_edge_face_connectivity = []
81
+ for edge_id, face_id1, face_id2 in v_conn:
82
+ if face_id1 in preserved_ids and face_id2 in preserved_ids:
83
+ new_edge_face_connectivity.append([edge_id, prev_id_to_new_id[face_id1], prev_id_to_new_id[face_id2]])
84
+ candidate_shapes.append((new_faces, new_curves, new_edge_face_connectivity))
85
+ return candidate_shapes
86
+
87
+
88
+ def construct_brep_from_datanpz(data_root, out_root, folder_name, v_drop_num=0,
89
+ is_ray=False, is_log=True,
90
+ is_optimize_geom=True, isdebug=False, use_cuda=False, from_scratch=True,
91
+ is_save_data=False):
92
+ disable_occ_log()
93
+ # is_log = False
94
+ # isdebug = False
95
+ time_records = [0, 0, 0, 0, 0, 0]
96
+ timer = time.time()
97
+ data_root = Path(data_root)
98
+ out_root = Path(out_root)
99
+ if from_scratch:
100
+ check_dir(out_root / folder_name)
101
+
102
+ # Check if it is already processed
103
+ if (out_root / folder_name / "success.txt").exists():
104
+ return time_records
105
+ safe_check_dir(out_root / folder_name)
106
+
107
+ debug_face_save_path = out_root / folder_name / "debug_face_loop"
108
+ if is_save_data:
109
+ safe_check_dir(debug_face_save_path)
110
+
111
+ if is_log:
112
+ print(
113
+ f"{Colors.GREEN}############################# Processing {folder_name} #############################{Colors.RESET}")
114
+
115
+ # Prepare the data
116
+ shape = get_data(os.path.join(data_root, folder_name, 'data.npz'))
117
+ if isdebug:
118
+ export_edges(shape.recon_edge_points, debug_face_save_path / 'edge_ori.obj')
119
+ shape.remove_half_edges()
120
+ shape.check_openness()
121
+ shape.build_fe()
122
+ shape.build_vertices(0.2)
123
+
124
+ if isdebug:
125
+ print(
126
+ f"{Colors.GREEN}Remove {len(shape.remove_edge_idx_src) + len(shape.remove_edge_idx_new)} edges{Colors.RESET}")
127
+
128
+ if is_save_data:
129
+ # export_point_cloud(os.path.join(debug_face_save_path, 'face.ply'), shape.recon_face_points.reshape(-1, 3))
130
+ updated_edge_points = np.delete(shape.recon_edge_points, shape.remove_edge_idx_new, axis=0)
131
+ export_edges(updated_edge_points, os.path.join(debug_face_save_path, 'edge.obj'))
132
+ # for face_idx in range(len(shape.face_edge_adj)):
133
+ # export_point_cloud(os.path.join(debug_face_save_path, f"face{face_idx}.ply"),
134
+ # shape.recon_face_points[face_idx].reshape(-1, 3))
135
+ # for edge_idx in shape.face_edge_adj[face_idx]:
136
+ # idx = np.where(shape.edge_face_connectivity[:, 0] == edge_idx)[0][0]
137
+ # adj_face = shape.edge_face_connectivity[idx][1:]
138
+ # export_point_cloud(
139
+ # os.path.join(debug_face_save_path, f"face{face_idx}_edge_idx{edge_idx}_face{adj_face}.ply"),
140
+ # shape.recon_edge_points[edge_idx].reshape(-1, 3),
141
+ # np.linspace([1, 0, 0], [0, 1, 0], shape.recon_edge_points[edge_idx].shape[0]))
142
+ # for edge_idx in range(len(shape.recon_edge_points)):
143
+ # if edge_idx in shape.remove_edge_idx_new:
144
+ # continue
145
+ # export_point_cloud(os.path.join(
146
+ # debug_face_save_path, f'edge{edge_idx}.ply'),
147
+ # shape.recon_edge_points[edge_idx].reshape(-1, 3),
148
+ # np.linspace([1, 0, 0], [0, 1, 0], shape.recon_edge_points[edge_idx].shape[0]))
149
+
150
+ # Optimize data
151
+ if is_optimize_geom:
152
+ interpolation_face = []
153
+ for item in shape.interpolation_face:
154
+ interpolation_face.append(item)
155
+
156
+ if not is_ray:
157
+ shape.recon_face_points, shape.recon_edge_points = optimize(
158
+ interpolation_face, shape.recon_edge_points, shape.recon_face_points,
159
+ shape.edge_face_connectivity, shape.is_end_point, shape.pair1,
160
+ shape.face_edge_adj, v_islog=isdebug, v_max_iter=50, use_cuda=use_cuda)
161
+ else:
162
+ shape.recon_face_points, shape.recon_edge_points = optimize(
163
+ shape.interpolation_face, shape.recon_edge_points, shape.recon_face_points,
164
+ shape.edge_face_connectivity, shape.is_end_point, shape.pair1,
165
+ shape.face_edge_adj, v_islog=False, v_max_iter=50, use_cuda=use_cuda)
166
+
167
+ if is_save_data:
168
+ updated_edge_points = np.delete(shape.recon_edge_points, shape.remove_edge_idx_new, axis=0)
169
+ export_edges(updated_edge_points, os.path.join(debug_face_save_path, 'optimized_edge.obj'))
170
+ # for face_idx in range(len(shape.face_edge_adj)):
171
+ # for edge_idx in shape.face_edge_adj[face_idx]:
172
+ # idx = np.where(shape.edge_face_connectivity[:, 0] == edge_idx)[0][0]
173
+ # adj_face = shape.edge_face_connectivity[idx][1:]
174
+ # export_point_cloud(
175
+ # os.path.join(debug_face_save_path,
176
+ # f"face{face_idx}_optim_edge_idx{edge_idx}_face{adj_face}.ply"),
177
+ # shape.recon_edge_points[edge_idx].reshape(-1, 3),
178
+ # np.linspace([1, 0, 0], [0, 1, 0], shape.recon_edge_points[edge_idx].shape[0]))
179
+ # export_point_cloud(debug_face_save_path / f'optim_face{face_idx}.ply',
180
+ # shape.recon_face_points[face_idx].reshape(-1, 3))
181
+ # for edge_idx in range(len(shape.recon_edge_points)):
182
+ # if edge_idx in shape.remove_edge_idx_new:
183
+ # continue
184
+ # export_point_cloud(
185
+ # os.path.join(debug_face_save_path, f'optim_edge{edge_idx}.ply'),
186
+ # shape.recon_edge_points[edge_idx].reshape(-1, 3),
187
+ # np.linspace([1, 0, 0], [0, 1, 0], shape.recon_edge_points[edge_idx].shape[0]))
188
+
189
+ ori_shape = copy.deepcopy(shape)
190
+
191
+ recon_geom_faces = [create_surface(points) for points in shape.recon_face_points]
192
+ recon_topo_faces = [
193
+ BRepBuilderAPI_MakeFace(geom_face, TRANSFER_PRECISION).Face() for geom_face in recon_geom_faces]
194
+ recon_geom_curves = [create_edge(points) for points in shape.recon_edge_points]
195
+ recon_topo_curves = [BRepBuilderAPI_MakeEdge(curve).Edge() for curve in recon_geom_curves]
196
+
197
+ shape.recon_geom_faces = [item for item in recon_geom_faces]
198
+ shape.recon_topo_faces = [item for item in recon_topo_faces]
199
+ shape.recon_geom_curves = [item for item in recon_geom_curves]
200
+ shape.recon_topo_curves = [item for item in recon_topo_curves]
201
+ shape.build_geom(is_replace_edge=True)
202
+ recon_topo_curves = [item for item in shape.recon_topo_curves]
203
+
204
+ # Write separate faces
205
+ v, f = get_separated_surface(shape.recon_topo_faces, v_precision1=0.1, v_precision2=0.2)
206
+ trimesh.Trimesh(vertices=v, faces=f).export(out_root / folder_name / "separate_faces.ply")
207
+
208
+ num_max_drop = min(v_drop_num, math.ceil(0.2 * len(ori_shape.recon_face_points)))
209
+ is_success = False
210
+
211
+ for num_drop in range(num_max_drop + 1):
212
+ candidate_shapes = get_candidate_shapes(num_drop, recon_geom_faces, recon_topo_curves, ori_shape.edge_face_connectivity)
213
+
214
+ for (faces, curves, connectivity) in candidate_shapes:
215
+ if len(faces) == 0:
216
+ if is_log:
217
+ print(f"{Colors.RED}No data in {folder_name}{Colors.RESET}")
218
+ # shutil.rmtree(os.path.join(out_root, folder_name))
219
+ continue
220
+
221
+ num_faces = len(faces)
222
+ face_edge_adj = [[] for _ in range(num_faces)]
223
+ for edge_face1_face2 in connectivity:
224
+ edge, face1, face2 = edge_face1_face2
225
+ if face1 == face2:
226
+ # raise ValueError("Face1 and Face2 should be different")
227
+ print("Face1 and Face2 should be different")
228
+ continue
229
+ assert edge not in face_edge_adj[face1]
230
+ face_edge_adj[face1].append(edge)
231
+ face_edge_adj[face2].append(edge)
232
+
233
+ # Construct trimmed surface
234
+ trimmed_faces = []
235
+ for i_face in range(num_faces):
236
+ if len(face_edge_adj[i_face]) == 0:
237
+ trimmed_faces.append(None)
238
+ continue
239
+ face_edge_idx = face_edge_adj[i_face]
240
+ geom_face = faces[i_face]
241
+ face_edges = [curves[edge_idx] for edge_idx in face_edge_idx]
242
+
243
+ # Build wire
244
+ trimmed_face = None
245
+ for threshold in CONNECT_TOLERANCE:
246
+ wire_list = create_wire_from_unordered_edges(face_edges, threshold)
247
+ if wire_list is None:
248
+ continue
249
+
250
+ trimmed_face = create_trimmed_face_from_wire(geom_face, face_edges, wire_list, threshold)
251
+ if trimmed_face is not None:
252
+ break
253
+
254
+ trimmed_faces.append(trimmed_face)
255
+
256
+ trimmed_faces = [face for face in trimmed_faces if face is not None]
257
+ if len(trimmed_faces) < 0.8 * num_faces:
258
+ continue
259
+
260
+ # Try construct solid from trimmed faces only
261
+ solid = None
262
+ if len(trimmed_faces) > 0.8 * num_faces:
263
+ for connected_tolerance in CONNECT_TOLERANCE:
264
+ if is_log:
265
+ print(f"Try construct solid with {connected_tolerance}")
266
+ solid = get_solid(trimmed_faces, connected_tolerance)
267
+ if solid is not None:
268
+ break
269
+
270
+ # Check solid
271
+ if solid is not None:
272
+ save_step_file(out_root / folder_name / 'recon_brep.step', solid)
273
+ if not check_step_valid_soild(str(out_root / folder_name / 'recon_brep.step')):
274
+ print("Inconsistent solid check in {}".format(folder_name))
275
+ os.remove(out_root / folder_name / 'recon_brep.step')
276
+ else:
277
+ write_stl_file(solid, str(out_root / folder_name / "recon_brep.stl"),
278
+ linear_deflection=0.1, angular_deflection=0.2)
279
+ open(out_root / folder_name / "success.txt", 'w').close()
280
+ is_success = True
281
+ break
282
+ if is_success:
283
+ break
284
+
285
+ # If solid is None, then try to obtain step file with all faces
286
+ if not is_success:
287
+ # Construct trimmed surface
288
+ num_faces = len(recon_topo_faces)
289
+ face_edge_adj = [[] for _ in range(num_faces)]
290
+ for edge_face1_face2 in ori_shape.edge_face_connectivity:
291
+ edge, face1, face2 = edge_face1_face2
292
+ if face1 == face2:
293
+ # raise ValueError("Face1 and Face2 should be different")
294
+ print("Face1 and Face2 should be different")
295
+ continue
296
+ assert edge not in face_edge_adj[face1]
297
+ face_edge_adj[face1].append(edge)
298
+ face_edge_adj[face2].append(edge)
299
+
300
+ trimmed_faces = []
301
+ for i_face in range(num_faces):
302
+ if len(face_edge_adj[i_face]) == 0:
303
+ trimmed_faces.append(None)
304
+ continue
305
+ face_edge_idx = face_edge_adj[i_face]
306
+ geom_face = recon_geom_faces[i_face]
307
+ face_edges = [recon_topo_curves[edge_idx] for edge_idx in face_edge_idx]
308
+
309
+ # Build wire
310
+ trimmed_face = None
311
+ for threshold in CONNECT_TOLERANCE:
312
+ wire_list = create_wire_from_unordered_edges(face_edges, threshold)
313
+ if wire_list is None:
314
+ continue
315
+
316
+ trimmed_face = create_trimmed_face_from_wire(geom_face, face_edges, wire_list, threshold)
317
+ if trimmed_face is not None:
318
+ break
319
+
320
+ trimmed_faces.append(trimmed_face)
321
+
322
+ mixed_faces = []
323
+ for i_face in range(num_faces):
324
+ if trimmed_faces[i_face] is None:
325
+ face = BRepBuilderAPI_MakeFace(recon_geom_faces[i_face], TRANSFER_PRECISION).Face()
326
+ mixed_faces.append(face)
327
+ else:
328
+ mixed_faces.append(trimmed_faces[i_face])
329
+
330
+ # trimmed_faces = [face for face in trimmed_faces if face is not None]
331
+ # if len(trimmed_faces) < 0.8 * num_faces:
332
+ # continue
333
+
334
+ compound = None
335
+ for connected_tolerance in CONNECT_TOLERANCE:
336
+ compound = get_compound(mixed_faces, connected_tolerance)
337
+ if compound is not None:
338
+ break
339
+
340
+ if compound is not None:
341
+ save_step_file(out_root / folder_name / 'recon_brep.step', compound)
342
+ else:
343
+ print(f"Failed to construct solid in {folder_name}")
344
+ return time_records
345
+
346
+
347
+ if __name__ == '__main__':
348
+ parser = argparse.ArgumentParser(description='Construct Brep From Data')
349
+ parser.add_argument('--data_root', type=str, required=True)
350
+ parser.add_argument('--list', type=str, default="")
351
+ parser.add_argument('--out_root', type=str, required=True)
352
+ parser.add_argument('--num_cpus', type=int, default=12)
353
+ parser.add_argument('--use_ray', action='store_true')
354
+ parser.add_argument('--prefix', type=str, default="")
355
+ parser.add_argument('--use_cuda', action='store_true')
356
+ parser.add_argument('--from_scratch', action='store_true')
357
+ parser.add_argument('--drop_num', type=int, default=0)
358
+ args = parser.parse_args()
359
+ v_data_root = args.data_root
360
+ v_out_root = args.out_root
361
+ filter_list = args.list
362
+ is_use_ray = args.use_ray
363
+ num_cpus = args.num_cpus
364
+ use_cuda = args.use_cuda
365
+ from_scratch = args.from_scratch
366
+ drop_num = args.drop_num
367
+ safe_check_dir(v_out_root)
368
+ if not os.path.exists(v_data_root):
369
+ raise ValueError(f"Data root path {v_data_root} does not exist.")
370
+
371
+ if args.prefix != "":
372
+ construct_brep_from_datanpz(v_data_root, v_out_root, args.prefix,
373
+ v_drop_num=drop_num,
374
+ use_cuda=use_cuda, is_optimize_geom=True, isdebug=True, is_save_data=True, )
375
+ exit()
376
+ all_folders = [folder for folder in os.listdir(v_data_root) if os.path.isdir(os.path.join(v_data_root, folder))]
377
+ if filter_list != "":
378
+ print(f"Use filter_list {filter_list}")
379
+ if not os.path.exists(filter_list):
380
+ raise ValueError(f"List {filter_list} does not exist.")
381
+ if os.path.isdir(filter_list):
382
+ valid_prefies = [f for f in os.listdir(filter_list) if os.path.isdir(os.path.join(filter_list, f))]
383
+ elif filter_list.endswith(".txt"):
384
+ valid_prefies = [item.strip() for item in open(filter_list).readlines()]
385
+ else:
386
+ raise ValueError(f"Invalid list {filter_list}")
387
+ all_folders = list(set(all_folders) & set(valid_prefies))
388
+
389
+ all_folders.sort()
390
+ all_folders = all_folders
391
+
392
+ print(f"Total {len(all_folders)} folders")
393
+
394
+ if not is_use_ray:
395
+ # random.shuffle(all_folders)
396
+ for i in tqdm(range(len(all_folders))):
397
+ construct_brep_from_datanpz(v_data_root, v_out_root, all_folders[i],
398
+ v_drop_num=drop_num,
399
+ use_cuda=use_cuda, from_scratch=from_scratch,
400
+ is_save_data=True, is_log=False, is_optimize_geom=True, is_ray=False, )
401
+ else:
402
+ ray.init(
403
+ dashboard_host="0.0.0.0",
404
+ dashboard_port=8080,
405
+ num_cpus=num_cpus,
406
+ # num_gpus=num_gpus,
407
+ # local_mode=True
408
+ )
409
+ construct_brep_from_datanpz_ray = ray.remote(num_gpus=0.1 if use_cuda else 0, max_retries=0)(
410
+ construct_brep_from_datanpz)
411
+
412
+ tasks = []
413
+ for i in range(len(all_folders)):
414
+ tasks.append(construct_brep_from_datanpz_ray.remote(
415
+ v_data_root, v_out_root,
416
+ all_folders[i],
417
+ v_drop_num=drop_num,
418
+ use_cuda=use_cuda, from_scratch=from_scratch,
419
+ is_log=False, is_ray=True, is_optimize_geom=True, isdebug=False,
420
+ ))
421
+ results = []
422
+ for i in tqdm(range(len(all_folders))):
423
+ try:
424
+ results.append(ray.get(tasks[i], timeout=60))
425
+ except:
426
+ results.append(None)
427
+ results = [item for item in results if item is not None]
428
+ print(len(results))
429
+ results = np.array(results)
430
+ print(results.mean(axis=0))
431
+ print("Done")
environment.yml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ name: HoLa-Brep
2
+ channels:
3
+ - conda-forge
4
+ - nvidia
5
+ - pytorch
6
+ dependencies:
7
+ - python=3.10
8
+ - pip=24.3.1
9
+ - numpy=2.2.2
10
+ - pythonocc-core==7.8.1
eval/__init__.py ADDED
File without changes
eval/check_data_deduplicate.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import multiprocessing
2
+
3
+ import networkx as nx
4
+ import numpy as np
5
+ import argparse
6
+ import os
7
+
8
+ import trimesh
9
+ from tqdm import tqdm
10
+ import ray
11
+
12
+ from check_valid import check_step_valid_soild, load_data_with_prefix
13
+ from eval_brepgen import normalize_pc
14
+ from eval_unique_novel import *
15
+
16
+
17
+ def find_connected_components(matrix):
18
+ N = len(matrix)
19
+ visited = [False] * N
20
+ components = []
21
+
22
+ def dfs(idx, component):
23
+ stack = [idx]
24
+ while stack:
25
+ node = stack.pop()
26
+ if not visited[node]:
27
+ visited[node] = True
28
+ component.append(node)
29
+ for neighbor in range(N):
30
+ if matrix[node][neighbor] and not visited[neighbor]:
31
+ stack.append(neighbor)
32
+
33
+ for i in range(N):
34
+ if not visited[i]:
35
+ component = []
36
+ dfs(i, component)
37
+ components.append(component)
38
+
39
+ return components
40
+
41
+
42
+ def compute_unique(graph_list, atol=None, is_use_ray=False, batch_size=100000, num_max_split_batch=128):
43
+ N = len(graph_list)
44
+ identical_pairs = []
45
+ unique_graph_idx = list(range(N))
46
+ pair_0, pair_1 = np.triu_indices(N, k=1)
47
+ check_pairs = np.column_stack((pair_0, pair_1))
48
+
49
+ num_split_batch = len(check_pairs) // batch_size
50
+ if num_split_batch > 64:
51
+ num_split_batch = num_max_split_batch
52
+ batch_size = len(check_pairs) // num_split_batch
53
+
54
+ if not is_use_ray:
55
+ for idx1, idx2 in tqdm(check_pairs):
56
+ is_identical = is_graph_identical(graph_list[idx1], graph_list[idx2], atol=atol)
57
+ if is_identical:
58
+ unique_graph_idx.remove(idx2) if idx2 in unique_graph_idx else None
59
+ else:
60
+ N_batch = len(check_pairs) // batch_size
61
+ futures = []
62
+ for i in tqdm(range(N_batch)):
63
+ batch_pairs = check_pairs[i * batch_size: (i + 1) * batch_size]
64
+ batch_graph_pair = [(graph_list[idx1], graph_list[idx2]) for idx1, idx2 in batch_pairs]
65
+ futures.append(is_graph_identical_remote.remote(batch_graph_pair, atol))
66
+ results = ray.get(futures)
67
+
68
+ for batch_idx in tqdm(range(N_batch)):
69
+ for idx, is_identical in enumerate(results[batch_idx]):
70
+ if not is_identical:
71
+ continue
72
+ idx1, idx2 = check_pairs[batch_idx * batch_size + idx]
73
+ if idx2 in unique_graph_idx:
74
+ unique_graph_idx.remove(idx2)
75
+ identical_pairs.append((idx1, idx2))
76
+
77
+ return unique_graph_idx, identical_pairs
78
+
79
+
80
+ def test_check():
81
+ sample = np.random.rand(3, 32, 32, 3)
82
+ face1 = sample[[0, 1, 2]]
83
+ face2 = sample[[0, 2, 1]]
84
+ faces_adj1 = [[0, 1]]
85
+ faces_adj2 = [[0, 2]]
86
+
87
+ graph1 = build_graph(face1, faces_adj1)
88
+ graph2 = build_graph(face2, faces_adj2)
89
+
90
+ is_identical = is_graph_identical(graph1, graph2)
91
+ # 判断图是否相等
92
+ print("Graphs are equal" if is_identical else "Graphs are not equal")
93
+
94
+
95
+ def load_data_from_npz(data_npz_file):
96
+ data_npz = np.load(data_npz_file, allow_pickle=True)
97
+ data_npz1 = np.load(data_npz_file.replace("deepcad_32", "deepcad_train_v6"), allow_pickle=True)
98
+ # Brepgen
99
+ if 'face_edge_adj' in data_npz:
100
+ faces = data_npz['pred_face']
101
+ face_edge_adj = data_npz['face_edge_adj']
102
+ faces_adj_pair = []
103
+ N = face_edge_adj.shape[0]
104
+ for face_idx1 in range(N):
105
+ for face_idx2 in range(face_idx1 + 1, N):
106
+ face_edges1 = face_edge_adj[face_idx1]
107
+ face_edges2 = face_edge_adj[face_idx2]
108
+ if sorted((face_idx1, face_idx2)) in faces_adj_pair:
109
+ continue
110
+ if len(set(face_edges1).intersection(set(face_edges2))) > 0:
111
+ faces_adj_pair.append(sorted((face_idx1, face_idx2)))
112
+ return faces, faces_adj_pair
113
+ # Ours
114
+ if 'sample_points_faces' in data_npz:
115
+ face_points = data_npz['sample_points_faces'] # Face sample points (num_faces*20*20*3)
116
+ edge_face_connectivity = data_npz['edge_face_connectivity'] # (num_intersection, (id_edge, id_face1, id_face2))
117
+ elif 'pred_face' in data_npz and 'pred_edge_face_connectivity' in data_npz:
118
+ face_points = data_npz['pred_face']
119
+ edge_face_connectivity = data_npz['pred_edge_face_connectivity']
120
+ else:
121
+ raise ValueError("Invalid data format")
122
+ faces_adj_pair = []
123
+ for edge_idx, face_idx1, face_idx2 in edge_face_connectivity:
124
+ faces_adj_pair.append([face_idx1, face_idx2])
125
+ if face_points.shape[-1] != 3:
126
+ face_points = face_points[..., :3]
127
+
128
+ src_shape = face_points.shape
129
+ face_points = normalize_pc(face_points.reshape(-1, 3)).reshape(src_shape)
130
+ return face_points, faces_adj_pair
131
+
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser()
135
+ parser.add_argument("--train_root", type=str, required=True)
136
+ parser.add_argument("--n_bit", type=int)
137
+ parser.add_argument("--atol", type=float)
138
+ parser.add_argument("--use_ray", action='store_true')
139
+ parser.add_argument("--load_batch_size", type=int, default=100)
140
+ parser.add_argument("--compute_batch_size", type=int, default=10000)
141
+ parser.add_argument("--txt", type=str, default=None)
142
+ parser.add_argument("--num_cpus", type=int, default=32)
143
+ args = parser.parse_args()
144
+ train_data_root = args.train_root
145
+ is_use_ray = args.use_ray
146
+ n_bit = args.n_bit
147
+ atol = args.atol
148
+ load_batch_size = args.load_batch_size
149
+ compute_batch_size = args.compute_batch_size
150
+ folder_list_txt = args.txt
151
+ num_cpus = args.num_cpus
152
+
153
+ if not n_bit and not atol:
154
+ raise ValueError("Must set either n_bit or atol")
155
+ if n_bit and atol:
156
+ raise ValueError("Cannot set both n_bit and atol")
157
+
158
+ if n_bit:
159
+ atol = None
160
+ if atol:
161
+ n_bit = -1
162
+
163
+ if folder_list_txt:
164
+ with open(folder_list_txt, "r") as f:
165
+ check_folders = [line.strip() for line in f.readlines()]
166
+ else:
167
+ check_folders = None
168
+
169
+ ################################################## Unqiue #######################################################
170
+ # Load all the data files
171
+ print("Loading data files...")
172
+ data_npz_file_list = load_data_with_prefix(train_data_root, 'data.npz')
173
+ data_npz_file_list.sort()
174
+ if is_use_ray:
175
+ ray.init()
176
+ futures = []
177
+ graph_list = []
178
+ prefix_list = []
179
+ for i in tqdm(range(0, len(data_npz_file_list), load_batch_size)):
180
+ batch_data_npz_file_list = data_npz_file_list[i: i + load_batch_size]
181
+ futures.append(load_and_build_graph_remote.remote(batch_data_npz_file_list, check_folders, n_bit))
182
+ for future in tqdm(futures):
183
+ result = ray.get(future)
184
+ graph_list_batch, prefix_list_batch = result
185
+ graph_list.extend(graph_list_batch)
186
+ prefix_list.extend(prefix_list_batch)
187
+ ray.shutdown()
188
+ else:
189
+ graph_list, prefix_list = load_and_build_graph(data_npz_file_list, n_bit)
190
+ print(f"Loaded {len(graph_list)} data files")
191
+
192
+ # sort the graph list according the face num
193
+ graph_node_num = np.array([graph.number_of_nodes() for graph in graph_list])
194
+
195
+ identical_pairs_txt = train_data_root + f"_identical_pairs_{n_bit}bit.txt"
196
+ fp_identical_pairs = open(identical_pairs_txt, "w")
197
+ fp_identical_pairs.close()
198
+ novel_txt = train_data_root + f"_novel_{n_bit}bit.txt"
199
+ fp_novel = open(novel_txt, "w")
200
+ fp_novel.close()
201
+
202
+ if is_use_ray:
203
+ ray.init(_temp_dir=r"/mnt/d/img2brep/ray_temp")
204
+ unique_graph_idx_list = []
205
+ pbar = tqdm(range(3, 31))
206
+ for num_face in pbar:
207
+ print(f"Processing {num_face}")
208
+ pbar.set_description(f"Processing {num_face}")
209
+ fp_identical_pairs = open(identical_pairs_txt, "a")
210
+ fp_novel = open(novel_txt, "a")
211
+ print(f"face_num = {num_face}", file=fp_identical_pairs)
212
+
213
+ hits_graph_idx = np.where(graph_node_num == num_face)[0]
214
+ hits_graph = [graph_list[idx] for idx in tqdm(hits_graph_idx)]
215
+ hits_graph_prefix = [prefix_list[idx] for idx in hits_graph_idx]
216
+
217
+ if len(hits_graph) != 0:
218
+ local_unique_graph_idx_list, identical_pairs = compute_unique(hits_graph, atol, is_use_ray, compute_batch_size)
219
+ for unique_graph_idx in local_unique_graph_idx_list:
220
+ print(f"{hits_graph_prefix[unique_graph_idx]}", file=fp_novel)
221
+
222
+ local_unique_graph_idx_list = [hits_graph_idx[idx] for idx in local_unique_graph_idx_list]
223
+ unique_graph_idx_list.extend(local_unique_graph_idx_list)
224
+
225
+ if len(identical_pairs) > 0:
226
+ for idx1, idx2 in identical_pairs:
227
+ print(f"{hits_graph_prefix[idx1]} {hits_graph_prefix[idx2]}", file=fp_identical_pairs)
228
+ pbar.set_postfix({"Local Unique": len(local_unique_graph_idx_list) / len(hits_graph),
229
+ "Total Unique": len(unique_graph_idx_list) / len(graph_list), })
230
+ print(f"Unique: {len(local_unique_graph_idx_list)}/{len(hits_graph_idx)}"
231
+ f"={len(local_unique_graph_idx_list) / len(hits_graph_idx)}", file=fp_identical_pairs)
232
+ else:
233
+ print(f"face_num = {num_face} has no data", file=fp_identical_pairs)
234
+ fp_identical_pairs.close()
235
+ fp_novel.close()
236
+
237
+ if is_use_ray:
238
+ ray.shutdown()
239
+
240
+ print(f"Unique num: {len(unique_graph_idx_list)}/{len(graph_list)}={len(unique_graph_idx_list) / len(graph_list)}")
241
+ print(f"Identical pairs are saved to {identical_pairs_txt}")
242
+ print(f"Novel txt are saved to {novel_txt}")
243
+ print("Done")
244
+
245
+
246
+ if __name__ == "__main__":
247
+ main()
eval/check_deduplicate_dis.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import numpy as np
3
+ import argparse
4
+ import os
5
+
6
+ from tqdm import tqdm
7
+ import ray
8
+
9
+ from check_valid import check_step_valid_soild, load_data_with_prefix
10
+
11
+
12
+ def real2bit(data, n_bits=8, min_range=-1, max_range=1):
13
+ """Convert vertices in [-1., 1.] to discrete values in [0, n_bits**2 - 1]."""
14
+ range_quantize = 2 ** n_bits - 1
15
+ data_quantize = (data - min_range) * range_quantize / (max_range - min_range)
16
+ data_quantize = np.clip(data_quantize, a_min=0, a_max=range_quantize) # clip values
17
+ return data_quantize.astype(int)
18
+
19
+
20
+ def build_graph(faces, faces_adj, n_bit=4):
21
+ # faces1 and faces2 are np.array of shape (n_faces, n_points, n_points, 3)
22
+ # faces_adj1 and faces_adj2 are lists of (face_idx, face_idx) adjacency, ex. [[0, 1], [1, 2]]
23
+ faces_bits = real2bit(faces, n_bits=n_bit)
24
+ """Build a graph from a shape."""
25
+ G = nx.Graph()
26
+ for face_idx, face_bit in enumerate(faces_bits):
27
+ face_bit = face_bit.reshape(-1, 3)
28
+ face_bit_ordered = face_bit[np.lexsort((face_bit[:, 0], face_bit[:, 1], face_bit[:, 2]))]
29
+ G.add_node(face_idx, shape_geometry=face_bit_ordered)
30
+ for pair in faces_adj:
31
+ G.add_edge(pair[0], pair[1])
32
+ return G
33
+
34
+
35
+ def is_graph_identical(graph1, graph2):
36
+ """Check if two shapes are identical."""
37
+ # Check if the two graphs are isomorphic considering node attributes
38
+ return nx.is_isomorphic(
39
+ graph1, graph2,
40
+ node_match=lambda n1, n2: np.array_equal(n1['shape_geometry'], n2['shape_geometry'])
41
+ )
42
+
43
+
44
+ def is_graph_identical_batch(graph_pair_list):
45
+ is_identical_list = []
46
+ for graph1, graph2 in graph_pair_list:
47
+ is_identical = is_graph_identical(graph1, graph2)
48
+ is_identical_list.append(is_identical)
49
+ return is_identical_list
50
+
51
+
52
+ is_graph_identical_remote = ray.remote(is_graph_identical_batch)
53
+
54
+
55
+ def find_connected_components(matrix):
56
+ N = len(matrix)
57
+ visited = [False] * N
58
+ components = []
59
+
60
+ def dfs(idx, component):
61
+ stack = [idx]
62
+ while stack:
63
+ node = stack.pop()
64
+ if not visited[node]:
65
+ visited[node] = True
66
+ component.append(node)
67
+ for neighbor in range(N):
68
+ if matrix[node][neighbor] and not visited[neighbor]:
69
+ stack.append(neighbor)
70
+
71
+ for i in range(N):
72
+ if not visited[i]:
73
+ component = []
74
+ dfs(i, component)
75
+ components.append(component)
76
+
77
+ return components
78
+
79
+
80
+ def compute_gen_unique(graph_list, is_use_ray=False, batch_size=100000):
81
+ N = len(graph_list)
82
+ unique_graph_idx = list(range(N))
83
+ pair_0, pair_1 = np.triu_indices(N, k=1)
84
+ check_pairs = list(zip(pair_0, pair_1))
85
+ deduplicate_matrix = np.zeros((N, N), dtype=bool)
86
+
87
+ if not is_use_ray:
88
+ for idx1, idx2 in tqdm(check_pairs):
89
+ is_identical = is_graph_identical(graph_list[idx1], graph_list[idx2])
90
+ if is_identical:
91
+ unique_graph_idx.remove(idx2) if idx2 in unique_graph_idx else None
92
+ deduplicate_matrix[idx1, idx2] = True
93
+ deduplicate_matrix[idx2, idx1] = True
94
+ else:
95
+ ray.init()
96
+ N_batch = len(check_pairs) // batch_size
97
+ futures = []
98
+ for i in tqdm(range(N_batch)):
99
+ batch_pairs = check_pairs[i * batch_size: (i + 1) * batch_size]
100
+ batch_graph_pair = [(graph_list[idx1], graph_list[idx2]) for idx1, idx2 in batch_pairs]
101
+ futures.append(is_graph_identical_remote.remote(batch_graph_pair))
102
+ results = ray.get(futures)
103
+
104
+ for batch_idx in tqdm(range(N_batch)):
105
+ for idx, is_identical in enumerate(results[batch_idx]):
106
+ if not is_identical:
107
+ continue
108
+ idx1, idx2 = check_pairs[batch_idx * batch_size + idx]
109
+ deduplicate_matrix[idx1, idx2] = True
110
+ deduplicate_matrix[idx2, idx1] = True
111
+ if idx2 in unique_graph_idx:
112
+ unique_graph_idx.remove(idx2)
113
+ ray.shutdown()
114
+
115
+ unique = len(unique_graph_idx)
116
+ print(f"Unique: {unique}/{N}")
117
+ unique_ratio = unique / N
118
+
119
+ return unique_ratio, deduplicate_matrix
120
+
121
+
122
+ def compute_gen_novel(gen_graph_list, train_graph_list, is_use_ray=False, batch_size=100000):
123
+ M, N = len(gen_graph_list), len(train_graph_list)
124
+ deduplicate_matrix = np.zeros((M, N), dtype=bool)
125
+ pair_0, pair_1 = np.triu_indices_from(deduplicate_matrix, k=1)
126
+ check_pairs = list(zip(pair_0, pair_1))
127
+ non_novel_graph_idx = np.zeros(M, dtype=bool)
128
+
129
+ if not is_use_ray:
130
+ for idx1, idx2 in tqdm(check_pairs):
131
+ if non_novel_graph_idx[idx1]:
132
+ continue
133
+ is_identical = is_graph_identical(gen_graph_list[idx1], train_graph_list[idx2])
134
+ if is_identical:
135
+ non_novel_graph_idx[idx1] = True
136
+ deduplicate_matrix[idx1, idx2] = True
137
+ else:
138
+ ray.init()
139
+ N_batch = len(check_pairs) // batch_size
140
+ futures = []
141
+ for i in tqdm(range(N_batch)):
142
+ batch_pairs = check_pairs[i * batch_size: (i + 1) * batch_size]
143
+ batch_graph_pair = [(gen_graph_list[idx1], train_graph_list[idx2]) for idx1, idx2 in batch_pairs]
144
+ futures.append(is_graph_identical_remote.remote(batch_graph_pair))
145
+ results = ray.get(futures)
146
+
147
+ for batch_idx in tqdm(range(N_batch)):
148
+ for idx, is_identical in enumerate(results[batch_idx]):
149
+ if not is_identical:
150
+ continue
151
+ idx1, idx2 = check_pairs[batch_idx * batch_size + idx]
152
+ deduplicate_matrix[idx1, idx2] = True
153
+ non_novel_graph_idx[idx1] = True
154
+ ray.shutdown()
155
+
156
+ novel = M - np.sum(non_novel_graph_idx)
157
+ print(f"Novel: {novel}/{M}")
158
+ novel_ratio = novel / M
159
+ return novel_ratio, deduplicate_matrix
160
+
161
+
162
+ def test_check():
163
+ sample = np.random.rand(3, 32, 32, 3)
164
+ face1 = sample[[0, 1, 2]]
165
+ face2 = sample[[0, 2, 1]]
166
+ faces_adj1 = [[0, 1]]
167
+ faces_adj2 = [[0, 2]]
168
+
169
+ graph1 = build_graph(face1, faces_adj1)
170
+ graph2 = build_graph(face2, faces_adj2)
171
+
172
+ is_identical = is_graph_identical(graph1, graph2)
173
+ # 判断图是否相等
174
+ print("Graphs are equal" if is_identical else "Graphs are not equal")
175
+
176
+
177
+ def load_data_from_npz(data_npz_file):
178
+ data_npz = np.load(data_npz_file, allow_pickle=True)
179
+ # Brepgen
180
+ if 'face_edge_adj' in data_npz:
181
+ faces = data_npz['pred_face']
182
+ face_edge_adj = data_npz['face_edge_adj']
183
+ faces_adj_pair = []
184
+ N = face_edge_adj.shape[0]
185
+ for face_idx1 in range(N):
186
+ for face_idx2 in range(face_idx1 + 1, N):
187
+ face_edges1 = face_edge_adj[face_idx1]
188
+ face_edges2 = face_edge_adj[face_idx2]
189
+ if sorted((face_idx1, face_idx2)) in faces_adj_pair:
190
+ continue
191
+ if len(set(face_edges1).intersection(set(face_edges2))) > 0:
192
+ faces_adj_pair.append(sorted((face_idx1, face_idx2)))
193
+ return faces, faces_adj_pair
194
+ # Ours
195
+ if 'sample_points_faces' in data_npz and 'edge_face_connectivity' in data_npz:
196
+ face_points = data_npz['sample_points_faces'] # Face sample points (num_faces*20*20*3)
197
+ edge_points = data_npz['sample_points_lines'] # Edge sample points (num_lines*20*3)
198
+ edge_face_connectivity = data_npz['edge_face_connectivity'] # (num_intersection, (id_edge, id_face1, id_face2))
199
+ elif 'pred_face' in data_npz and 'pred_edge_face_connectivity' in data_npz:
200
+ face_points = data_npz['pred_face']
201
+ edge_points = data_npz['pred_edge']
202
+ edge_face_connectivity = data_npz['pred_edge_face_connectivity']
203
+ else:
204
+ raise ValueError("Invalid data format")
205
+ faces_adj_pair = []
206
+ for edge_idx, face_idx1, face_idx2 in edge_face_connectivity:
207
+ faces_adj_pair.append([face_idx1, face_idx2])
208
+ return face_points, faces_adj_pair
209
+
210
+
211
+ def load_and_build_graph(data_npz_file_list, gen_post_data_root=None, n_bit=4):
212
+ gen_graph_list = []
213
+ prefix_list = []
214
+ for data_npz_file in data_npz_file_list:
215
+ folder_name = os.path.basename(os.path.dirname(data_npz_file))
216
+ if gen_post_data_root:
217
+ step_file_list = load_data_with_prefix(os.path.join(gen_post_data_root, folder_name), ".step")
218
+ if len(step_file_list) == 0:
219
+ continue
220
+ if not check_step_valid_soild(step_file_list[0]):
221
+ continue
222
+ prefix_list.append(folder_name)
223
+ faces, faces_adj_pair = load_data_from_npz(data_npz_file)
224
+ graph = build_graph(faces, faces_adj_pair, n_bit)
225
+ gen_graph_list.append(graph)
226
+ return gen_graph_list, prefix_list
227
+
228
+
229
+ load_and_build_graph_remote = ray.remote(load_and_build_graph)
230
+
231
+
232
+ def main():
233
+ parser = argparse.ArgumentParser()
234
+ parser.add_argument("--fake", type=str, required=True)
235
+ parser.add_argument("--fake_post", type=str, required=False)
236
+ parser.add_argument("--train_root", type=str, required=False)
237
+ parser.add_argument("--n_bit", type=int, default=4)
238
+ parser.add_argument("--use_ray", action='store_true')
239
+ parser.add_argument("--load_batch_size", type=int, default=400)
240
+ parser.add_argument("--compute_batch_size", type=int, default=200000)
241
+ parser.add_argument("--txt", type=str, default=None)
242
+ parser.add_argument("--num_cpus", type=int, default=16)
243
+ args = parser.parse_args()
244
+ gen_data_root = args.fake
245
+ gen_post_data_root = args.fake_post
246
+ train_data_root = args.train_root
247
+ is_use_ray = args.use_ray
248
+ n_bit = args.n_bit
249
+ load_batch_size = args.load_batch_size
250
+ compute_batch_size = args.compute_batch_size
251
+ folder_list_txt = args.txt
252
+ num_cpus = args.num_cpus
253
+
254
+ # Load all the generated data files
255
+ print("Loading generated data files...")
256
+ data_npz_file_list = load_data_with_prefix(gen_data_root, 'data.npz')
257
+ if is_use_ray:
258
+ ray.init(num_cpus=num_cpus)
259
+ futures = []
260
+ gen_graph_list = []
261
+ gen_prefix_list = []
262
+ for i in tqdm(range(0, len(data_npz_file_list), load_batch_size)):
263
+ batch_data_npz_file_list = data_npz_file_list[i: i + load_batch_size]
264
+ futures.append(load_and_build_graph_remote.remote(batch_data_npz_file_list, gen_post_data_root, n_bit))
265
+ for future in tqdm(futures):
266
+ result = ray.get(future)
267
+ gen_graph_list_batch, gen_prefix_list_batch = result
268
+ gen_graph_list.extend(gen_graph_list_batch)
269
+ gen_prefix_list.extend(gen_prefix_list_batch)
270
+ ray.shutdown()
271
+ else:
272
+ gen_graph_list, gen_prefix_list = load_and_build_graph(data_npz_file_list, gen_post_data_root, n_bit)
273
+ print(f"Loaded {len(gen_graph_list)} generated data files")
274
+
275
+ print("Loading training data files...")
276
+ data_npz_file_list = load_data_with_prefix(train_data_root, 'data.npz', folder_list_txt=folder_list_txt)
277
+ load_batch_size = load_batch_size * 5
278
+ if is_use_ray:
279
+ ray.init(num_cpus=num_cpus)
280
+ futures = []
281
+ train_graph_list = []
282
+ train_prefix_list = []
283
+ for i in tqdm(range(0, len(data_npz_file_list), load_batch_size)):
284
+ batch_data_npz_file_list = data_npz_file_list[i: i + load_batch_size]
285
+ futures.append(load_and_build_graph_remote.remote(batch_data_npz_file_list, None, n_bit))
286
+ for future in tqdm(futures):
287
+ result = ray.get(future)
288
+ train_graph_list_batch, train_prefix_list_batch = result
289
+ train_graph_list.extend(train_graph_list_batch)
290
+ train_prefix_list.extend(train_prefix_list_batch)
291
+ ray.shutdown()
292
+ else:
293
+ train_graph_list, train_prefix_list = load_and_build_graph(data_npz_file_list, None, n_bit)
294
+ print(f"Loaded {len(train_graph_list)} training data files")
295
+
296
+ print("Computing Unique ratio...")
297
+ unique_ratio, deduplicate_matrix = compute_gen_unique(gen_graph_list, is_use_ray, compute_batch_size)
298
+ print(f"Unique ratio: {unique_ratio}")
299
+
300
+ deduplicate_components_txt = gen_data_root + f"_deduplicate_components_{n_bit}bit.txt"
301
+ fp = open(deduplicate_components_txt, "w")
302
+ print(f"Unique ratio: {unique_ratio}", file=fp)
303
+ deduplicate_components = find_connected_components(deduplicate_matrix)
304
+ for component in deduplicate_components:
305
+ if len(component) > 1:
306
+ component = [gen_prefix_list[idx] for idx in component]
307
+ print(f"Component: {component}", file=fp)
308
+ print(f"Deduplicate components are saved to {deduplicate_components_txt}")
309
+
310
+ print("Computing Novel ratio...")
311
+ novel_ratio = compute_gen_novel(gen_graph_list, train_graph_list, is_use_ray, compute_batch_size)
312
+ print(f"Novel ratio: {novel_ratio}")
313
+ print("Done")
314
+
315
+
316
+ if __name__ == "__main__":
317
+ main()
eval/check_valid.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import shutil
3
+ import sys
4
+
5
+ from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeSolid
6
+ from OCC.Core.BRepCheck import BRepCheck_Analyzer
7
+ from OCC.Core.IGESControl import IGESControl_Reader
8
+ from OCC.Core.Interface import Interface_Static
9
+ from OCC.Core.STEPControl import STEPControl_Reader, STEPControl_Writer, STEPControl_AsIs
10
+ from OCC.Core.StepData import StepData_StepModel
11
+ from OCC.Core.TopAbs import TopAbs_SOLID, TopAbs_COMPOUND, TopAbs_SHELL, TopAbs_FACE, TopAbs_EDGE
12
+ from OCC.Extend.DataExchange import read_step_file
13
+ from OCC.Core.ShapeFix import ShapeFix_ShapeTolerance
14
+ import os
15
+ import argparse
16
+ import glob
17
+ from tqdm import tqdm
18
+ from matplotlib import pyplot as plt
19
+ import numpy as np
20
+ from diffusion.utils import get_primitives
21
+
22
+ os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
23
+
24
+ Interface_Static.SetIVal("read.precision.mode", 1)
25
+ Interface_Static.SetRVal("read.precision.val", 1e-1)
26
+ # Interface_Static.SetIVal("read.stdsameparameter.mode", 1)
27
+ # Interface_Static.SetIVal("read.surfacecurve.mode", 3)
28
+ #
29
+ # Interface_Static.SetCVal("write.step.schema", "DIS")
30
+ Interface_Static.SetIVal("write.precision.mode", 2)
31
+ Interface_Static.SetRVal("write.precision.val", 1e-1)
32
+
33
+
34
+ # Interface_Static.SetIVal("write.surfacecurve.mode", 1)
35
+
36
+
37
+ def check_step_valid_soild(step_file, precision=1e-1, return_shape=False):
38
+ try:
39
+ shape = read_step_file(str(step_file), as_compound=False, verbosity=False)
40
+ except:
41
+ if return_shape:
42
+ return False, None
43
+ else:
44
+ return False
45
+ if shape.ShapeType() != TopAbs_SOLID:
46
+ if return_shape:
47
+ return False, shape
48
+ else:
49
+ return False
50
+ shape_tol_setter = ShapeFix_ShapeTolerance()
51
+ shape_tol_setter.SetTolerance(shape, precision)
52
+ analyzer = BRepCheck_Analyzer(shape)
53
+ is_valid = analyzer.IsValid()
54
+ if return_shape:
55
+ return is_valid, shape
56
+ return is_valid
57
+
58
+
59
+ def load_data_with_prefix(root_folder, prefix, folder_list_txt=None):
60
+ data_files = []
61
+ folder_list = []
62
+ if folder_list_txt is not None:
63
+ with open(folder_list_txt, "r") as f:
64
+ folder_list = f.read().splitlines()
65
+ # Walk through the directory tree starting from the root folder
66
+ for root, dirs, files in os.walk(root_folder):
67
+ if folder_list_txt is not None and os.path.basename(root) not in folder_list:
68
+ continue
69
+ is_found = False
70
+ for filename in files:
71
+ # Check if the file ends with the specified prefix
72
+ if filename.endswith(prefix):
73
+ file_path = os.path.join(root, filename)
74
+ is_found = True
75
+ data_files.append(file_path)
76
+ if not is_found:
77
+ print(f"No {prefix} file found in {root}")
78
+
79
+ return data_files
80
+
81
+
82
+ if __name__ == "__main__":
83
+ parser = argparse.ArgumentParser()
84
+ parser.add_argument("--data_root", type=str, required=True)
85
+ parser.add_argument("--prefix", type=str, required=False, default="")
86
+ parser.add_argument("--only_success", action="store_true", default=False)
87
+ args = parser.parse_args()
88
+ data_root = args.data_root
89
+ only_success = args.only_success
90
+ folders = [f for f in os.listdir(data_root) if os.path.isdir(os.path.join(data_root, f))]
91
+
92
+ if args.prefix:
93
+ step_file_list = load_data_with_prefix(os.path.join(data_root, args.prefix), ".step")
94
+ assert len(step_file_list) > 0
95
+ print(f"Checking CAD solids in {args.prefix}...")
96
+ isvalid = check_step_valid_soild(step_file_list[0], is_set_gloabl=True)
97
+ print("Valid" if isvalid else "Invalid")
98
+ exit(0)
99
+
100
+ step_file_list = load_data_with_prefix(data_root, ".step")
101
+
102
+ print(f"Total sample features: {len(folders)}")
103
+ print(f"Total CAD solids: {len(step_file_list)}")
104
+
105
+ print("Start checking CAD solids...")
106
+
107
+ exception_folders = []
108
+ exception_out_root = data_root + "_exception"
109
+ if os.path.exists(exception_out_root):
110
+ shutil.rmtree(exception_out_root)
111
+ os.makedirs(exception_out_root, exist_ok=False)
112
+
113
+ # Load cad data
114
+ valid_count = 0
115
+ pbar = tqdm(step_file_list)
116
+ num_faces = []
117
+ num_edges = []
118
+ for step_file in pbar:
119
+ is_valid, shape = check_step_valid_soild(step_file, return_shape=True)
120
+ if os.path.exists(os.path.join(os.path.dirname(step_file), "success.txt")) and not is_valid:
121
+ folder_name = os.path.basename(os.path.dirname(step_file))
122
+ exception_folders.append(folder_name)
123
+ shutil.copytree(os.path.dirname(step_file), os.path.join(exception_out_root, folder_name))
124
+
125
+ if is_valid:
126
+ if only_success and not os.path.exists(os.path.join(os.path.dirname(step_file), "success.txt")):
127
+ continue
128
+ valid_count += 1
129
+ num_faces.append(len(get_primitives(shape, TopAbs_FACE)))
130
+ num_edges.append(len(get_primitives(shape, TopAbs_EDGE)) // 2)
131
+ pbar.set_postfix({"valid_count": valid_count})
132
+ # else:
133
+ # print(f"Invalid CAD solid: {step_file}")
134
+
135
+ fig, ax = plt.subplots(1, 2, layout="constrained")
136
+ ax[0].set_title("Num. faces")
137
+ ax[1].set_title("Num. edges")
138
+ hist_f, bin_f = np.histogram(num_faces, bins=5, range=(0, 30))
139
+ hist_e, bin_e = np.histogram(num_edges, bins=5, range=(0, 50))
140
+ # Normalize
141
+ hist_f = hist_f / np.sum(hist_f)
142
+ hist_e = hist_e / np.sum(hist_e)
143
+ ax[0].plot(bin_f[:-1], hist_f, "-")
144
+ ax[1].plot(bin_e[:-1], hist_e, "-")
145
+ ax[0].set_aspect(1. / ax[0].get_data_ratio())
146
+ ax[1].set_aspect(1. / ax[1].get_data_ratio())
147
+ plt.savefig(data_root + "_num_faces_edges.png", dpi=600)
148
+
149
+ print(f"Number of valid CAD solids: {valid_count}")
150
+ print(f"Valid rate: {valid_count / len(folders) * 100:.2f}%")
151
+
152
+ if len(exception_folders) > 0:
153
+ with open(os.path.join(exception_out_root, "exception_folders.txt"), "w") as f:
154
+ for folder in exception_folders:
155
+ f.write(folder + "\n")
156
+ print(f"Exception folders are saved to {exception_out_root}")
157
+ if len(exception_folders) == 0:
158
+ shutil.rmtree(exception_out_root)
159
+ print("No exception folders found.")
eval/eval_brepgen.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import argparse
3
+ import os
4
+ import numpy as np
5
+ from lightning_fabric import seed_everything
6
+ from tqdm import tqdm
7
+ import random
8
+ import warnings
9
+ from scipy.stats import entropy
10
+ from sklearn.neighbors import NearestNeighbors
11
+ from plyfile import PlyData
12
+ from pathlib import Path
13
+ import multiprocessing
14
+ from chamfer_distance import ChamferDistance
15
+ from eval.eval_pc_set import *
16
+
17
+ N_POINTS = 2000
18
+
19
+
20
+ def find_files(folder, extension):
21
+ return sorted([Path(os.path.join(folder, f)) for f in os.listdir(folder) if f.endswith(extension)])
22
+
23
+
24
+ def read_ply(path):
25
+ with open(path, 'rb') as f:
26
+ plydata = PlyData.read(f)
27
+ x = np.array(plydata['vertex']['x'])
28
+ y = np.array(plydata['vertex']['y'])
29
+ z = np.array(plydata['vertex']['z'])
30
+ vertex = np.stack([x, y, z], axis=1)
31
+ return vertex
32
+
33
+
34
+ def distChamfer(a, b):
35
+ x, y = a, b
36
+ bs, num_points, points_dim = x.size()
37
+ xx = torch.bmm(x, x.transpose(2, 1))
38
+ yy = torch.bmm(y, y.transpose(2, 1))
39
+ zz = torch.bmm(x, y.transpose(2, 1))
40
+ diag_ind = torch.arange(0, num_points).to(a).long()
41
+ rx = xx[:, diag_ind, diag_ind].unsqueeze(1).expand_as(xx)
42
+ ry = yy[:, diag_ind, diag_ind].unsqueeze(1).expand_as(yy)
43
+ P = (rx.transpose(2, 1) + ry - 2 * zz)
44
+ return P.min(1)[0], P.min(2)[0]
45
+
46
+
47
+ def _pairwise_CD(sample_pcs, ref_pcs, batch_size):
48
+ N_sample = sample_pcs.shape[0]
49
+ N_ref = ref_pcs.shape[0]
50
+ all_cd = []
51
+ all_emd = []
52
+ iterator = range(N_sample)
53
+ matched_gt = []
54
+ pbar = tqdm(iterator)
55
+ chamfer_dist = ChamferDistance()
56
+
57
+ for sample_b_start in pbar:
58
+ sample_batch = sample_pcs[sample_b_start]
59
+
60
+ cd_lst = []
61
+ emd_lst = []
62
+ for ref_b_start in range(0, N_ref, batch_size):
63
+ ref_b_end = min(N_ref, ref_b_start + batch_size)
64
+ ref_batch = ref_pcs[ref_b_start:ref_b_end]
65
+
66
+ batch_size_ref = ref_batch.size(0)
67
+ sample_batch_exp = sample_batch.view(1, -1, 3).expand(batch_size_ref, -1, -1)
68
+ sample_batch_exp = sample_batch_exp.contiguous()
69
+
70
+ dl, dr, idx1, idx2 = chamfer_dist(sample_batch_exp, ref_batch)
71
+ cd_lst.append((dl.mean(dim=1) + dr.mean(dim=1)).view(1, -1))
72
+
73
+ cd_lst = torch.cat(cd_lst, dim=1)
74
+ all_cd.append(cd_lst)
75
+
76
+ hit = np.argmin(cd_lst.detach().cpu().numpy()[0])
77
+ matched_gt.append(hit)
78
+ pbar.set_postfix({"cov": len(np.unique(matched_gt)) * 1.0 / N_ref})
79
+
80
+ all_cd = torch.cat(all_cd, dim=0) # N_sample, N_ref
81
+
82
+ return all_cd
83
+
84
+
85
+ def compute_cov_mmd(sample_pcs, ref_pcs, batch_size):
86
+ all_dist = _pairwise_CD(sample_pcs, ref_pcs, batch_size)
87
+ N_sample, N_ref = all_dist.size(0), all_dist.size(1)
88
+ min_val_fromsmp, min_idx = torch.min(all_dist, dim=1)
89
+ min_val, _ = torch.min(all_dist, dim=0)
90
+ mmd = min_val.mean()
91
+ cov = float(min_idx.unique().view(-1).size(0)) / float(N_ref)
92
+ cov = torch.tensor(cov).to(all_dist)
93
+
94
+ return {
95
+ 'MMD-CD': mmd.item(),
96
+ 'COV-CD': cov.item(),
97
+ }, min_idx.cpu().numpy()
98
+
99
+ def jsd_between_point_cloud_sets(sample_pcs, ref_pcs, in_unit_sphere, resolution=28):
100
+ '''Computes the JSD between two sets of point-clouds, as introduced in the paper ```Learning Representations And Generative Models
101
+ For 3D Point Clouds```.
102
+ Args:
103
+ sample_pcs: (np.ndarray S1xR2x3) S1 point-clouds, each of R1 points.
104
+ ref_pcs: (np.ndarray S2xR2x3) S2 point-clouds, each of R2 points.
105
+ resolution: (int) grid-resolution. Affects granularity of measurements.
106
+ '''
107
+ sample_grid_var = entropy_of_occupancy_grid(sample_pcs, resolution, in_unit_sphere)[1]
108
+ ref_grid_var = entropy_of_occupancy_grid(ref_pcs, resolution, in_unit_sphere)[1]
109
+ return jensen_shannon_divergence(sample_grid_var, ref_grid_var)
110
+
111
+
112
+ def entropy_of_occupancy_grid(pclouds, grid_resolution, in_sphere=False):
113
+ '''Given a collection of point-clouds, estimate the entropy of the random variables
114
+ corresponding to occupancy-grid activation patterns.
115
+ Inputs:
116
+ pclouds: (numpy array) #point-clouds x points per point-cloud x 3
117
+ grid_resolution (int) size of occupancy grid that will be used.
118
+ '''
119
+ epsilon = 10e-4
120
+ bound = 1 + epsilon
121
+ if abs(np.max(pclouds)) > bound or abs(np.min(pclouds)) > bound:
122
+ print(abs(np.max(pclouds)), abs(np.min(pclouds)))
123
+ warnings.warn('Point-clouds are not in unit cube.')
124
+
125
+ if in_sphere and np.max(np.sqrt(np.sum(pclouds ** 2, axis=2))) > bound:
126
+ warnings.warn('Point-clouds are not in unit sphere.')
127
+
128
+ grid_coordinates, _ = unit_cube_grid_point_cloud(grid_resolution, in_sphere)
129
+ grid_coordinates = grid_coordinates.reshape(-1, 3)
130
+ grid_counters = np.zeros(len(grid_coordinates))
131
+ grid_bernoulli_rvars = np.zeros(len(grid_coordinates))
132
+ nn = NearestNeighbors(n_neighbors=1).fit(grid_coordinates)
133
+
134
+ for pc in pclouds:
135
+ _, indices = nn.kneighbors(pc)
136
+ indices = np.squeeze(indices)
137
+ for i in indices:
138
+ grid_counters[i] += 1
139
+ indices = np.unique(indices)
140
+ for i in indices:
141
+ grid_bernoulli_rvars[i] += 1
142
+
143
+ acc_entropy = 0.0
144
+ n = float(len(pclouds))
145
+ for g in grid_bernoulli_rvars:
146
+ p = 0.0
147
+ if g > 0:
148
+ p = float(g) / n
149
+ acc_entropy += entropy([p, 1.0 - p])
150
+
151
+ return acc_entropy / len(grid_counters), grid_counters
152
+
153
+
154
+ def unit_cube_grid_point_cloud(resolution, clip_sphere=False):
155
+ '''Returns the center coordinates of each cell of a 3D grid with resolution^3 cells,
156
+ that is placed in the unit-cube.
157
+ If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.
158
+ '''
159
+ grid = np.ndarray((resolution, resolution, resolution, 3), np.float32)
160
+ spacing = 1.0 / float(resolution - 1) * 2
161
+ for i in range(resolution):
162
+ for j in range(resolution):
163
+ for k in range(resolution):
164
+ grid[i, j, k, 0] = i * spacing - 0.5 * 2
165
+ grid[i, j, k, 1] = j * spacing - 0.5 * 2
166
+ grid[i, j, k, 2] = k * spacing - 0.5 * 2
167
+
168
+ if clip_sphere:
169
+ grid = grid.reshape(-1, 3)
170
+ grid = grid[np.linalg.norm(grid, axis=1) <= 0.5]
171
+
172
+ return grid, spacing
173
+
174
+
175
+ def jensen_shannon_divergence(P, Q):
176
+ if np.any(P < 0) or np.any(Q < 0):
177
+ raise ValueError('Negative values.')
178
+ if len(P) != len(Q):
179
+ raise ValueError('Non equal size.')
180
+
181
+ P_ = P / np.sum(P) # Ensure probabilities.
182
+ Q_ = Q / np.sum(Q)
183
+
184
+ e1 = entropy(P_, base=2)
185
+ e2 = entropy(Q_, base=2)
186
+ e_sum = entropy((P_ + Q_) / 2.0, base=2)
187
+ res = e_sum - ((e1 + e2) / 2.0)
188
+
189
+ res2 = _jsdiv(P_, Q_)
190
+
191
+ if not np.allclose(res, res2, atol=10e-5, rtol=0):
192
+ warnings.warn('Numerical values of two JSD methods don\'t agree.')
193
+
194
+ return res
195
+
196
+
197
+ def _jsdiv(P, Q):
198
+ '''another way of computing JSD'''
199
+
200
+ def _kldiv(A, B):
201
+ a = A.copy()
202
+ b = B.copy()
203
+ idx = np.logical_and(a > 0, b > 0)
204
+ a = a[idx]
205
+ b = b[idx]
206
+ return np.sum([v for v in a * np.log2(a / b)])
207
+
208
+ P_ = P / np.sum(P)
209
+ Q_ = Q / np.sum(Q)
210
+
211
+ M = 0.5 * (P_ + Q_)
212
+
213
+ return 0.5 * (_kldiv(P_, M) + _kldiv(Q_, M))
214
+
215
+
216
+ def downsample_pc(points, n):
217
+ sample_idx = random.sample(list(range(points.shape[0])), n)
218
+ return points[sample_idx]
219
+
220
+
221
+ def normalize_pc(points):
222
+ # normalize
223
+ mean = np.mean(points, axis=0)
224
+ points = (points - mean)
225
+ # fit to unit cube
226
+ scale = np.max(np.abs(points))
227
+ points = points / scale
228
+ return points
229
+
230
+
231
+ def align_pc(points):
232
+ # 1. Center the point cloud
233
+ centroid = np.mean(points, axis=0)
234
+ centered_points = points - centroid
235
+
236
+ # 2. Calculate the three edge lengths of bbox
237
+ min_coords = np.min(centered_points, axis=0)
238
+ max_coords = np.max(centered_points, axis=0)
239
+ dimensions = max_coords - min_coords
240
+
241
+ # 3. Sort axes by dimension length to get axis order
242
+ axis_order = np.argsort(dimensions)[::-1] # sort from longest to shortest
243
+
244
+ # 4. Create permutation matrix (align longest edge to x, shortest to y)
245
+ perm_matrix = np.zeros((3, 3))
246
+ perm_matrix[0, axis_order[0]] = 1 # longest edge -> x
247
+ perm_matrix[1, axis_order[2]] = 1 # shortest edge -> y
248
+ perm_matrix[2, axis_order[1]] = 1 # medium edge -> z
249
+
250
+ # 5. Apply transformation
251
+ aligned_points = np.dot(centered_points, perm_matrix.T)
252
+
253
+ # 6. Ensure same centroid faces direction
254
+ if np.mean(aligned_points[:, 2]) < 0:
255
+ aligned_points[:, 2] *= -1
256
+
257
+ return aligned_points
258
+
259
+
260
+ def collect_pc(cad_folder):
261
+ pc_path = find_files(os.path.join(cad_folder, 'pcd'), 'final_pcd.ply')
262
+ if len(pc_path) == 0:
263
+ return []
264
+ pc_path = pc_path[-1] # final pcd
265
+ pc = read_ply(pc_path)
266
+ if pc.shape[0] > N_POINTS:
267
+ pc = downsample_pc(pc, N_POINTS)
268
+ pc = normalize_pc(pc)
269
+ return pc
270
+
271
+
272
+ def collect_pc2(cad_folder):
273
+ pc = read_ply(cad_folder)
274
+ if pc.shape[0] > N_POINTS:
275
+ pc = downsample_pc(pc, N_POINTS)
276
+ pc = normalize_pc(pc)
277
+ pc = align_pc(pc)
278
+ return pc
279
+
280
+
281
+ theta_x = np.radians(90) # Rotation angle around X-axis
282
+ theta_y = np.radians(90) # Rotation angle around Y-axis
283
+ theta_z = np.radians(180) # Rotation angle around Z-axis
284
+
285
+ # Create individual rotation matrices
286
+ Rx = np.array([[1, 0, 0],
287
+ [0, np.cos(theta_x), -np.sin(theta_x)],
288
+ [0, np.sin(theta_x), np.cos(theta_x)]])
289
+
290
+ Ry = np.array([[np.cos(theta_y), 0, np.sin(theta_y)],
291
+ [0, 1, 0],
292
+ [-np.sin(theta_y), 0, np.cos(theta_y)]])
293
+
294
+ Rz = np.array([[np.cos(theta_z), -np.sin(theta_z), 0],
295
+ [np.sin(theta_z), np.cos(theta_z), 0],
296
+ [0, 0, 1]])
297
+
298
+ rotation_matrix = np.dot(np.dot(Rz, Ry), Rx)
299
+
300
+
301
+ def collect_pc3(cad_folder):
302
+ pc = read_ply(cad_folder)
303
+ if pc.shape[0] > N_POINTS:
304
+ pc = downsample_pc(pc, N_POINTS)
305
+ pc = normalize_pc(pc)
306
+ rotated_point_cloud = np.dot(pc, rotation_matrix.T).astype(np.float32) # Transpose the rotation matrix to apply it correctly
307
+ return rotated_point_cloud
308
+
309
+
310
+ def load_data_with_prefix(root_folder, prefix):
311
+ data_files = []
312
+
313
+ # Walk through the directory tree starting from the root folder
314
+ for root, dirs, files in os.walk(root_folder):
315
+ for filename in files:
316
+ # Check if the file ends with the specified prefix
317
+ if filename.endswith(prefix):
318
+ file_path = os.path.join(root, filename)
319
+ data_files.append(file_path)
320
+
321
+ data_files.sort()
322
+ return data_files
323
+
324
+
325
+ def main():
326
+ parser = argparse.ArgumentParser()
327
+ parser.add_argument("--fake", type=str)
328
+ parser.add_argument("--real", type=str)
329
+ parser.add_argument("--n_test", type=int, default=1000)
330
+ parser.add_argument("--multi", type=float, default=3)
331
+ parser.add_argument("--times", type=int, default=10)
332
+ parser.add_argument("--batch_size", type=int, default=64)
333
+ args = parser.parse_args()
334
+
335
+ seed_everything(0)
336
+ print("n_test: {}, multiplier: {}, repeat times: {}".format(args.n_test, args.multi, args.times))
337
+
338
+ args.output = args.fake + '_results.txt'
339
+
340
+ seed_everything(0)
341
+ # Load reference pcd
342
+ num_cpus = multiprocessing.cpu_count()
343
+ ref_pcs = []
344
+ gt_shape_paths = load_data_with_prefix(args.real, '.ply')
345
+ load_iter = multiprocessing.Pool(num_cpus).imap(collect_pc2, gt_shape_paths)
346
+ for pc in tqdm(load_iter, total=len(gt_shape_paths)):
347
+ if len(pc) > 0:
348
+ ref_pcs.append(pc)
349
+ ref_pcs = np.stack(ref_pcs, axis=0)
350
+ print("real point clouds: {}".format(ref_pcs.shape))
351
+
352
+ # Load fake pcd
353
+ sample_pcs = []
354
+ shape_paths = load_data_with_prefix(args.fake, '.ply')
355
+ load_iter = multiprocessing.Pool(num_cpus).imap(collect_pc2, shape_paths)
356
+ for pc in tqdm(load_iter, total=len(shape_paths)):
357
+ if len(pc) > 0:
358
+ sample_pcs.append(pc)
359
+ sample_pcs = np.stack(sample_pcs, axis=0)
360
+
361
+ print("fake point clouds: {}".format(sample_pcs.shape))
362
+
363
+ # Testing
364
+ cov_on_gt = []
365
+ fp = open(args.output, "w")
366
+ result_list = []
367
+ for i in range(args.times):
368
+ print("iteration {}...".format(i))
369
+ select_idx1 = random.sample(list(range(len(sample_pcs))), int(args.multi * args.n_test))
370
+ rand_sample_pcs = sample_pcs[select_idx1]
371
+
372
+ select_idx2 = random.sample(list(range(len(ref_pcs))), args.n_test)
373
+ rand_ref_pcs = ref_pcs[select_idx2]
374
+
375
+ jsd = jsd_between_point_cloud_sets(rand_sample_pcs, rand_ref_pcs, in_unit_sphere=False)
376
+ with torch.no_grad():
377
+ rand_sample_pcs = torch.tensor(rand_sample_pcs).cuda().float()
378
+ rand_ref_pcs = torch.tensor(rand_ref_pcs).cuda().float()
379
+ result, idx = compute_cov_mmd(rand_sample_pcs, rand_ref_pcs, batch_size=args.batch_size)
380
+ result.update({"JSD": jsd})
381
+
382
+ cov_on_gt.extend(list(np.array(select_idx2)[np.unique(idx)]))
383
+
384
+ if False:
385
+ unique_idx = np.unique(idx, return_counts=True)
386
+ id_gts = unique_idx[0][np.argsort(unique_idx[1])[::-1][:100]]
387
+ gt_prefixes = [os.path.basename(gt_shape_paths[i])[:8] for i in select_idx2]
388
+ pred_prefixes = [os.path.basename(shape_paths[i])[:8] for i in select_idx1]
389
+
390
+ gt_prefixes[403]
391
+ print(result)
392
+ print(result, file=fp)
393
+ result_list.append(result)
394
+
395
+ avg_result = {}
396
+ for k in result_list[0].keys():
397
+ avg_result.update({"avg-" + k: np.mean([x[k] for x in result_list])})
398
+ print("average result:")
399
+ print(avg_result)
400
+ print(avg_result, file=fp)
401
+ fp.close()
402
+
403
+ cov_on_gt = list(set(cov_on_gt))
404
+ cov_on_gt = [gt_shape_paths[i] for i in cov_on_gt]
405
+ np.save(args.fake + '_cov_on_gt.npy', cov_on_gt)
406
+
407
+
408
+ if __name__ == '__main__':
409
+ main()
eval/eval_complexity.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import ray
3
+ import numpy as np
4
+ import argparse
5
+
6
+ from OCC.Core.BRepAdaptor import BRepAdaptor_Surface
7
+ from OCC.Core.BRepGProp import brepgprop
8
+ from OCC.Core.BRepLProp import BRepLProp_SLProps
9
+ from OCC.Core.GProp import GProp_GProps
10
+ from lightning_fabric import seed_everything
11
+
12
+ from eval.eval_condition import *
13
+
14
+ import networkx as nx
15
+ from OCC.Core.STEPControl import STEPControl_Reader
16
+ from OCC.Core.TopExp import TopExp_Explorer
17
+ from OCC.Core.TopAbs import TopAbs_VERTEX, TopAbs_EDGE
18
+ from OCC.Core.BRep import BRep_Tool
19
+ from OCC.Core.gp import gp_Pnt
20
+
21
+
22
+ def remove_outliers_zscore(data, threshold=3, max_value=50):
23
+ if len(data) == 0 or sum(data) == 0:
24
+ return data
25
+ mean = np.mean(data)
26
+ std_dev = np.std(data)
27
+ return [x for x in data if abs((x - mean) / (std_dev + 1e-8)) <= threshold and x < max_value]
28
+
29
+
30
+ def extract_edges_and_vertices(shape):
31
+ explorer_edges = TopExp_Explorer(shape, TopAbs_EDGE)
32
+ explorer_vertices = TopExp_Explorer(shape, TopAbs_VERTEX)
33
+
34
+ vertex_map = {}
35
+ edges = []
36
+
37
+ while explorer_edges.More():
38
+ edge = explorer_edges.Current()
39
+
40
+ vertices_on_edge = []
41
+ vertex_explorer = TopExp_Explorer(edge, TopAbs_VERTEX)
42
+ while vertex_explorer.More():
43
+ vertex = vertex_explorer.Current()
44
+ point = BRep_Tool.Pnt(vertex)
45
+ coord = (round(point.X(), 6), round(point.Y(), 6), round(point.Z(), 6))
46
+
47
+ if coord not in vertex_map:
48
+ vertex_map[coord] = len(vertex_map)
49
+
50
+ vertices_on_edge.append(vertex_map[coord])
51
+ vertex_explorer.Next()
52
+
53
+ if len(vertices_on_edge) == 2:
54
+ edges.append(tuple(vertices_on_edge))
55
+
56
+ explorer_edges.Next()
57
+
58
+ return vertex_map, edges
59
+
60
+
61
+ def create_nx_graph(vertex_map, edges):
62
+ graph = nx.Graph()
63
+
64
+ for coord, node_id in vertex_map.items():
65
+ graph.add_node(node_id, coord=coord)
66
+
67
+ for edge in edges:
68
+ graph.add_edge(edge[0], edge[1])
69
+
70
+ return graph
71
+
72
+
73
+ def calculate_cyclomatic_complexity(graph):
74
+ num_nodes = graph.number_of_nodes() # N
75
+ num_edges = graph.number_of_edges() # E
76
+ if graph.is_directed():
77
+ num_components = nx.number_strongly_connected_components(graph)
78
+ else:
79
+ num_components = nx.number_connected_components(graph)
80
+ # M = E - N + 2P
81
+ cyclomatic_complexity = num_edges - num_nodes + 2 * num_components
82
+ return cyclomatic_complexity
83
+
84
+
85
+ def eval_complexity_one(step_file_path):
86
+ isvalid, shape = check_step_valid_soild(step_file_path, return_shape=True)
87
+ if not isvalid:
88
+ return None
89
+
90
+ vertex_map, edges = extract_edges_and_vertices(shape)
91
+ graph = create_nx_graph(vertex_map, edges)
92
+ cyclomatic_complexity = calculate_cyclomatic_complexity(graph)
93
+
94
+ face_list = get_primitives(shape, TopAbs_FACE)
95
+ num_face = len(face_list)
96
+ num_edge = len(vertex_map.keys())
97
+ num_vertex = len(edges)
98
+
99
+ sample_point_curvature = []
100
+ num_samples = 256
101
+ for face in face_list:
102
+ surf_adaptor = BRepAdaptor_Surface(face)
103
+ u_min, u_max, v_min, v_max = (surf_adaptor.FirstUParameter(), surf_adaptor.LastUParameter(), surf_adaptor.FirstVParameter(),
104
+ surf_adaptor.LastVParameter())
105
+
106
+ u_samples = np.linspace(u_min, u_max, int(np.sqrt(num_samples)))
107
+ v_samples = np.linspace(v_min, v_max, int(np.sqrt(num_samples)))
108
+
109
+ face_sample_point_curvature = []
110
+ for u in u_samples:
111
+ for v in v_samples:
112
+ props = BRepLProp_SLProps(surf_adaptor, u, v, 2, 1e-8)
113
+ if props.IsCurvatureDefined():
114
+ mean_curvature = props.MeanCurvature()
115
+ face_sample_point_curvature.append(abs(mean_curvature))
116
+ face_sample_point_curvature = remove_outliers_zscore(face_sample_point_curvature)
117
+ if len(face_sample_point_curvature) == 0:
118
+ continue
119
+ sample_point_curvature.append(np.median(face_sample_point_curvature))
120
+
121
+ mean_curvature = np.mean(sample_point_curvature) if len(sample_point_curvature) > 0 else np.nan
122
+
123
+ if num_face == 0 or mean_curvature == np.nan:
124
+ return None
125
+
126
+ return {
127
+ 'num_face' : int(num_face),
128
+ 'num_edge' : int(num_edge),
129
+ 'num_vertex' : int(num_vertex),
130
+ 'cyclomatic_complexity': cyclomatic_complexity,
131
+ 'mean_curvature' : mean_curvature,
132
+ }
133
+
134
+
135
+ eval_complexity_one_remote = ray.remote(eval_complexity_one)
136
+
137
+ if __name__ == '__main__':
138
+ parser = argparse.ArgumentParser(description='Evaluate Brep Complexity')
139
+ parser.add_argument('--eval_root', type=str)
140
+ parser.add_argument('--only_valid', action='store_true')
141
+ args = parser.parse_args()
142
+
143
+ # 设置随机种子
144
+ seed_everything(0)
145
+ ray.init(ignore_reinit_error=True, local_mode=False)
146
+
147
+ all_folders = os.listdir(args.eval_root)
148
+ is_valid_list = []
149
+ futures = []
150
+ for folder in tqdm(all_folders):
151
+ step_path_list = glob.glob(os.path.join(args.eval_root, folder, '*.step'))
152
+ if len(step_path_list) == 0:
153
+ is_valid_list.append(False)
154
+ futures.append(None)
155
+ continue
156
+ is_valid_list.append(check_step_valid_soild(step_path_list[0], return_shape=False))
157
+ futures.append(eval_complexity_one_remote.remote(step_path_list[0]))
158
+
159
+ assert len(is_valid_list) == len(futures) == len(all_folders)
160
+ all_result = {}
161
+ for i, future in enumerate(tqdm(futures)):
162
+ if future is None:
163
+ continue
164
+ result = ray.get(future)
165
+ if args.only_valid and not is_valid_list[i]:
166
+ continue
167
+ all_result[all_folders[i]] = result
168
+
169
+ num_face_list = []
170
+ num_edge_list = []
171
+ num_vertex_list = []
172
+ cyclomatic_complexity_list = []
173
+ mean_curvature_list = []
174
+ exception_folder = []
175
+
176
+ for folder, result in tqdm(all_result.items()):
177
+ if result is None:
178
+ continue
179
+ result = dict(result)
180
+ num_face_list.append(result['num_face'])
181
+ num_edge_list.append(result['num_edge'])
182
+ num_vertex_list.append(result['num_vertex'])
183
+ cyclomatic_complexity_list.append(result['cyclomatic_complexity'])
184
+ mean_curvature_list.append(result['mean_curvature'])
185
+ exception_folder.append(folder)
186
+
187
+ print(f'Num Face: {np.mean(num_face_list)}')
188
+ print(f'Num Edge: {np.mean(num_edge_list)}')
189
+ print(f'Num Vertex: {np.mean(num_vertex_list)}')
190
+ print(f'Cyclomatic Complexity: {np.mean(cyclomatic_complexity_list)}')
191
+ print(f'Mean Curvature: {np.mean(mean_curvature_list)}')
192
+ print(f"{np.mean(num_face_list)} {np.mean(num_edge_list)} {np.mean(num_vertex_list)} "
193
+ f"{np.mean(cyclomatic_complexity_list)} {np.mean(mean_curvature_list)}")
194
+ ray.shutdown()
eval/eval_cond.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if [ -z "$TYPE" ]; then
2
+ echo "Error: 'CONDITION' variable is not set."
3
+ exit 1
4
+ fi
5
+
6
+ # Eval
7
+ python -m eval.eval_condition \
8
+ --eval_root ./outputs/${TYPE}_post \
9
+ --gt_root ./data/organized_data/ \
10
+ --list ./data/data_index/deduplicated_deepcad_testing_7_30.txt \
11
+ --use_ray \
12
+ --from_scratch \
13
+ --num_cpus 24
eval/eval_condition.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time, os, random, traceback, sys
2
+ from pathlib import Path
3
+
4
+ import matplotlib.pyplot as plt
5
+ import torch
6
+ import numpy as np
7
+
8
+ from OCC.Core.BRepAdaptor import BRepAdaptor_Curve
9
+ from tqdm import tqdm
10
+ import trimesh
11
+ import argparse
12
+
13
+ # import pandas as pd
14
+ from chamferdist import ChamferDistance
15
+
16
+ from OCC.Core.STEPControl import STEPControl_Reader
17
+ from OCC.Core.TopExp import TopExp_Explorer
18
+ from OCC.Core.TopAbs import TopAbs_VERTEX, TopAbs_EDGE, TopAbs_FACE
19
+ from OCC.Core.BRep import BRep_Tool
20
+ from OCC.Core.gp import gp_Pnt
21
+ from OCC.Core.IFSelect import IFSelect_RetDone
22
+ from OCC.Extend.DataExchange import read_step_file, write_step_file, write_stl_file
23
+ from OCC.Core.BRepCheck import BRepCheck_Analyzer
24
+
25
+ import ray
26
+ import shutil
27
+
28
+ from OCC.Core.TopoDS import TopoDS_Solid, TopoDS_Shell
29
+ from OCC.Core.TopAbs import TopAbs_COMPOUND, TopAbs_SHELL, TopAbs_SOLID
30
+
31
+ from diffusion.utils import get_primitives, get_triangulations, get_points_along_edge, get_curve_length
32
+ from eval.check_valid import check_step_valid_soild
33
+
34
+
35
+ def is_vertex_close(p1, p2, tol=1e-3):
36
+ return np.linalg.norm(np.array(p1) - np.array(p2)) < tol
37
+
38
+
39
+ def compute_statistics(eval_root, v_only_valid, listfile):
40
+ all_folders = [folder for folder in os.listdir(eval_root) if os.path.isdir(os.path.join(eval_root, folder))]
41
+ if listfile != '':
42
+ valid_names = [item.strip() for item in open(listfile, 'r').readlines()]
43
+ all_folders = list(set(all_folders) & set(valid_names))
44
+ all_folders.sort()
45
+ exception_folders = []
46
+ results = {
47
+ "prefix": []
48
+ }
49
+ for folder_name in tqdm(all_folders):
50
+ if not os.path.exists(os.path.join(eval_root, folder_name, 'eval.npz')):
51
+ exception_folders.append(folder_name)
52
+ continue
53
+
54
+ item = np.load(os.path.join(eval_root, folder_name, 'eval.npz'), allow_pickle=True)['results'].item()
55
+ if item['num_recon_face'] == 1:
56
+ exception_folders.append(folder_name)
57
+ if v_only_valid:
58
+ continue
59
+
60
+ if v_only_valid and not os.path.exists(os.path.join(eval_root, folder_name, 'success.txt')):
61
+ continue
62
+
63
+ results["prefix"].append(folder_name)
64
+ for key in item:
65
+ if key not in results:
66
+ results[key] = []
67
+ results[key].append(item[key])
68
+
69
+ if len(exception_folders) != 0:
70
+ print(f"Found exception folders: {exception_folders}")
71
+
72
+ for key in results:
73
+ results[key] = np.array(results[key])
74
+
75
+ results_str = ""
76
+ results_str += "Number\n"
77
+ results_str += f"Vertices: {np.mean(results['num_recon_vertex'])}/{np.mean(results['num_gt_vertex'])}\n"
78
+ results_str += f"Edge: {np.mean(results['num_recon_edge'])}/{np.mean(results['num_gt_edge'])}\n"
79
+ results_str += f"Face: {np.mean(results['num_recon_face'])}/{np.mean(results['num_gt_face'])}\n"
80
+
81
+ results_str += "Chamfer\n"
82
+ results_str += f"Vertices: {np.mean(results['vertex_cd'])}\n"
83
+ results_str += f"Edge: {np.mean(results['edge_cd'])}\n"
84
+ results_str += f"Face: {np.mean(results['face_cd'])}\n"
85
+
86
+ results_str += "Detection\n"
87
+ results_str += f"Vertices: {np.mean(results['vertex_fscore'])}\n"
88
+ results_str += f"Edge: {np.mean(results['edge_fscore'])}\n"
89
+ results_str += f"Face: {np.mean(results['face_fscore'])}\n"
90
+
91
+ results_str += "Topology\n"
92
+ results_str += f"FE: {np.mean(results['fe_fscore'])}\n"
93
+ results_str += f"EV: {np.mean(results['ev_fscore'])}\n"
94
+
95
+ results_str += "Accuracy\n"
96
+ results_str += f"Vertices: {np.mean(results['vertex_acc_cd'])}\n"
97
+ results_str += f"Edge: {np.mean(results['edge_acc_cd'])}\n"
98
+ results_str += f"Face: {np.mean(results['face_acc_cd'])}\n"
99
+ results_str += f"FE: {np.mean(results['fe_pre'])}\n"
100
+ results_str += f"EV: {np.mean(results['ev_pre'])}\n"
101
+
102
+ results_str += "Completeness\n"
103
+ results_str += f"Vertices: {np.mean(results['vertex_com_cd'])}\n"
104
+ results_str += f"Edge: {np.mean(results['edge_com_cd'])}\n"
105
+ results_str += f"Face: {np.mean(results['face_com_cd'])}\n"
106
+ results_str += f"FE: {np.mean(results['fe_rec'])}\n"
107
+ results_str += f"EV: {np.mean(results['ev_rec'])}\n"
108
+ print(results_str)
109
+ print("{:.4f} {:.4f} {:.4f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}".format(
110
+ np.mean(results['vertex_cd']), np.mean(results['edge_cd']), np.mean(results['face_cd']),
111
+ np.mean(results['vertex_fscore']), np.mean(results['edge_fscore']), np.mean(results['face_fscore']),
112
+ np.mean(results['fe_fscore']), np.mean(results['ev_fscore']),
113
+ ))
114
+ print(
115
+ "{:.0f}/{:.0f} {:.0f}/{:.0f} {:.0f}/{:.0f} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}".format(
116
+ np.mean(results['num_recon_vertex']), np.mean(results['num_gt_vertex']),
117
+ np.mean(results['num_recon_edge']), np.mean(results['num_gt_edge']),
118
+ np.mean(results['num_recon_face']), np.mean(results['num_gt_face']),
119
+ np.mean(results['vertex_acc_cd']), np.mean(results['edge_acc_cd']), np.mean(results['face_acc_cd']),
120
+ np.mean(results['vertex_com_cd']), np.mean(results['edge_com_cd']), np.mean(results['face_com_cd']),
121
+ np.mean(results['vertex_pre']), np.mean(results['edge_pre']), np.mean(results['face_pre']),
122
+ np.mean(results['fe_pre']), np.mean(results['ev_pre']),
123
+ np.mean(results['vertex_rec']), np.mean(results['edge_rec']), np.mean(results['face_rec']),
124
+ np.mean(results['fe_rec']), np.mean(results['ev_rec'])
125
+ ))
126
+ # print(f"{len(all_folders)-len(exception_folders)}/{len(all_folders)} are valid")
127
+ print(f"{results['face_cd'].shape[0]}/{len(all_folders)} are valid")
128
+
129
+ def draw():
130
+ face_chamfer = results['face_cd']
131
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6))
132
+ ax.hist(face_chamfer, bins=50, range=(0, 0.05), density=True, alpha=0.5, color='b', label='Face')
133
+ ax.set_title('Face Chamfer Distance')
134
+ ax.set_xlabel('Chamfer Distance')
135
+ ax.set_ylabel('Density')
136
+ ax.legend()
137
+ plt.savefig(str(eval_root) + "_face_chamfer.png", dpi=600)
138
+ # plt.show()
139
+
140
+ draw()
141
+ pass
142
+
143
+
144
+ def get_data(v_shape, v_num_per_m=100):
145
+ faces, face_points, edges, edge_points, vertices, vertex_points = [], [], [], [], [], []
146
+ for face in get_primitives(v_shape, TopAbs_FACE, v_remove_half=True):
147
+ try:
148
+ v, f = get_triangulations(face, 0.1, 0.1)
149
+ if len(f) == 0:
150
+ print("Ignore 0 face")
151
+ continue
152
+ except:
153
+ print("Ignore 1 face")
154
+ continue
155
+ mesh_item = trimesh.Trimesh(vertices=v, faces=f)
156
+ area = mesh_item.area
157
+ num_samples = min(max(int(v_num_per_m * v_num_per_m * area), 5), 10000)
158
+ pc_item, id_face = trimesh.sample.sample_surface(mesh_item, num_samples)
159
+ normals = mesh_item.face_normals[id_face]
160
+ faces.append(face)
161
+ face_points.append(np.concatenate((pc_item, normals), axis=1))
162
+ for edge in get_primitives(v_shape, TopAbs_EDGE, v_remove_half=True):
163
+ length = get_curve_length(edge)
164
+ num_samples = min(max(int(v_num_per_m * length), 5), 10000)
165
+ v = get_points_along_edge(edge, num_samples)
166
+ edges.append(edge)
167
+ edge_points.append(v)
168
+ for vertex in get_primitives(v_shape, TopAbs_VERTEX, v_remove_half=True):
169
+ vertices.append(vertex)
170
+ vertex_points.append(np.asarray([BRep_Tool.Pnt(vertex).Coord()]))
171
+ vertex_points = np.stack(vertex_points, axis=0)
172
+ return faces, face_points, edges, edge_points, vertices, vertex_points
173
+
174
+
175
+ def get_chamfer(v_recon_points, v_gt_points):
176
+ device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
177
+ chamfer_distance = ChamferDistance()
178
+ recon_fp = torch.from_numpy(np.concatenate(v_recon_points, axis=0)).float().to(device)[:, :3]
179
+ gt_fp = torch.from_numpy(np.concatenate(v_gt_points, axis=0)).float().to(device)[:, :3]
180
+ fp_acc_cd = chamfer_distance(recon_fp.unsqueeze(0), gt_fp.unsqueeze(0),
181
+ bidirectional=False, point_reduction='mean').cpu().item()
182
+ fp_com_cd = chamfer_distance(gt_fp.unsqueeze(0), recon_fp.unsqueeze(0),
183
+ bidirectional=False, point_reduction='mean').cpu().item()
184
+ fp_cd = fp_acc_cd + fp_com_cd
185
+ return fp_acc_cd, fp_com_cd, fp_cd
186
+
187
+
188
+ def get_match_ids(v_recon_points, v_gt_points):
189
+ from scipy.optimize import linear_sum_assignment
190
+
191
+ cost = np.zeros([len(v_recon_points), len(v_gt_points)]) # recon to gt
192
+ for i in range(cost.shape[0]):
193
+ for j in range(cost.shape[1]):
194
+ _, _, cost[i][j] = get_chamfer(
195
+ v_recon_points[i][..., :3][None, ..., :3],
196
+ v_gt_points[j][..., :3][None, ..., :3]
197
+ )
198
+
199
+ recon_indices, recon_to_gt = linear_sum_assignment(cost)
200
+
201
+ result_recon2gt = -1 * np.ones(len(v_recon_points), dtype=np.int32)
202
+ result_gt2recon = -1 * np.ones(len(v_gt_points), dtype=np.int32)
203
+
204
+ result_recon2gt[recon_indices] = recon_to_gt
205
+ result_gt2recon[recon_to_gt] = recon_indices
206
+ return result_recon2gt, result_gt2recon, cost
207
+
208
+
209
+ def get_detection(id_recon_gt, id_gt_recon, cost_matrix, v_threshold=0.1):
210
+ true_positive = 0
211
+ for i in range(len(id_recon_gt)):
212
+ if id_recon_gt[i] != -1 and cost_matrix[i, id_recon_gt[i]] < v_threshold:
213
+ true_positive += 1
214
+ precision = true_positive / (len(id_recon_gt) + 1e-6)
215
+ recall = true_positive / (len(id_gt_recon) + 1e-6)
216
+ return 2 * precision * recall / (precision + recall + 1e-6), precision, recall
217
+
218
+
219
+ def get_topology(faces, edges, vertices):
220
+ recon_face_edge, recon_edge_vertex = {}, {}
221
+ for i_face, face in enumerate(faces):
222
+ face_edge = []
223
+ for edge in get_primitives(face, TopAbs_EDGE):
224
+ face_edge.append(edges.index(edge) if edge in edges else edges.index(edge.Reversed()))
225
+ recon_face_edge[i_face] = list(set(face_edge))
226
+
227
+ for i_edge, edge in enumerate(edges):
228
+ edge_vertex = []
229
+ for vertex in get_primitives(edge, TopAbs_VERTEX):
230
+ edge_vertex.append(vertices.index(vertex) if vertex in vertices else vertices.index(vertex.Reversed()))
231
+ recon_edge_vertex[i_edge] = list(set(edge_vertex))
232
+ return recon_face_edge, recon_edge_vertex
233
+
234
+
235
+ def get_topo_detection(recon_face_edge, gt_face_edge, id_recon_gt_face, id_recon_gt_edge):
236
+ positive = 0
237
+ for i_recon_face, edges in recon_face_edge.items():
238
+ i_gt_face = id_recon_gt_face[i_recon_face]
239
+ if i_gt_face == -1:
240
+ continue
241
+ for i_edge in edges:
242
+ if id_recon_gt_edge[i_edge] in gt_face_edge[i_gt_face]:
243
+ positive += 1
244
+ precision = positive / (sum([len(edges) for edges in recon_face_edge.values()]) + 1e-6)
245
+ recall = positive / (sum([len(edges) for edges in gt_face_edge.values()]) + 1e-6)
246
+ return 2 * precision * recall / (precision + recall + 1e-6), precision, recall
247
+
248
+ def eval_one_with_try(eval_root, gt_root, folder_name, is_point2cad=False, v_num_per_m=100):
249
+ try:
250
+ eval_one(eval_root, gt_root, folder_name, is_point2cad, v_num_per_m)
251
+ except:
252
+ pass
253
+
254
+ def eval_one(eval_root, gt_root, folder_name, is_point2cad=False, v_num_per_m=100):
255
+ if os.path.exists(eval_root / folder_name / 'error.txt'):
256
+ os.remove(eval_root / folder_name / 'error.txt')
257
+ if os.path.exists(eval_root / folder_name / 'eval.npz'):
258
+ os.remove(eval_root / folder_name / 'eval.npz')
259
+
260
+ # At least have fall_back_mesh
261
+ step_name = "recon_brep.step"
262
+
263
+ if is_point2cad:
264
+ if not (eval_root / folder_name / "clipped/mesh_transformed.ply").exists():
265
+ print(f"Error: {folder_name} does not have mesh_transformed")
266
+ return
267
+ mesh = trimesh.load(eval_root / folder_name / "clipped/mesh_transformed.ply")
268
+ color = np.stack((
269
+ [item[1] for item in mesh.metadata['_ply_raw']['face']['data']],
270
+ [item[2] for item in mesh.metadata['_ply_raw']['face']['data']],
271
+ [item[3] for item in mesh.metadata['_ply_raw']['face']['data']],
272
+ ), axis=1)
273
+ color_map = [list(map(lambda item:int(item),item.strip().split(" "))) for item in open("src/brepnet/eval/point2cad_color.txt").readlines()]
274
+ index = np.asarray([color_map.index(item.tolist()) for item in color])
275
+ recon_face_points = [None]*(index.max()+1)
276
+ for i in range(index.max() + 1):
277
+ item_faces = mesh.faces[index == i]
278
+ item_mesh = trimesh.Trimesh(vertices=mesh.vertices, faces=item_faces)
279
+ num_samples = min(max(int(item_mesh.area * v_num_per_m * v_num_per_m), 5), 10000)
280
+ pc_item, id_face = trimesh.sample.sample_surface(item_mesh, num_samples)
281
+ normals = item_mesh.face_normals[id_face]
282
+ recon_face_points[i] = np.concatenate((pc_item, normals), axis=1)
283
+
284
+ if not (eval_root / folder_name / "clipped/curve_points.xyzc").exists():
285
+ print(f"Error: {folder_name} does not have curve_points")
286
+ return
287
+ curve_points = np.asarray([list(map(lambda item: float(item),item.strip().split(" "))) for item in open(eval_root / folder_name / "clipped/curve_points.xyzc").readlines()])
288
+ num_curves = int(curve_points.max(axis=0)[3]) + 1
289
+ recon_edge_points = [None]*num_curves
290
+ for i in range(num_curves):
291
+ item_points = curve_points[curve_points[:,3] == i][:,:3]
292
+ recon_edge_points[i] = item_points
293
+
294
+ if (eval_root / folder_name / "clipped/remove_duplicates_corners.ply").exists():
295
+ pc = trimesh.load(eval_root / folder_name / "clipped/remove_duplicates_corners.ply")
296
+ recon_vertex_points = pc.vertices[:,None]
297
+ else:
298
+ recon_vertex_points = np.asarray((0,0,0), dtype=np.float32)[None,None]
299
+
300
+ recon_face_edge = {}
301
+ recon_edge_vertex = {}
302
+ EV_mode = False
303
+ for items in open(eval_root / folder_name / 'topo/topo_fix.txt', 'r').readlines():
304
+ items = items.strip().split(" ")
305
+ if items[0] == "EV":
306
+ EV_mode = True
307
+ continue
308
+ if len(items) == 1:
309
+ continue
310
+ if not EV_mode:
311
+ recon_face_edge[int(items[0])] = list(map(lambda item: int(item), items[1:]))
312
+ else:
313
+ recon_edge_vertex[int(items[0])] = list(map(lambda item: int(item), items[1:]))
314
+ pass
315
+ else:
316
+ try:
317
+ # Face chamfer distance
318
+ if (eval_root / folder_name / step_name).exists():
319
+ valid, recon_shape = check_step_valid_soild(eval_root / folder_name / step_name, return_shape=True)
320
+ else:
321
+ print(f"Error: {folder_name} does not have {step_name}")
322
+ raise
323
+ if recon_shape is None:
324
+ print(f"Error: {folder_name} 's {step_name} is not valid")
325
+ raise
326
+
327
+ # Get data
328
+ recon_faces, recon_face_points, recon_edges, recon_edge_points, recon_vertices, recon_vertex_points = get_data(
329
+ recon_shape, v_num_per_m)
330
+
331
+ # Topology
332
+ recon_face_edge, recon_edge_vertex = get_topology(recon_faces, recon_edges, recon_vertices)
333
+ except:
334
+ recon_face_points = [np.zeros((1, 6), dtype=np.float32)]
335
+ recon_edge_points = [np.zeros((1, 6), dtype=np.float32)]
336
+ recon_vertex_points = [np.zeros((1, 3), dtype=np.float32)]
337
+ recon_face_edge = {}
338
+ recon_edge_vertex = {}
339
+
340
+ # GT
341
+ _, gt_shape = check_step_valid_soild(gt_root / folder_name / "normalized_shape.step", return_shape=True)
342
+ gt_faces, gt_face_points, gt_edges, gt_edge_points, gt_vertices, gt_vertex_points = get_data(gt_shape, v_num_per_m)
343
+ gt_face_edge, gt_edge_vertex = get_topology(gt_faces, gt_edges, gt_vertices)
344
+
345
+ # Chamfer
346
+ face_acc_cd, face_com_cd, face_cd = get_chamfer(recon_face_points, gt_face_points)
347
+ edge_acc_cd, edge_com_cd, edge_cd = get_chamfer(recon_edge_points, gt_edge_points)
348
+ vertex_acc_cd, vertex_com_cd, vertex_cd = get_chamfer(recon_vertex_points, gt_vertex_points)
349
+
350
+ # Detection
351
+ id_recon_gt_face, id_gt_recon_face, cost_face = get_match_ids(recon_face_points, gt_face_points)
352
+ id_recon_gt_edge, id_gt_recon_edge, cost_edge = get_match_ids(recon_edge_points, gt_edge_points)
353
+ id_recon_gt_vertex, id_gt_recon_vertex, cost_vertices = get_match_ids(recon_vertex_points, gt_vertex_points)
354
+
355
+ face_fscore, face_pre, face_rec = get_detection(id_recon_gt_face, id_gt_recon_face, cost_face)
356
+ edge_fscore, edge_pre, edge_rec = get_detection(id_recon_gt_edge, id_gt_recon_edge, cost_edge)
357
+ vertex_fscore, vertex_pre, vertex_rec = get_detection(id_recon_gt_vertex, id_gt_recon_vertex, cost_vertices)
358
+
359
+ fe_fscore, fe_pre, fe_rec = get_topo_detection(recon_face_edge, gt_face_edge, id_recon_gt_face, id_recon_gt_edge)
360
+ ev_fscore, ev_pre, ev_rec = get_topo_detection(recon_edge_vertex, gt_edge_vertex, id_recon_gt_edge,
361
+ id_recon_gt_vertex)
362
+
363
+ results = {
364
+ "face_cd": face_cd,
365
+ "edge_cd": edge_cd,
366
+ "vertex_cd": vertex_cd,
367
+
368
+ "face_fscore": face_fscore,
369
+ "edge_fscore": edge_fscore,
370
+ "vertex_fscore": vertex_fscore,
371
+ "fe_fscore": fe_fscore,
372
+ "ev_fscore": ev_fscore,
373
+
374
+ "face_acc_cd": face_acc_cd,
375
+ "edge_acc_cd": edge_acc_cd,
376
+ "vertex_acc_cd": vertex_acc_cd,
377
+
378
+ "face_com_cd": face_com_cd,
379
+ "edge_com_cd": edge_com_cd,
380
+ "vertex_com_cd": vertex_com_cd,
381
+
382
+ "fe_pre": fe_pre,
383
+ "ev_pre": ev_pre,
384
+ "fe_rec": fe_rec,
385
+ "ev_rec": ev_rec,
386
+
387
+ "vertex_pre": vertex_pre,
388
+ "edge_pre": edge_pre,
389
+ "face_pre": face_pre,
390
+
391
+ "vertex_rec": vertex_rec,
392
+ "edge_rec": edge_rec,
393
+ "face_rec": face_rec,
394
+
395
+ "num_recon_face": len(recon_face_points),
396
+ "num_gt_face": len(gt_face_points),
397
+ "num_recon_edge": len(recon_edge_points),
398
+ "num_gt_edge": len(gt_edge_points),
399
+ "num_recon_vertex": len(recon_vertex_points),
400
+ "num_gt_vertex": len(gt_vertex_points),
401
+ }
402
+ np.savez_compressed(eval_root / folder_name / 'eval.npz', results=results, allow_pickle=True)
403
+
404
+
405
+ if __name__ == '__main__':
406
+ parser = argparse.ArgumentParser(description='Evaluate The Generated Brep')
407
+ parser.add_argument('--eval_root', type=str, required=True)
408
+ parser.add_argument('--gt_root', type=str, required=True)
409
+ parser.add_argument('--use_ray', action='store_true')
410
+ parser.add_argument('--num_cpus', type=int, default=16)
411
+ parser.add_argument('--prefix', type=str, default='')
412
+ parser.add_argument('--list', type=str, default='')
413
+ parser.add_argument('--from_scratch', action='store_true')
414
+ parser.add_argument('--is_point2cad', action='store_true')
415
+ parser.add_argument('--only_valid', action='store_true')
416
+ args = parser.parse_args()
417
+ eval_root = Path(args.eval_root)
418
+ gt_root = Path(args.gt_root)
419
+ is_use_ray = args.use_ray
420
+ num_cpus = args.num_cpus
421
+ listfile = args.list
422
+ from_scratch = args.from_scratch
423
+ is_point2cad = args.is_point2cad
424
+ only_valid = args.only_valid
425
+
426
+ if not os.path.exists(eval_root):
427
+ raise ValueError(f"Data root path {eval_root} does not exist.")
428
+ if not os.path.exists(gt_root):
429
+ raise ValueError(f"Output root path {gt_root} does not exist.")
430
+
431
+ if args.prefix != '':
432
+ eval_one(eval_root, gt_root, args.prefix, is_point2cad)
433
+ exit()
434
+
435
+ all_folders = [folder for folder in os.listdir(eval_root) if os.path.isdir(eval_root / folder)]
436
+ ori_length = len(all_folders)
437
+ if listfile != '':
438
+ valid_names = [item.strip() for item in open(listfile, 'r').readlines()]
439
+ all_folders = list(set(all_folders) & set(valid_names))
440
+ all_folders.sort()
441
+ print(f"Total {len(all_folders)}/{ori_length} folders to evaluate")
442
+
443
+ if not from_scratch:
444
+ print("Filtering the folders that have eval.npz")
445
+ all_folders = [folder for folder in all_folders if not os.path.exists(eval_root / folder / 'eval.npz')]
446
+ print(f"Total {len(all_folders)} folders to compute after caching")
447
+
448
+ if not is_use_ray:
449
+ # random.shuffle(self.folder_names)
450
+ for i in tqdm(range(len(all_folders))):
451
+ eval_one(eval_root, gt_root, all_folders[i], is_point2cad)
452
+ else:
453
+ ray.init(
454
+ dashboard_host="0.0.0.0",
455
+ dashboard_port=8080,
456
+ num_cpus=num_cpus,
457
+ # local_mode=True
458
+ )
459
+ eval_one_remote = ray.remote(max_retries=0)(eval_one_with_try)
460
+ tasks = []
461
+ timeout_cancel_list = []
462
+ for i in range(len(all_folders)):
463
+ tasks.append(eval_one_remote.remote(eval_root, gt_root, all_folders[i], is_point2cad))
464
+ results = []
465
+ for i in tqdm(range(len(all_folders))):
466
+ try:
467
+ results.append(ray.get(tasks[i], timeout=60 * 3))
468
+ except ray.exceptions.GetTimeoutError:
469
+ results.append(None)
470
+ timeout_cancel_list.append(all_folders[i])
471
+ ray.cancel(tasks[i])
472
+ except:
473
+ results.append(None)
474
+ results = [item for item in results if item is not None]
475
+ print(f"Cancel for timeout: {timeout_cancel_list}")
476
+
477
+ print("Computing statistics...")
478
+ compute_statistics(eval_root, only_valid, listfile)
479
+ print("Done")
eval/eval_lfd.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if [ -z "$TYPE" ]; then
2
+ echo "Error: 'CONDITION' variable is not set."
3
+ exit 1
4
+ fi
5
+
6
+ cd ./eval/lfd/evaluation_scripts/compute_lfd_feat
7
+ python -m compute_lfd_feat_multiprocess --gen_path ../../../../outputs/${TYPE}_post --save_path ../../../../outputs/${TYPE}_lfd_feat --prefix recon_brep.stl
8
+ cd ..
9
+ python -m compute_lfd --dataset_path ../../../data/data_lfd_feat --gen_path ../../../outputs/${TYPE}_lfd_feat --save_name ../../../outputs/${TYPE}_lfd.pkl --num_workers 8 --list ../../../data/data_index/deduplicated_deepcad_training_7_30.txt
10
+ cd ../../..
11
+ python -m eval.viz_lfd ./outputs/${TYPE}_lfd.pkl ./outputs/${TYPE}_lfd.png ./outputs/${TYPE}_post
eval/eval_pc_set.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ def evaluate_uniformity_nnd(points):
5
+ """
6
+ Evaluate point cloud uniformity using Nearest Neighbor Distance (NND)
7
+ Args:
8
+ points: numpy array of shape (N, 3)
9
+ Returns:
10
+ dict containing NND statistics
11
+ """
12
+ # 1. 计算每个点到其最近邻的距离
13
+ diff = points[:, None, :] - points[None, :, :] # (N, N, 3)
14
+ distances = np.sqrt(np.sum(diff * diff, axis=-1)) # (N, N)
15
+
16
+ # 将自身距离设为无穷大
17
+ np.fill_diagonal(distances, np.inf)
18
+
19
+ # 获取每个点的最近邻距离
20
+ min_distances = np.min(distances, axis=1) # (N,)
21
+
22
+ # 2. 计算统计指标
23
+ metrics = {
24
+ 'mean_nnd': np.mean(min_distances),
25
+ 'std_nnd' : np.std(min_distances),
26
+ 'cv_nnd' : np.std(min_distances) / np.mean(min_distances), # 变异系数
27
+ 'min_nnd' : np.min(min_distances),
28
+ 'max_nnd' : np.max(min_distances),
29
+
30
+ # Clark-Evans R统计量: R = 实际平均最近邻距离 / 期望平均最近邻距离
31
+ # R接近1表示随机分布,R<1表示聚集,R>1表示均匀
32
+ 'density' : len(points) / np.prod(np.max(points, axis=0) - np.min(points, axis=0)),
33
+ }
34
+
35
+ # 计算Clark-Evans R统计量
36
+ expected_mean_dist = 0.5 / np.sqrt(metrics['density'])
37
+ metrics['clark_evans_r'] = metrics['mean_nnd'] / expected_mean_dist
38
+
39
+ # 3. 计算直方图数据(可用于可视化)
40
+ hist, bins = np.histogram(min_distances, bins='auto', density=True)
41
+ metrics['hist_values'] = hist
42
+ metrics['hist_bins'] = bins
43
+
44
+ return metrics
eval/eval_uncond.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Eval
2
+ python -m eval.sample_points --data_root ./outputs/unconditional_post --out_root ./outputs/unconditional_pcd --valid;
3
+ python -m eval.eval_brepgen --real ./data/organized_data --fake ./outputs/unconditional_pcd;
4
+ python -m eval.eval_complexity --eval_root ./outputs/unconditional_post --only_valid;
5
+ python -m eval.eval_condition \
6
+ --eval_root ./outputs/unconditional_post \
7
+ --gt_root ./data/organized_data/ \
8
+ --list ./data/data_index/deduplicated_deepcad_testing_7_30.txt \
9
+ --num_cpus 24 \
10
+ --use_ray \
11
+ --from_scratch \
12
+ --only_valid
13
+
14
+ # Validness
15
+ python -m eval.check_valid --data_root ./outputs/unconditional_post
eval/eval_unique_novel.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import multiprocessing
2
+
3
+ import networkx as nx
4
+ import numpy as np
5
+ import argparse
6
+ import os
7
+
8
+ import trimesh
9
+ from tqdm import tqdm
10
+ import ray
11
+
12
+ from check_valid import check_step_valid_soild, load_data_with_prefix
13
+ from eval_brepgen import normalize_pc
14
+
15
+
16
+ def real2bit(data, n_bits=8, min_range=-1, max_range=1):
17
+ """Convert vertices in [-1., 1.] to discrete values in [0, n_bits**2 - 1]."""
18
+ range_quantize = 2 ** n_bits - 1
19
+ data_quantize = (data - min_range) * range_quantize / (max_range - min_range)
20
+ data_quantize = np.clip(data_quantize, a_min=0, a_max=range_quantize) # clip values
21
+ return data_quantize.astype(int)
22
+
23
+
24
+ def build_graph(faces, faces_adj, n_bit=4):
25
+ # faces1 and faces2 are np.array of shape (n_faces, n_points, n_points, 3)
26
+ # faces_adj1 and faces_adj2 are lists of (face_idx, face_idx) adjacency, ex. [[0, 1], [1, 2]]
27
+ if n_bit < 0:
28
+ faces_bits = faces
29
+ else:
30
+ faces_bits = real2bit(faces, n_bits=n_bit)
31
+ """Build a graph from a shape."""
32
+ G = nx.Graph()
33
+ for face_idx, face_bit in enumerate(faces_bits):
34
+ G.add_node(face_idx, shape_geometry=face_bit)
35
+ for pair in faces_adj:
36
+ G.add_edge(pair[0], pair[1])
37
+ return G
38
+
39
+
40
+ def is_graph_identical(graph1, graph2, atol=None):
41
+ """Check if two shapes are identical."""
42
+ # Check if the two graphs are isomorphic considering node attributes
43
+ if atol is None:
44
+ return nx.is_isomorphic(
45
+ graph1, graph2,
46
+ node_match=lambda n1, n2: np.array_equal(n1['shape_geometry'], n2['shape_geometry'])
47
+ )
48
+ else:
49
+ return nx.is_isomorphic(
50
+ graph1, graph2,
51
+ node_match=lambda n1, n2: np.allclose(n1['shape_geometry'], n2['shape_geometry'], atol=atol, rtol=0)
52
+ )
53
+
54
+
55
+ def is_graph_identical_batch(graph_pair_list, atol=None):
56
+ is_identical_list = []
57
+ for graph1, graph2 in graph_pair_list:
58
+ is_identical = is_graph_identical(graph1, graph2, atol=atol)
59
+ is_identical_list.append(is_identical)
60
+ return is_identical_list
61
+
62
+
63
+ is_graph_identical_remote = ray.remote(is_graph_identical_batch)
64
+
65
+
66
+ def find_connected_components(matrix):
67
+ N = len(matrix)
68
+ visited = [False] * N
69
+ components = []
70
+
71
+ def dfs(idx, component):
72
+ stack = [idx]
73
+ while stack:
74
+ node = stack.pop()
75
+ if not visited[node]:
76
+ visited[node] = True
77
+ component.append(node)
78
+ for neighbor in range(N):
79
+ if matrix[node][neighbor] and not visited[neighbor]:
80
+ stack.append(neighbor)
81
+
82
+ for i in range(N):
83
+ if not visited[i]:
84
+ component = []
85
+ dfs(i, component)
86
+ components.append(component)
87
+
88
+ return components
89
+
90
+
91
+ def compute_gen_unique(graph_list, is_use_ray=False, batch_size=100000, atol=None):
92
+ N = len(graph_list)
93
+ unique_graph_idx = list(range(N))
94
+ pair_0, pair_1 = np.triu_indices(N, k=1)
95
+ check_pairs = list(zip(pair_0, pair_1))
96
+ deduplicate_matrix = np.zeros((N, N), dtype=bool)
97
+
98
+ if not is_use_ray:
99
+ for idx1, idx2 in tqdm(check_pairs):
100
+ is_identical = is_graph_identical(graph_list[idx1], graph_list[idx2], atol=atol)
101
+ if is_identical:
102
+ unique_graph_idx.remove(idx2) if idx2 in unique_graph_idx else None
103
+ deduplicate_matrix[idx1, idx2] = True
104
+ deduplicate_matrix[idx2, idx1] = True
105
+ else:
106
+ ray.init()
107
+ N_batch = len(check_pairs) // batch_size
108
+ futures = []
109
+ for i in tqdm(range(N_batch)):
110
+ batch_pairs = check_pairs[i * batch_size: (i + 1) * batch_size]
111
+ batch_graph_pair = [(graph_list[idx1], graph_list[idx2]) for idx1, idx2 in batch_pairs]
112
+ futures.append(is_graph_identical_remote.remote(batch_graph_pair, atol))
113
+ results = ray.get(futures)
114
+
115
+ for batch_idx in tqdm(range(N_batch)):
116
+ for idx, is_identical in enumerate(results[batch_idx]):
117
+ if not is_identical:
118
+ continue
119
+ idx1, idx2 = check_pairs[batch_idx * batch_size + idx]
120
+ deduplicate_matrix[idx1, idx2] = True
121
+ deduplicate_matrix[idx2, idx1] = True
122
+ if idx2 in unique_graph_idx:
123
+ unique_graph_idx.remove(idx2)
124
+ ray.shutdown()
125
+
126
+ unique = len(unique_graph_idx)
127
+ print(f"Unique: {unique}/{N}")
128
+ unique_ratio = unique / N
129
+
130
+ return unique_ratio, deduplicate_matrix
131
+
132
+
133
+ def compute_gen_novel_bk(gen_graph_list, train_graph_list, is_use_ray=False, batch_size=100000):
134
+ M, N = len(gen_graph_list), len(train_graph_list)
135
+ deduplicate_matrix = np.zeros((M, N), dtype=bool)
136
+ pair_0, pair_1 = np.triu_indices_from(deduplicate_matrix, k=1)
137
+ check_pairs = list(zip(pair_0, pair_1))
138
+ non_novel_graph_idx = np.zeros(M, dtype=bool)
139
+
140
+ if not is_use_ray:
141
+ for idx1, idx2 in tqdm(check_pairs):
142
+ if non_novel_graph_idx[idx1]:
143
+ continue
144
+ is_identical = is_graph_identical(gen_graph_list[idx1], train_graph_list[idx2])
145
+ if is_identical:
146
+ non_novel_graph_idx[idx1] = True
147
+ deduplicate_matrix[idx1, idx2] = True
148
+ else:
149
+ ray.init()
150
+ N_batch = len(check_pairs) // batch_size
151
+ futures = []
152
+ for i in tqdm(range(N_batch)):
153
+ batch_pairs = check_pairs[i * batch_size: (i + 1) * batch_size]
154
+ batch_graph_pair = [(gen_graph_list[idx1], train_graph_list[idx2]) for idx1, idx2 in batch_pairs]
155
+ futures.append(is_graph_identical_remote.remote(batch_graph_pair))
156
+ results = ray.get(futures)
157
+
158
+ for batch_idx in tqdm(range(N_batch)):
159
+ for idx, is_identical in enumerate(results[batch_idx]):
160
+ if not is_identical:
161
+ continue
162
+ idx1, idx2 = check_pairs[batch_idx * batch_size + idx]
163
+ deduplicate_matrix[idx1, idx2] = True
164
+ non_novel_graph_idx[idx1] = True
165
+ ray.shutdown()
166
+
167
+ novel = M - np.sum(non_novel_graph_idx)
168
+ print(f"Novel: {novel}/{M}")
169
+ novel_ratio = novel / M
170
+ return novel_ratio, deduplicate_matrix
171
+
172
+
173
+ def is_graph_identical_list(graph1, graph2_path_list):
174
+ """Check if two shapes are identical."""
175
+ # Check if the two graphs are isomorphic considering node attributes
176
+ graph2_list, graph2_prefix_list = load_and_build_graph(graph2_path_list)
177
+ for graph2 in graph2_list:
178
+ if nx.is_isomorphic(graph1, graph2,
179
+ node_match=lambda n1, n2: np.array_equal(n1['shape_geometry'], n2['shape_geometry'])):
180
+ return True
181
+ return False
182
+
183
+
184
+ is_graph_identical_list_remote = ray.remote(is_graph_identical_list)
185
+
186
+
187
+ def test_check():
188
+ sample = np.random.rand(3, 32, 32, 3)
189
+ face1 = sample[[0, 1, 2]]
190
+ face2 = sample[[0, 2, 1]]
191
+ faces_adj1 = [[0, 1]]
192
+ faces_adj2 = [[0, 2]]
193
+
194
+ graph1 = build_graph(face1, faces_adj1)
195
+ graph2 = build_graph(face2, faces_adj2)
196
+
197
+ is_identical = is_graph_identical(graph1, graph2)
198
+ # 判断图是否相等
199
+ print("Graphs are equal" if is_identical else "Graphs are not equal")
200
+
201
+
202
+ def load_data_from_npz(data_npz_file):
203
+ data_npz = np.load(data_npz_file, allow_pickle=True)
204
+ data_npz1 = np.load(data_npz_file.replace("deepcad_32", "deepcad_train_v6"), allow_pickle=True)
205
+ # Brepgen
206
+ if 'face_edge_adj' in data_npz:
207
+ faces = data_npz['pred_face']
208
+ face_edge_adj = data_npz['face_edge_adj']
209
+ faces_adj_pair = []
210
+ N = face_edge_adj.shape[0]
211
+ for face_idx1 in range(N):
212
+ for face_idx2 in range(face_idx1 + 1, N):
213
+ face_edges1 = face_edge_adj[face_idx1]
214
+ face_edges2 = face_edge_adj[face_idx2]
215
+ if sorted((face_idx1, face_idx2)) in faces_adj_pair:
216
+ continue
217
+ if len(set(face_edges1).intersection(set(face_edges2))) > 0:
218
+ faces_adj_pair.append(sorted((face_idx1, face_idx2)))
219
+ return faces, faces_adj_pair
220
+ # Ours
221
+ if 'sample_points_faces' in data_npz:
222
+ face_points = data_npz['sample_points_faces'] # Face sample points (num_faces*20*20*3)
223
+ edge_face_connectivity = data_npz['edge_face_connectivity'] # (num_intersection, (id_edge, id_face1, id_face2))
224
+ elif 'pred_face' in data_npz and 'pred_edge_face_connectivity' in data_npz:
225
+ face_points = data_npz['pred_face']
226
+ edge_face_connectivity = data_npz['pred_edge_face_connectivity']
227
+ else:
228
+ raise ValueError("Invalid data format")
229
+ faces_adj_pair = []
230
+ for edge_idx, face_idx1, face_idx2 in edge_face_connectivity:
231
+ faces_adj_pair.append([face_idx1, face_idx2])
232
+ if face_points.shape[-1] != 3:
233
+ face_points = face_points[..., :3]
234
+
235
+ src_shape = face_points.shape
236
+ face_points = normalize_pc(face_points.reshape(-1, 3)).reshape(src_shape)
237
+ return face_points, faces_adj_pair
238
+
239
+
240
+ def load_and_build_graph(data_npz_file_list, gen_post_data_root=None, n_bit=4):
241
+ gen_graph_list = []
242
+ prefix_list = []
243
+ for data_npz_file in data_npz_file_list:
244
+ folder_name = os.path.basename(os.path.dirname(data_npz_file))
245
+ if gen_post_data_root:
246
+ step_file_list = load_data_with_prefix(os.path.join(gen_post_data_root, folder_name), ".step")
247
+ if len(step_file_list) == 0:
248
+ continue
249
+ if not check_step_valid_soild(step_file_list[0]):
250
+ continue
251
+ prefix_list.append(folder_name)
252
+ faces, faces_adj_pair = load_data_from_npz(data_npz_file)
253
+ graph = build_graph(faces, faces_adj_pair, n_bit)
254
+ gen_graph_list.append(graph)
255
+ return gen_graph_list, prefix_list
256
+
257
+
258
+ load_and_build_graph_remote = ray.remote(load_and_build_graph)
259
+
260
+
261
+ def main():
262
+ parser = argparse.ArgumentParser()
263
+ parser.add_argument("--fake_root", type=str, required=True)
264
+ parser.add_argument("--fake_post", type=str, required=True)
265
+ parser.add_argument("--train_root", type=str, required=False)
266
+ parser.add_argument("--n_bit", type=int, required=False)
267
+ parser.add_argument("--atol", type=float, required=False)
268
+ parser.add_argument("--use_ray", action='store_true')
269
+ parser.add_argument("--load_batch_size", type=int, default=400)
270
+ parser.add_argument("--compute_batch_size", type=int, default=200000)
271
+ parser.add_argument("--txt", type=str, default=None)
272
+ parser.add_argument("--num_cpus", type=int, default=32)
273
+ parser.add_argument("--min_face", type=int, required=False)
274
+ parser.add_argument("--only_unique", action='store_true')
275
+ args = parser.parse_args()
276
+ gen_data_root = args.fake_root
277
+ gen_post_data_root = args.fake_post
278
+ train_data_root = args.train_root
279
+ is_use_ray = args.use_ray
280
+ n_bit = args.n_bit
281
+ atol = args.atol
282
+ load_batch_size = args.load_batch_size
283
+ compute_batch_size = args.compute_batch_size
284
+ folder_list_txt = args.txt
285
+ num_cpus = args.num_cpus
286
+
287
+ if not n_bit and not atol:
288
+ raise ValueError("Must set either n_bit or atol")
289
+ if n_bit and atol:
290
+ raise ValueError("Cannot set both n_bit and atol")
291
+
292
+ if not args.only_unique and not train_data_root:
293
+ raise ValueError("Must set train_data_root when not only_unique")
294
+
295
+ if n_bit:
296
+ atol = None
297
+ if atol:
298
+ n_bit = -1
299
+
300
+ ################################################## Unqiue #######################################################
301
+ # Load all the generated data files
302
+ print("Loading generated data files...")
303
+ gen_data_npz_file_list = load_data_with_prefix(gen_data_root, 'data.npz')
304
+ if is_use_ray:
305
+ ray.init()
306
+ futures = []
307
+ gen_graph_list = []
308
+ gen_prefix_list = []
309
+ for i in tqdm(range(0, len(gen_data_npz_file_list), load_batch_size)):
310
+ batch_gen_data_npz_file_list = gen_data_npz_file_list[i: i + load_batch_size]
311
+ futures.append(load_and_build_graph_remote.remote(batch_gen_data_npz_file_list, gen_post_data_root, n_bit))
312
+ for future in tqdm(futures):
313
+ result = ray.get(future)
314
+ gen_graph_list_batch, gen_prefix_list_batch = result
315
+ gen_graph_list.extend(gen_graph_list_batch)
316
+ gen_prefix_list.extend(gen_prefix_list_batch)
317
+ ray.shutdown()
318
+ else:
319
+ gen_graph_list, gen_prefix_list = load_and_build_graph(gen_data_npz_file_list, gen_post_data_root, n_bit)
320
+ print(f"Loaded {len(gen_graph_list)} generated data files")
321
+
322
+ if args.min_face:
323
+ graph_node_num = [len(graph.nodes) for graph in gen_graph_list]
324
+ gen_graph_list = [gen_graph_list[idx] for idx, num in enumerate(graph_node_num) if num >= args.min_face]
325
+ gen_prefix_list = [gen_prefix_list[idx] for idx, num in enumerate(graph_node_num) if num >= args.min_face]
326
+ print(f"Filtered sample that face_num < {args.min_face}, remain {len(gen_graph_list)}")
327
+
328
+ print("Computing Unique ratio...")
329
+ unique_ratio, deduplicate_matrix = compute_gen_unique(gen_graph_list, is_use_ray, compute_batch_size, atol=atol)
330
+ print(f"Unique ratio: {unique_ratio}")
331
+
332
+ if n_bit == -1:
333
+ unique_txt = gen_data_root + f"_unique_atol_{atol}_results.txt"
334
+ else:
335
+ unique_txt = gen_data_root + f"_unique_{n_bit}bit_results.txt"
336
+ fp = open(unique_txt, "w")
337
+ print(f"Unique ratio: {unique_ratio}", file=fp)
338
+ deduplicate_components = find_connected_components(deduplicate_matrix)
339
+ for component in deduplicate_components:
340
+ if len(component) > 1:
341
+ component = [gen_prefix_list[idx] for idx in component]
342
+ print(f"Component: {component}", file=fp)
343
+ print(f"Deduplicate components are saved to {unique_txt}")
344
+ fp.close()
345
+
346
+ if args.only_unique:
347
+ exit(0)
348
+
349
+ # For accelerate, please first run the find_nerest.py to find the nearest item in train data for each fake sample
350
+ ################################################### Novel ########################################################
351
+ print("Computing Novel ratio...")
352
+ print("Loading training data files...")
353
+ # data_npz_file_list = load_data_with_prefix(train_data_root, 'data.npz', folder_list_txt=folder_list_txt)
354
+ # load_batch_size = load_batch_size * 5
355
+
356
+ is_identical = np.zeros(len(gen_graph_list), dtype=bool)
357
+ if is_use_ray:
358
+ ray.init()
359
+ futures = []
360
+ for gen_graph_idx, gen_graph in enumerate(tqdm(gen_graph_list)):
361
+ nearest_txt = os.path.join(gen_post_data_root, gen_prefix_list[gen_graph_idx], "nearest.txt")
362
+ if not os.path.exists(nearest_txt):
363
+ continue
364
+ with open(nearest_txt, "r+") as f:
365
+ lines = f.readlines()
366
+ train_folders = [os.path.join(train_data_root, line.strip().split(" ")[0], 'data.npz') for line in lines[2:]]
367
+ futures.append(is_graph_identical_list_remote.remote(gen_graph, train_folders))
368
+ results = ray.get(futures)
369
+ for gen_graph_idx, result in enumerate(results):
370
+ is_identical[gen_graph_idx] = result
371
+ ray.shutdown()
372
+ else:
373
+ pbar = tqdm(gen_graph_list)
374
+ for gen_graph_idx, gen_graph in enumerate(pbar):
375
+ nearest_txt = os.path.join(gen_post_data_root, gen_prefix_list[gen_graph_idx], "nearest.txt")
376
+ if not os.path.exists(nearest_txt):
377
+ continue
378
+ with open(nearest_txt, "r+") as f:
379
+ lines = f.readlines()
380
+ train_folders = [os.path.join(train_data_root, line.strip().split(" ")[0], 'data.npz') for line in lines[2:]]
381
+ is_identical[gen_graph_idx] = is_graph_identical_list(gen_graph, train_folders)
382
+ pbar.set_postfix({"novel_count": np.sum(~is_identical)})
383
+
384
+ identical_folder = np.array(gen_prefix_list)[is_identical]
385
+ print(f"Novel ratio: {np.sum(~is_identical) / len(gen_graph_list)}")
386
+ novel_txt = gen_data_root + f"_novel_{n_bit}bit_results.txt"
387
+ with open(novel_txt, "w") as f:
388
+ f.write(f"Novel ratio: {np.sum(~is_identical) / len(gen_graph_list)}\n")
389
+ for folder in identical_folder:
390
+ f.write(folder + "\n")
391
+ print("Done")
392
+
393
+
394
+ if __name__ == "__main__":
395
+ main()
eval/eval_validity.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import argparse
3
+
4
+ from lightning_fabric import seed_everything
5
+
6
+ from eval_condition import *
7
+ from OCC.Core.GCPnts import GCPnts_AbscissaPoint
8
+ from OCC.Core.GeomAdaptor import GeomAdaptor_Curve
9
+
10
+
11
+ def get_fluxEE(vertices: np.ndarray, facets: np.ndarray) -> float:
12
+ points = vertices[facets]
13
+ a = points[:, 1] - points[:, 0]
14
+ b = points[:, 2] - points[:, 0]
15
+ normals = np.cross(a, b)
16
+ norms = np.linalg.norm(normals)
17
+ assert np.all(norms != 0)
18
+ normals /= norms[:, None]
19
+ d_S = 0.5 * norms
20
+ fluxEE = np.sum(np.sum(normals, axis=1) * d_S)
21
+ return abs(fluxEE)
22
+
23
+
24
+ def get_NormalC(v_recon_points: np.ndarray, v_gt_points: np.ndarray) -> float:
25
+ # ACC
26
+ acc_l1norm = np.sum(np.abs(v_gt_points[:, None, :3] - v_recon_points[:, :3]), axis=2)
27
+ min_dist_index = np.argmin(acc_l1norm, axis=0)
28
+ acc = np.mean(np.sum(v_recon_points[:, 3:] * v_gt_points[min_dist_index][:, 3:], axis=1))
29
+
30
+ # Comp
31
+ comp_l1norm = np.sum(np.abs(v_recon_points[:, None, :3] - v_gt_points[:, :3]), axis=2)
32
+ min_dist_index = np.argmin(comp_l1norm, axis=0)
33
+ comp = np.mean(np.sum(v_gt_points[:, 3:] * v_recon_points[min_dist_index][:, 3:], axis=1))
34
+
35
+ return acc, comp, (acc + comp) / 2.0
36
+
37
+
38
+ def get_danglingEdgeLength(shape):
39
+ no_directions = True
40
+ edges = get_primitives(shape, TopAbs_EDGE, no_directions)
41
+ faces = get_primitives(shape, TopAbs_FACE, no_directions)
42
+ connection = {edge: set() for edge in edges}
43
+
44
+ def EdgeBelongsToFace(edge, face):
45
+ edgeOnFace = get_primitives(face, TopAbs_EDGE, True)
46
+ for _edge in edgeOnFace:
47
+ if _edge.IsSame(edge):
48
+ return True
49
+ return False
50
+
51
+ # Get edge-face connections
52
+ for edge in edges:
53
+ for face in faces:
54
+ if EdgeBelongsToFace(edge, face):
55
+ connection[edge].add(face)
56
+
57
+ # Get dangling edge length
58
+ danglingEdgeLength = 0.0
59
+ for edge, faces in connection.items():
60
+ if len(faces) < 2:
61
+ curve, _, _ = BRep_Tool.Curve(edge)
62
+ if len(faces) == 1 and (BRep_Tool.Surface(list(faces)[0]).IsUPeriodic() or BRep_Tool.Surface(list(faces)[0]).IsVPeriodic()):
63
+ continue
64
+ else:
65
+ danglingEdgeLength += GCPnts_AbscissaPoint.Length(GeomAdaptor_Curve(curve))
66
+
67
+ return danglingEdgeLength
68
+
69
+
70
+ if __name__ == "__main__":
71
+ parser = argparse.ArgumentParser(description='Evaluate The Generated Brep')
72
+ parser.add_argument('--eval_root', type=str)
73
+ parser.add_argument('--gt_root', type=str)
74
+ parser.add_argument('--use_ray', action='store_true')
75
+ parser.add_argument('--num_cpus', type=int, default=16)
76
+ parser.add_argument('--prefix', type=str, default='')
77
+ parser.add_argument('--list', type=str, default='')
78
+ parser.add_argument('--from_scratch', action='store_true')
79
+ args = parser.parse_args()
80
+
81
+ seed_everything(0)
eval/lfd/evaluation_scripts/README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Scripts for Evaluating GET3D
2
+
3
+ #### Compute Light Field Distance
4
+
5
+ We thanks the authors for releasing the source code of
6
+ LFD [official repo](https://github.com/Sunwinds/ShapeDescriptor) and
7
+ It's [python extension](https://github.com/kacperkan/light-field-distance).
8
+
9
+ - Step 0: Download the all the files
10
+ from [official repo](https://github.com/Sunwinds/ShapeDescriptor/tree/master/LightField/3DRetrieval_v1.8/3DRetrieval_v1.8/Executable)
11
+ , and save it into `evaluation_scripts/load_data`.
12
+ - Step 1: Compile the files for light fild distance
13
+
14
+ ```bash
15
+ cd evaluation_scripts/load_data
16
+ bash do_all.sh
17
+ cd ../..
18
+ git clone https://github.com/kacperkan/light-field-distance
19
+ cd light-field-distance
20
+ bash compile.sh
21
+ python setup.py install
22
+ cd ..
23
+ ```
24
+
25
+ - Step 2: To compute LFD on a server, we need to set up a dummy screen
26
+
27
+ ```bash
28
+ apt-get install -y freeglut3 libglu1-mesa xserver-xorg-video-dummy
29
+ X -config evaluation_scripts/compute_lfd_feat/dummy-1920x1080.conf
30
+ ```
31
+
32
+ - Step 3: On a separate console, `export DISPLAY=:0`
33
+
34
+ - Step 4: We first generat the Light Field feature for each object by running
35
+
36
+ ```bash
37
+ python compute_lfd_feat_multiprocess.py --gen_path PATH_TO_THE_MODEL_PREDICTION --save_path PATH_FOR_LFD_OUTPUT_FOR_PRED
38
+ ```
39
+
40
+ - Step 5: Do the same for the ground truth data
41
+
42
+ ```bash
43
+ python compute_lfd_feat_multiprocess.py --gen_path PATH_TO_GT_MODEL --save_path PATH_FOR_LFD_OUTPUT_FOR_GT
44
+ ```
45
+
46
+ - Step 6: Compute the metric: LFD
47
+
48
+ ```bash
49
+ python compute_lfd.py --split_path PATH_TO_TEST_SPLIT --dataset_path PATH_FOR_LFD_OUTPUT_FOR_GT --gen_path PATH_FOR_LFD_OUTPUT_FOR_PRED --save_name results/our/lfd.pkl
50
+ ```
51
+
52
+ ### Compute Chamfer Distance
53
+
54
+ - Step 1: Download original shapenet obj files from Shapenet Webpage
55
+ - Step 2: Running scripts to compute the chamfer distance
56
+
57
+ ```bash
58
+ python compute_cd.py --dataset_path PATH_TO_GT_OBJS --gen_path PATH_TO_THE_MODEL_PREDICTION --split_path PATH_TO_TEST_SPLIT --save_name results/our/cd.pkl
59
+ ```
60
+
61
+ (Optional) For shapenet car, since the GT dataset contains intern structures, we thus only
62
+ sample the points from the outer surface of the object for both our prediction and ground
63
+ truth. To achieve this:
64
+
65
+ ```bash
66
+ python sample_surface.py --n_points 5000 --n_proc 2 --shape_root PATH_TO_OBJS --save_root PATH_TO_THE_SAMPLE_POINTS
67
+ ```
68
+
69
+ ### Compute Cov and MMD score:
70
+
71
+ After compute the chamfer distance and LFD, to compute the Coverage score and MMD score:
72
+
73
+ ```bash
74
+ python compute_cov_mmd.py
75
+ ```
eval/lfd/evaluation_scripts/compute_lfd.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
8
+
9
+ import random
10
+ import numpy as np
11
+ import ray
12
+ import torch
13
+ import os
14
+ from tqdm import tqdm
15
+ from load_data.interface import LoadData
16
+
17
+
18
+ def read_all_data(folder_list, load_data, add_model_str=True, add_ori_name=False):
19
+ all_data = []
20
+
21
+ for f in folder_list:
22
+ if add_model_str:
23
+ result = load_data.run(os.path.join(f, 'model', 'mesh'))
24
+ elif add_ori_name:
25
+ result = load_data.run(os.path.join(f, f.split('/')[-1], 'mesh'))
26
+ else:
27
+ result = load_data.run(os.path.join(f, 'mesh'))
28
+
29
+ all_data.append(result)
30
+ q8_table = all_data[0][0]
31
+ align_10 = all_data[0][1]
32
+ dest_ArtCoeff = [r[2][np.newaxis, :] for r in all_data]
33
+ dest_FdCoeff_q8 = [r[3][np.newaxis, :] for r in all_data]
34
+ dest_CirCoeff_q8 = [r[4][np.newaxis, :] for r in all_data]
35
+ dest_EccCoeff_q8 = [r[5][np.newaxis, :] for r in all_data]
36
+ SRC_ANGLE = 10
37
+ ANGLE = 10
38
+ CAMNUM = 10
39
+ ART_COEF = 35
40
+ FD_COEF = 10
41
+ n_shape = len(all_data)
42
+ dest_ArtCoeff = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_ArtCoeff, axis=0))).int().cuda().reshape(n_shape, SRC_ANGLE, CAMNUM, ART_COEF)
43
+ dest_FdCoeff_q8 = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_FdCoeff_q8, axis=0))).int().cuda().reshape(n_shape, ANGLE, CAMNUM, FD_COEF)
44
+ dest_CirCoeff_q8 = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_CirCoeff_q8, axis=0))).int().cuda().reshape(n_shape, ANGLE, CAMNUM)
45
+ dest_EccCoeff_q8 = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_EccCoeff_q8, axis=0))).int().cuda().reshape(n_shape, ANGLE, CAMNUM)
46
+ q8_table = torch.from_numpy(np.ascontiguousarray(q8_table)).int().cuda().reshape(256, 256)
47
+ align_10 = torch.from_numpy(np.ascontiguousarray(align_10)).int().cuda().reshape(60, 20) ##
48
+ return q8_table.contiguous(), align_10.contiguous(), dest_ArtCoeff.contiguous(), \
49
+ dest_FdCoeff_q8.contiguous(), dest_CirCoeff_q8.contiguous(), dest_EccCoeff_q8.contiguous()
50
+
51
+ def compute_lfd_all(src_folder_list, tgt_folder_list, log):
52
+ load_data = LoadData()
53
+
54
+ add_ori_name = False
55
+ add_model_str = False
56
+ src_folder_list.sort()
57
+ tgt_folder_list.sort()
58
+
59
+ q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8 = read_all_data(src_folder_list, load_data, add_model_str=False)
60
+ q8_table, align_10, tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8 = read_all_data(tgt_folder_list, load_data, add_model_str=add_model_str, add_ori_name=add_ori_name) ###
61
+
62
+ from lfd_all_compute.lfd import LFD
63
+ lfd = LFD()
64
+ lfd_matrix = lfd.forward(
65
+ q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8,
66
+ tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8, log)
67
+ # print(lfd_matrix)
68
+ # print(lfd_matrix.shape)
69
+ mmd = lfd_matrix.float().min(dim=0)[0].mean()
70
+ mmd_swp = lfd_matrix.float().min(dim=1)[0].mean()
71
+ # print(mmd)
72
+ # print(mmd_swp)
73
+ return lfd_matrix.data.cpu().numpy()
74
+
75
+
76
+
77
+ if __name__ == '__main__':
78
+ import argparse
79
+
80
+ parser = argparse.ArgumentParser()
81
+ parser.add_argument("--save_name", type=str, required=True, help="path to the save resules shapenet dataset")
82
+ parser.add_argument("--dataset_path", type=str, required=True, help="path to the preprocessed shapenet dataset")
83
+ parser.add_argument("--gen_path", type=str, required=True, help="path to the generated models")
84
+ parser.add_argument("--num_workers", type=int, default=1, help="number of workers to run in parallel")
85
+ parser.add_argument("--list", type=str, default=None, help="list file in the training set")
86
+ args = parser.parse_args()
87
+ save_path = '/'.join(args.save_name.split('/')[:-1])
88
+ os.makedirs(save_path, exist_ok=True)
89
+ num_workers = args.num_workers
90
+ listfile = args.list
91
+ ray.init(
92
+ num_cpus=os.cpu_count(),
93
+ num_gpus=num_workers,
94
+ )
95
+ print(f"dataset_path: {args.dataset_path}")
96
+ print(f"gen_path: {args.gen_path}")
97
+ assert os.path.exists(args.dataset_path) and os.path.exists(args.gen_path)
98
+
99
+ tgt_folder_list = sorted(os.listdir(args.dataset_path))
100
+ if listfile is not None:
101
+ valid_folders = [item.strip() for item in open(listfile, 'r').readlines()]
102
+ tgt_folder_list = sorted(list(set(valid_folders) & set(tgt_folder_list)))
103
+ tgt_folder_list = [os.path.join(args.dataset_path, f) for f in tgt_folder_list]
104
+ else:
105
+ tgt_folder_list = [os.path.join(args.dataset_path, f) for f in tgt_folder_list]
106
+
107
+ src_folder_list = os.listdir(args.gen_path)
108
+ random.shuffle(src_folder_list)
109
+ src_folder_list = sorted(src_folder_list[:3000])
110
+ src_folder_list = [os.path.join(args.gen_path, f) for f in src_folder_list]
111
+
112
+ compute_lfd_all_remote = ray.remote(num_gpus=1, num_cpus=os.cpu_count() // num_workers)(compute_lfd_all)
113
+
114
+ print("Check data")
115
+ print(f"len of src_folder_list: {len(src_folder_list)}")
116
+ print(f"len of tgt_folder_list: {len(tgt_folder_list)}")
117
+ # print(src_folder_list[0])
118
+ # print(tgt_folder_list[0])
119
+
120
+ results = []
121
+ for i in range(num_workers):
122
+ i_start = i * len(src_folder_list) // num_workers
123
+ i_end = (i + 1) * len(src_folder_list) // num_workers
124
+ # print(i, i_start, i_end)
125
+ results.append(compute_lfd_all_remote.remote(
126
+ src_folder_list[i_start:i_end],
127
+ tgt_folder_list,
128
+ i==0))
129
+
130
+ lfd_matrix = ray.get(results)
131
+ lfd_matrix = np.concatenate(lfd_matrix, axis=0)
132
+ import pickle
133
+ save_name = args.save_name
134
+ nearest_name = [tgt_folder_list[idx].split("/")[-1] for idx in lfd_matrix.argmin(axis=1)]
135
+ src_folder_list = [src_folder_list[idx].split("/")[-1] for idx in range(len(src_folder_list))]
136
+ pickle.dump([src_folder_list, nearest_name, lfd_matrix], open(save_name, 'wb'))
137
+ print(f"pkl is saved to {save_name}")
eval/lfd/evaluation_scripts/compute_lfd_check_data.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
8
+
9
+ import random
10
+ import shutil
11
+
12
+ import numpy as np
13
+ import ray
14
+ import torch
15
+ import os
16
+ from tqdm import tqdm
17
+ from load_data.interface import LoadData
18
+ import pickle
19
+ from multiprocessing import Pool, cpu_count
20
+
21
+ def read_all_data(folder_list, load_data, add_model_str=True, add_ori_name=False):
22
+ all_data = []
23
+
24
+ for f in folder_list:
25
+ if add_model_str:
26
+ result = load_data.run(os.path.join(f, 'model', 'mesh'))
27
+ elif add_ori_name:
28
+ result = load_data.run(os.path.join(f, f.split('/')[-1], 'mesh'))
29
+ else:
30
+ result = load_data.run(os.path.join(f, 'mesh'))
31
+
32
+ all_data.append(result)
33
+ q8_table = all_data[0][0]
34
+ align_10 = all_data[0][1]
35
+ dest_ArtCoeff = [r[2][np.newaxis, :] for r in all_data]
36
+ dest_FdCoeff_q8 = [r[3][np.newaxis, :] for r in all_data]
37
+ dest_CirCoeff_q8 = [r[4][np.newaxis, :] for r in all_data]
38
+ dest_EccCoeff_q8 = [r[5][np.newaxis, :] for r in all_data]
39
+ SRC_ANGLE = 10
40
+ ANGLE = 10
41
+ CAMNUM = 10
42
+ ART_COEF = 35
43
+ FD_COEF = 10
44
+ n_shape = len(all_data)
45
+ dest_ArtCoeff = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_ArtCoeff, axis=0))).int().cuda().reshape(n_shape, SRC_ANGLE,
46
+ CAMNUM, ART_COEF)
47
+ dest_FdCoeff_q8 = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_FdCoeff_q8, axis=0))).int().cuda().reshape(n_shape, ANGLE,
48
+ CAMNUM, FD_COEF)
49
+ dest_CirCoeff_q8 = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_CirCoeff_q8, axis=0))).int().cuda().reshape(n_shape, ANGLE,
50
+ CAMNUM)
51
+ dest_EccCoeff_q8 = torch.from_numpy(np.ascontiguousarray(np.concatenate(dest_EccCoeff_q8, axis=0))).int().cuda().reshape(n_shape, ANGLE,
52
+ CAMNUM)
53
+ q8_table = torch.from_numpy(np.ascontiguousarray(q8_table)).int().cuda().reshape(256, 256)
54
+ align_10 = torch.from_numpy(np.ascontiguousarray(align_10)).int().cuda().reshape(60, 20) ##
55
+ return q8_table.contiguous(), align_10.contiguous(), dest_ArtCoeff.contiguous(), \
56
+ dest_FdCoeff_q8.contiguous(), dest_CirCoeff_q8.contiguous(), dest_EccCoeff_q8.contiguous()
57
+
58
+
59
+ def compute_lfd_all(src_folder_list, tgt_folder_list, log):
60
+ load_data = LoadData()
61
+
62
+ add_ori_name = False
63
+ add_model_str = False
64
+ src_folder_list.sort()
65
+ tgt_folder_list.sort()
66
+
67
+ q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8 = read_all_data(src_folder_list, load_data,
68
+ add_model_str=False)
69
+ q8_table, align_10, tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8 = read_all_data(tgt_folder_list, load_data,
70
+ add_model_str=add_model_str,
71
+ add_ori_name=add_ori_name) ###
72
+
73
+ from lfd_all_compute.lfd import LFD
74
+ lfd = LFD()
75
+ lfd_matrix = lfd.forward(
76
+ q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8,
77
+ tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8, log)
78
+ # print(lfd_matrix)
79
+ # print(lfd_matrix.shape)
80
+ mmd = lfd_matrix.float().min(dim=0)[0].mean()
81
+ mmd_swp = lfd_matrix.float().min(dim=1)[0].mean()
82
+ # print(mmd)
83
+ # print(mmd_swp)
84
+ return lfd_matrix.data.cpu().numpy()
85
+
86
+ def get_file_size_kb(mesh_path):
87
+ return int(os.path.getsize(mesh_path) / 1024)
88
+
89
+
90
+ if __name__ == '__main__':
91
+ import argparse
92
+
93
+ parser = argparse.ArgumentParser()
94
+ parser.add_argument("--mesh_path", type=str, required=True, help="path to the mesh folder")
95
+ parser.add_argument("--lfd_feat", type=str, required=True, help="path to the preprocessed shapenet dataset")
96
+ parser.add_argument("--save_root", type=str, required=True, help="path to the save resules shapenet dataset")
97
+ parser.add_argument("--num_workers", type=int, default=1, help="number of workers to run in parallel")
98
+ parser.add_argument("--list", type=str, default=None, help="list file in the training set")
99
+ args = parser.parse_args()
100
+ num_workers = args.num_workers
101
+ listfile = args.list
102
+
103
+ mesh_folder_path = args.mesh_path
104
+ lfd_feat_path = args.lfd_feat
105
+ save_root = args.save_root
106
+ os.makedirs(save_root, exist_ok=True)
107
+
108
+
109
+ print(f"mesh_path: {mesh_folder_path}")
110
+ print(f"lfd_feat_path: {lfd_feat_path}")
111
+
112
+ all_folders = os.listdir(mesh_folder_path)
113
+ all_folders.sort()
114
+ print("Get mesh_size")
115
+ mesh_folder_list = []
116
+ mesh_path_list = []
117
+ # mesh_size_list = []
118
+ for mesh_folder in tqdm(all_folders):
119
+ mesh_path = os.path.join(mesh_folder_path, mesh_folder, "mesh.stl")
120
+ mesh_folder_list.append(mesh_folder)
121
+ mesh_path_list.append(mesh_path)
122
+ # mesh_size_list.append(int(os.path.getsize(mesh_path) / 1024))
123
+
124
+ with Pool(processes=cpu_count()) as pool:
125
+ mesh_size_list = list(tqdm(pool.imap(get_file_size_kb, mesh_path_list), total=len(mesh_path_list)))
126
+
127
+ # sort according to the size of the mesh file
128
+ assert len(mesh_size_list) == len(mesh_folder_list)
129
+ # mesh_folder_list = [x for _, x in sorted(zip(mesh_size_list, mesh_folder_list))]
130
+ # mesh_size_list = sorted(mesh_size_list)
131
+ mesh_size_list = np.array(mesh_size_list)
132
+ print(f"Max size: {mesh_size_list.max()}")
133
+ print(f"Min size: {mesh_size_list.min()}")
134
+ print(f"Total {mesh_size_list.shape} mesh_folder to process")
135
+
136
+ tgt_folder_list = mesh_folder_list
137
+
138
+ if listfile is not None:
139
+ valid_folders = [item.strip() for item in open(listfile, 'r').readlines()]
140
+ tgt_folder_list = sorted(list(set(valid_folders) & set(tgt_folder_list)))
141
+ tgt_folder_list = [os.path.join(lfd_feat_path, f) for f in tgt_folder_list]
142
+ else:
143
+ tgt_folder_list = [os.path.join(lfd_feat_path, f) for f in tgt_folder_list]
144
+
145
+ src_folder_list = tgt_folder_list
146
+
147
+ start_from_size_end = 0
148
+ print(f"Start from size_end: {start_from_size_end}")
149
+ print((mesh_size_list>start_from_size_end).sum()/mesh_size_list.shape[0])
150
+
151
+ ray.init(
152
+ num_cpus=os.cpu_count(),
153
+ num_gpus=num_workers,
154
+ )
155
+
156
+ compute_lfd_all_remote = ray.remote(num_gpus=1, num_cpus=os.cpu_count() // num_workers)(compute_lfd_all)
157
+
158
+ print("Check data")
159
+ print(f"len of src_folder_list: {len(src_folder_list)}")
160
+ print(f"len of tgt_folder_list: {len(tgt_folder_list)}")
161
+ print(src_folder_list[0])
162
+ print(tgt_folder_list[0])
163
+
164
+ batch_size = 1
165
+ offset = 2
166
+
167
+ for size_start in tqdm(range(mesh_size_list.min(), mesh_size_list.max(), batch_size)):
168
+ size_end = size_start + offset
169
+ print(f"size_start: {size_start}, size_end: {size_end}, max_size: {mesh_size_list.max()}")
170
+ if size_end <= start_from_size_end:
171
+ continue
172
+ # get the folder list for the current batch
173
+ hitted_idx = np.where((mesh_size_list >= size_start) & (mesh_size_list <= size_end))[0]
174
+ print(f"len of hitted folder: {len(hitted_idx)}")
175
+ if len(hitted_idx) == 0:
176
+ continue
177
+ local_num_workers = min(num_workers, len(hitted_idx))
178
+ local_tgt_folder_list = [tgt_folder_list[i] for i in hitted_idx]
179
+ local_src_folder_list = local_tgt_folder_list
180
+ results = []
181
+ for i in range(local_num_workers):
182
+ local_i_start = i * len(local_src_folder_list) // local_num_workers
183
+ local_i_end = (i + 1) * len(local_src_folder_list) // local_num_workers
184
+ results.append(compute_lfd_all_remote.remote(
185
+ local_src_folder_list[local_i_start:local_i_end],
186
+ local_tgt_folder_list,
187
+ i == 0))
188
+ lfd_matrix = ray.get(results)
189
+ lfd_matrix = np.concatenate(lfd_matrix, axis=0)
190
+
191
+ save_name = os.path.join(save_root, f"lfd_{size_start:07d}kb_{size_end:07d}kb.pkl")
192
+ pickle.dump([local_tgt_folder_list, lfd_matrix], open(save_name, 'wb'))
193
+ print(f"pkl is saved to {save_name}\n\n")
eval/lfd/evaluation_scripts/compute_lfd_feat/compute_lfd_feat_multiprocess.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
8
+
9
+ import argparse
10
+ import glob
11
+
12
+ import numpy as np
13
+ import torch
14
+ import os
15
+ import random
16
+ from tqdm import tqdm
17
+ from pathlib import Path
18
+ from multiprocessing import Pool
19
+ # import kaolin as kal
20
+ import point_cloud_utils as pcu
21
+ import trimesh
22
+
23
+ from tqdm import tqdm
24
+
25
+
26
+ def seed_everything(seed):
27
+ if seed < 0:
28
+ return
29
+ torch.manual_seed(seed)
30
+ np.random.seed(seed)
31
+ random.seed(seed)
32
+
33
+
34
+ def load_mesh_v(mesh_name, normalized_scale=0.9):
35
+ if mesh_name.endswith('obj') or mesh_name.endswith('OBJ'):
36
+ mesh_1 = kal.io.obj.import_mesh(mesh_name)
37
+ vertices = mesh_1.vertices.cpu().numpy()
38
+ mesh_f1 = mesh_1.faces.cpu().numpy()
39
+ # elif mesh_name.endswith('ply'):
40
+ # vertices, mesh_f1 = pcu.load_mesh_vf(mesh_name)
41
+ elif mesh_name.endswith('stl') or mesh_name.endswith('ply'):
42
+ mesh = trimesh.load_mesh(mesh_name, force='mesh')
43
+ if isinstance(mesh, trimesh.Scene):
44
+ # we lose texture information here
45
+ mesh = trimesh.util.concatenate(
46
+ tuple(trimesh.Trimesh(vertices=g.vertices, faces=g.faces)
47
+ for g in mesh.geometry.values()))
48
+ vertices = np.asarray(mesh.vertices)
49
+ mesh_f1 = np.asarray(mesh.faces)
50
+ else:
51
+ raise NotImplementedError
52
+
53
+ if vertices.shape[0] == 0:
54
+ return None, None
55
+
56
+ scale = (vertices.max(axis=0) - vertices.min(axis=0)).max()
57
+ mesh_v1 = vertices / (scale+1e-6) * normalized_scale
58
+ return mesh_v1, mesh_f1
59
+
60
+
61
+ from lfd_me import MeshEncoder
62
+ from functools import partial
63
+
64
+
65
+ def align_mesh_feature(mesh_name, align_feature_sample_folder):
66
+ # mesh_fodler = mesh_name.split('/')[-3:]
67
+ # print(mesh_fodler)
68
+ # mesh_fodler[-1] = mesh_fodler[-1].split('.')[0]
69
+ # print(mesh_fodler)
70
+ # mesh_fodler = '/'.join(mesh_fodler)
71
+ mesh_fodler = os.path.basename(os.path.dirname(mesh_name))
72
+ mesh_fodler = os.path.join(align_feature_sample_folder, mesh_fodler)
73
+ # print(mesh_fodler)
74
+
75
+ if not os.path.exists(mesh_fodler):
76
+ os.makedirs(mesh_fodler)
77
+ if os.path.exists(os.path.join(mesh_fodler, 'mesh_q4_v1.8.art')) and os.path.getsize(
78
+ os.path.join(mesh_fodler, 'mesh_q4_v1.8.art')) > 1000:
79
+ temp_dir_path = Path(mesh_fodler)
80
+ file_name = 'mesh'
81
+ temp_path = temp_dir_path / "{}.obj".format(file_name)
82
+ path = temp_path.with_suffix("").as_posix()
83
+ return path
84
+
85
+ mesh_v, mesh_f = load_mesh_v(mesh_name, normalized_scale=1.0)
86
+ if mesh_v is None:
87
+ return None # No face here
88
+
89
+ mesh = MeshEncoder(mesh_v, mesh_f, folder=mesh_fodler, file_name='mesh', )
90
+ mesh.align_mesh()
91
+ return mesh.get_path()
92
+
93
+
94
+ def compute_lfd_feture(sample_pcs, n_process, save_path):
95
+ align_feature_sample_folder = save_path
96
+ os.makedirs(align_feature_sample_folder, exist_ok=True)
97
+ print('==> one model')
98
+ align_mesh_feature(sample_pcs[0], align_feature_sample_folder)
99
+ N_process = n_process
100
+ path_list = []
101
+ if n_process == 0:
102
+ for i in tqdm(range(len(sample_pcs))):
103
+ align_mesh_feature(sample_pcs[i], align_feature_sample_folder)
104
+ exit()
105
+ print('==> multi process')
106
+ pool = Pool(N_process)
107
+ for x in tqdm(
108
+ pool.imap_unordered(partial(align_mesh_feature, align_feature_sample_folder=align_feature_sample_folder), sample_pcs),
109
+ total=len(sample_pcs)):
110
+ path_list.append(x)
111
+ pool.close()
112
+ pool.join()
113
+
114
+
115
+ def load_data_with_prefix(root_folder, prefix, folder_list_txt=None):
116
+ data_files = []
117
+ folder_list = []
118
+ if folder_list_txt is not None:
119
+ with open(folder_list_txt, "r") as f:
120
+ folder_list = f.read().splitlines()
121
+ # Walk through the directory tree starting from the root folder
122
+ for root, dirs, files in os.walk(root_folder):
123
+ if folder_list_txt is not None and os.path.basename(root) not in folder_list:
124
+ continue
125
+ for filename in files:
126
+ # Check if the file ends with the specified prefix
127
+ if filename.endswith(prefix):
128
+ file_path = os.path.join(root, filename)
129
+ data_files.append(file_path)
130
+
131
+ return data_files
132
+
133
+
134
+ if __name__ == "__main__":
135
+ parser = argparse.ArgumentParser()
136
+ parser.add_argument("--gen_path", type=str, required=True, help="path to the generated models")
137
+ parser.add_argument("--save_path", type=str, required=True, help="path to save the generated features for each model")
138
+ parser.add_argument("--n_models", type=int, default=-1, help="Number of models used for evaluation")
139
+ parser.add_argument("--n_process", type=int, default=-1, help="Number of process used for evaluation")
140
+ parser.add_argument("--prefix", type=str, required=False, default="mesh.ply")
141
+
142
+ args = parser.parse_args()
143
+ if args.n_process == -1:
144
+ num_cpus = min(64, os.cpu_count())
145
+ else:
146
+ num_cpus = args.n_process
147
+ models = []
148
+ all_folders = os.listdir(args.gen_path)
149
+ for folder in tqdm(all_folders):
150
+ if not os.path.isdir(os.path.join(args.gen_path, folder)):
151
+ continue
152
+ files = glob.glob(os.path.join(args.gen_path, folder, args.prefix))
153
+ if len(files) == 0:
154
+ continue
155
+ models.append(os.path.abspath(files[0]))
156
+ models.sort()
157
+ print(f"Loading {len(models)} models")
158
+ compute_lfd_feture(models, num_cpus, os.path.abspath(args.save_path))
eval/lfd/evaluation_scripts/compute_lfd_feat/dummy-1920x1080.conf ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Section "Monitor"
2
+ Identifier "Monitor0"
3
+ HorizSync 28.0-80.0
4
+ VertRefresh 48.0-75.0
5
+ # https://arachnoid.com/modelines/
6
+ # 1920x1080 @ 60.00 Hz (GTF) hsync: 67.08 kHz; pclk: 172.80 MHz
7
+ Modeline "1920x1080_60.00" 172.80 1920 2040 2248 2576 1080 1081 1084 1118 -HSync +Vsync
8
+ EndSection
9
+
10
+ Section "Device"
11
+ Identifier "Card0"
12
+ Driver "dummy"
13
+ VideoRam 256000
14
+ EndSection
15
+
16
+ Section "Screen"
17
+ DefaultDepth 24
18
+ Identifier "Screen0"
19
+ Device "Card0"
20
+ Monitor "Monitor0"
21
+ SubSection "Display"
22
+ Depth 24
23
+ Modes "1920x1080_60.00"
24
+ EndSubSection
25
+ EndSection
eval/lfd/evaluation_scripts/compute_lfd_feat/lfd_me.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
8
+ '''
9
+ Function is modified based on https://github.com/kacperkan/light-field-distance
10
+ '''
11
+ import argparse
12
+ import sys
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ import tempfile
17
+ import uuid
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ import numpy as np
22
+ import trimesh
23
+
24
+ SIMILARITY_TAG = b"SIMILARITY:"
25
+ CURRENT_DIR = Path(__file__).parent.parent.parent / 'light-field-distance/lfd/Executable'
26
+
27
+ GENERATED_FILES_NAMES = [
28
+ "all_q4_v1.8.art",
29
+ "all_q8_v1.8.art",
30
+ "all_q8_v1.8.cir",
31
+ "all_q8_v1.8.ecc",
32
+ "all_q8_v1.8.fd",
33
+ ]
34
+
35
+ OUTPUT_NAME_TEMPLATES = [
36
+ "{}_q4_v1.8.art",
37
+ "{}_q8_v1.8.art",
38
+ "{}_q8_v1.8.cir",
39
+ "{}_q8_v1.8.ecc",
40
+ "{}_q8_v1.8.fd",
41
+ ]
42
+
43
+
44
+ class MeshEncoder:
45
+ """Class holding an object and preprocessing it using an external cmd."""
46
+
47
+ def __init__(self, vertices: np.ndarray, triangles: np.ndarray, folder=None, file_name=None):
48
+ """Instantiate the class.
49
+
50
+ It instantiates an empty, temporary folder that will hold any
51
+ intermediate data necessary to calculate Light Field Distance.
52
+
53
+ Args:
54
+ vertices: np.ndarray of vertices consisting of 3 coordinates each.
55
+ triangles: np.ndarray where each entry is a vector with 3 elements.
56
+ Each element correspond to vertices that create a triangle.
57
+ """
58
+ self.mesh = trimesh.Trimesh(vertices=vertices, faces=triangles)
59
+ if folder is None:
60
+ folder = tempfile.mkdtemp()
61
+ if file_name is None:
62
+ file_name = uuid.uuid4()
63
+ self.temp_dir_path = Path(folder)
64
+ self.file_name = file_name
65
+ self.temp_path = self.temp_dir_path / "{}.obj".format(self.file_name)
66
+ self.mesh.export(self.temp_path.as_posix())
67
+
68
+ def get_path(self) -> str:
69
+ """Get path of the object.
70
+
71
+ Commands require that an object is represented without any extension.
72
+
73
+ Returns:
74
+ Path to the temporary object created in the file system that
75
+ holds the Wavefront OBJ data of the object.
76
+ """
77
+ return self.temp_path.with_suffix("").as_posix()
78
+
79
+ def align_mesh(self):
80
+ """Create data of a 3D mesh to calculate Light Field Distance.
81
+
82
+ It runs an external command that create intermediate files and moves
83
+ these files to created temporary folder.
84
+
85
+ Returns:
86
+ None
87
+ """
88
+ run_dir = self.temp_dir_path
89
+ # copy_file = []
90
+ copy_file = ['3DAlignment', 'align10.txt', 'q8_table', '12_0.obj',
91
+ '12_1.obj',
92
+ '12_2.obj',
93
+ '12_3.obj',
94
+ '12_4.obj',
95
+ '12_5.obj',
96
+ '12_6.obj',
97
+ '12_7.obj',
98
+ '12_8.obj',
99
+ '12_9.obj', ]
100
+ for f in copy_file:
101
+ os.system(
102
+ 'cp %s %s' % (os.path.join(CURRENT_DIR, f),
103
+ os.path.join(run_dir, f)))
104
+ env = os.environ.copy()
105
+ env["DISPLAY"] = ":0"
106
+ process = subprocess.Popen(
107
+ ['./3DAlignment', self.temp_path.with_suffix("").as_posix()],
108
+ cwd=run_dir,
109
+ stdin=subprocess.PIPE,
110
+ stdout=subprocess.PIPE,
111
+ stderr=subprocess.PIPE,
112
+ env=env
113
+ )
114
+
115
+ output, err = process.communicate()
116
+
117
+ if len(err) > 0:
118
+ print(err)
119
+ sys.exit(1)
120
+
121
+ for file, out_file in zip(
122
+ GENERATED_FILES_NAMES, OUTPUT_NAME_TEMPLATES
123
+ ):
124
+ shutil.move(
125
+ os.path.join(run_dir, file),
126
+ (
127
+ self.temp_dir_path / out_file.format(self.file_name)
128
+ ).as_posix(),
129
+ )
130
+ for f in copy_file:
131
+ os.system('rm -rf %s' % (os.path.join(run_dir, f)))
132
+
133
+ os.system('rm -rf %s' % (self.temp_path.as_posix()))
eval/lfd/evaluation_scripts/lfd_all_compute/lfd.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
8
+
9
+ # !/usr/bin/env python
10
+ # -*- coding:utf-8 -*-
11
+ import torch
12
+ from tqdm import tqdm
13
+
14
+
15
+ def calculate_lfd_distance(
16
+ q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8,
17
+ tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8):
18
+ with torch.no_grad():
19
+ src_ArtCoeff = src_ArtCoeff.unsqueeze(dim=1).unsqueeze(dim=1).expand(-1, 10, 10, -1, -1, -1)
20
+ tgt_ArtCoeff = tgt_ArtCoeff.unsqueeze(dim=3).unsqueeze(dim=3).expand(-1, -1, -1, 10, 10, -1)
21
+ art_distance = q8_table[src_ArtCoeff.reshape(-1).long(), tgt_ArtCoeff.reshape(-1).long()]
22
+ art_distance = art_distance.reshape(
23
+ src_ArtCoeff.shape[0], src_ArtCoeff.shape[1], src_ArtCoeff.shape[2],
24
+ src_ArtCoeff.shape[3],
25
+ src_ArtCoeff.shape[4], src_ArtCoeff.shape[5])
26
+ art_distance = torch.sum(art_distance, dim=-1)
27
+
28
+ src_FdCoeff_q8 = src_FdCoeff_q8.unsqueeze(dim=1).unsqueeze(dim=1).expand(-1, 10, 10, -1, -1, -1)
29
+ tgt_FdCoeff_q8 = tgt_FdCoeff_q8.unsqueeze(dim=3).unsqueeze(dim=3).expand(-1, -1, -1, 10, 10, -1)
30
+ fd_distance = q8_table[src_FdCoeff_q8.reshape(-1).long(), tgt_FdCoeff_q8.reshape(-1).long()]
31
+ fd_distance = fd_distance.reshape(
32
+ src_FdCoeff_q8.shape[0], src_FdCoeff_q8.shape[1], src_FdCoeff_q8.shape[2],
33
+ src_FdCoeff_q8.shape[3], src_FdCoeff_q8.shape[4], src_FdCoeff_q8.shape[5])
34
+ fd_distance = torch.sum(fd_distance, dim=-1) * 2.0
35
+
36
+ src_CirCoeff_q8 = src_CirCoeff_q8.unsqueeze(dim=1).unsqueeze(dim=1).expand(-1, 10, 10, -1, -1)
37
+ tgt_CirCoeff_q8 = tgt_CirCoeff_q8.unsqueeze(dim=3).unsqueeze(dim=3).expand(-1, -1, -1, 10, 10)
38
+ cir_distance = q8_table[src_CirCoeff_q8.reshape(-1).long(), tgt_CirCoeff_q8.reshape(-1).long()]
39
+ cir_distance = cir_distance.reshape(
40
+ src_CirCoeff_q8.shape[0], src_CirCoeff_q8.shape[1],
41
+ src_CirCoeff_q8.shape[2],
42
+ src_CirCoeff_q8.shape[3], src_CirCoeff_q8.shape[4])
43
+ cir_distance = cir_distance * 2.0
44
+ src_EccCoeff_q8 = src_EccCoeff_q8.unsqueeze(dim=1).unsqueeze(dim=1).expand(-1, 10, 10, -1, -1)
45
+ tgt_EccCoeff_q8 = tgt_EccCoeff_q8.unsqueeze(dim=3).unsqueeze(dim=3).expand(-1, -1, -1, 10, 10)
46
+ ecc_distance = q8_table[src_EccCoeff_q8.reshape(-1).long(), tgt_EccCoeff_q8.reshape(-1).long()]
47
+ ecc_distance = ecc_distance.reshape(
48
+ src_EccCoeff_q8.shape[0], src_EccCoeff_q8.shape[1],
49
+ src_EccCoeff_q8.shape[2], src_EccCoeff_q8.shape[3],
50
+ src_EccCoeff_q8.shape[4])
51
+ cost = art_distance + fd_distance + cir_distance + ecc_distance
52
+ # find the cloest matching
53
+ # cost shape: batch_size x src_camera x src_angle x dst_camera x dst_angle
54
+ cost = cost.permute(0, 1, 3, 2, 4).long()
55
+ align_n = align_10[:, :10].reshape(-1)
56
+ cost_bxsrc_cxdst_cxsrc_axdst_a = cost
57
+ align_err = torch.gather(
58
+ input=cost_bxsrc_cxdst_cxsrc_axdst_a,
59
+ index=align_n.reshape(1, 1, 1, 60 * 10, 1).expand(
60
+ cost.shape[0], cost.shape[1],
61
+ cost.shape[2], 60 * 10, 10).long(),
62
+ dim=3)
63
+ align_err = align_err.reshape(cost.shape[0], cost.shape[1], cost.shape[2], 60, 10, 10)
64
+ sum_diag = 0
65
+ for i in range(10):
66
+ sum_diag += align_err[:, :, :, :, i, i]
67
+ sum_diag = sum_diag.reshape(cost.shape[0], -1)
68
+ dist = torch.min(sum_diag, dim=-1)[0]
69
+ return dist
70
+
71
+
72
+ class LightFieldDistanceFunction(torch.autograd.Function):
73
+ @staticmethod
74
+ def forward(
75
+ ctx, q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8,
76
+ tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8, log):
77
+ n = src_ArtCoeff.shape[0]
78
+ m = tgt_ArtCoeff.shape[0]
79
+ ##############
80
+ # This is only calculating one pair of distance
81
+ print(f"src_size: {n}")
82
+ print(f"tgt_size: {m}")
83
+ all_dist = []
84
+ with torch.no_grad():
85
+ for i in tqdm(range(n), mininterval=60, disable=not log):
86
+ start_idx = 0
87
+ n_all_run = tgt_ArtCoeff.shape[0]
88
+ n_each_run = 1000
89
+ one_run_d = []
90
+ while start_idx < n_all_run:
91
+ end_idx = min(n_all_run, start_idx + n_each_run)
92
+ run_length = end_idx - start_idx
93
+ d = calculate_lfd_distance(
94
+ q8_table, align_10,
95
+ src_ArtCoeff[i:i + 1].expand(run_length, -1, -1, -1),
96
+ src_FdCoeff_q8[i:i + 1].expand(run_length, -1, -1, -1),
97
+ src_CirCoeff_q8[i:i + 1].expand(run_length, -1, -1),
98
+ src_EccCoeff_q8[i:i + 1].expand(run_length, -1, -1),
99
+ tgt_ArtCoeff[start_idx:end_idx],
100
+ tgt_FdCoeff_q8[start_idx:end_idx],
101
+ tgt_CirCoeff_q8[start_idx:end_idx],
102
+ tgt_EccCoeff_q8[start_idx:end_idx])
103
+ start_idx = end_idx
104
+ one_run_d.append(d)
105
+ d = torch.cat(one_run_d, dim=0)
106
+ all_dist.append(d.unsqueeze(dim=0))
107
+ dist = torch.cat(all_dist, dim=0)
108
+
109
+ return dist
110
+
111
+ @staticmethod
112
+ def backward(ctx, graddist):
113
+ raise NotImplementedError
114
+ return None, None, None, None, None, None, None, None, None, None
115
+
116
+
117
+ class LFD(torch.nn.Module):
118
+ def forward(
119
+ self, q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8,
120
+ tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8, log):
121
+ return LightFieldDistanceFunction.apply(
122
+ q8_table, align_10, src_ArtCoeff, src_FdCoeff_q8, src_CirCoeff_q8, src_EccCoeff_q8,
123
+ tgt_ArtCoeff, tgt_FdCoeff_q8, tgt_CirCoeff_q8, tgt_EccCoeff_q8, log)