shuinb commited on
Commit
ca736e6
·
verified ·
1 Parent(s): 652f5ca

Finalize reproducible reconstruction package and remove superseded sources

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. codes/reconstruction/FlyingWithPhotons/.gitignore +0 -7
  2. codes/reconstruction/FlyingWithPhotons/LICENSE +0 -201
  3. codes/reconstruction/FlyingWithPhotons/README.md +0 -72
  4. codes/reconstruction/FlyingWithPhotons/__pycache__/train_ours.cpython-312.pyc +0 -0
  5. codes/reconstruction/FlyingWithPhotons/__pycache__/utils.cpython-312.pyc +0 -0
  6. codes/reconstruction/FlyingWithPhotons/configs/eval.ini +0 -6
  7. codes/reconstruction/FlyingWithPhotons/configs/train.ini +0 -55
  8. codes/reconstruction/FlyingWithPhotons/eval.py +0 -5
  9. codes/reconstruction/FlyingWithPhotons/evaluation/__init__.py +0 -4
  10. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/__init__.cpython-312.pyc +0 -0
  11. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/arguments.cpython-312.pyc +0 -0
  12. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/cli.cpython-312.pyc +0 -0
  13. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/core.cpython-312.pyc +0 -0
  14. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/evaluator.cpython-312.pyc +0 -0
  15. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/image_metrics.cpython-312.pyc +0 -0
  16. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/io.cpython-312.pyc +0 -0
  17. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/renderer.cpython-312.pyc +0 -0
  18. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/units.cpython-312.pyc +0 -0
  19. codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/worker.cpython-312.pyc +0 -0
  20. codes/reconstruction/FlyingWithPhotons/evaluation/arguments.py +0 -64
  21. codes/reconstruction/FlyingWithPhotons/evaluation/cli.py +0 -54
  22. codes/reconstruction/FlyingWithPhotons/evaluation/core.py +0 -81
  23. codes/reconstruction/FlyingWithPhotons/evaluation/evaluator.py +0 -161
  24. codes/reconstruction/FlyingWithPhotons/evaluation/image_metrics.py +0 -114
  25. codes/reconstruction/FlyingWithPhotons/evaluation/io.py +0 -30
  26. codes/reconstruction/FlyingWithPhotons/evaluation/renderer.py +0 -100
  27. codes/reconstruction/FlyingWithPhotons/evaluation/units.py +0 -84
  28. codes/reconstruction/FlyingWithPhotons/evaluation/worker.py +0 -21
  29. codes/reconstruction/FlyingWithPhotons/loaders/__init__.py +0 -0
  30. codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/__init__.cpython-312.pyc +0 -0
  31. codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/calibration.cpython-312.pyc +0 -0
  32. codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/regular_loader_our.cpython-312.pyc +0 -0
  33. codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/streaming_loader.cpython-312.pyc +0 -0
  34. codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/utils.cpython-312.pyc +0 -0
  35. codes/reconstruction/FlyingWithPhotons/loaders/calibration.py +0 -12
  36. codes/reconstruction/FlyingWithPhotons/loaders/regular_loader_our.py +0 -363
  37. codes/reconstruction/FlyingWithPhotons/loaders/streaming_loader.py +0 -208
  38. codes/reconstruction/FlyingWithPhotons/loaders/utils.py +0 -12
  39. codes/reconstruction/FlyingWithPhotons/misc/__init__.py +0 -0
  40. codes/reconstruction/FlyingWithPhotons/misc/__pycache__/__init__.cpython-312.pyc +0 -0
  41. codes/reconstruction/FlyingWithPhotons/misc/__pycache__/summary.cpython-312.pyc +0 -0
  42. codes/reconstruction/FlyingWithPhotons/misc/__pycache__/transient_volrend.cpython-312.pyc +0 -0
  43. codes/reconstruction/FlyingWithPhotons/misc/dataset_utils.py +0 -169
  44. codes/reconstruction/FlyingWithPhotons/misc/summary.py +0 -116
  45. codes/reconstruction/FlyingWithPhotons/misc/transient_volrend.py +0 -637
  46. codes/reconstruction/FlyingWithPhotons/radiance_fields/__init__.py +0 -0
  47. codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/__init__.cpython-312.pyc +0 -0
  48. codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/ngp.cpython-312.pyc +0 -0
  49. codes/reconstruction/FlyingWithPhotons/radiance_fields/ngp.py +0 -306
  50. codes/reconstruction/FlyingWithPhotons/requirements.txt +0 -23
codes/reconstruction/FlyingWithPhotons/.gitignore DELETED
@@ -1,7 +0,0 @@
1
- __pycache__/
2
- *.pyc
3
- results/
4
- exp/
5
- runs/
6
- *.pth
7
- *.ckpt
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/README.md DELETED
@@ -1,72 +0,0 @@
1
- # FlyingWithPhotons 最小复现版
2
-
3
- 保留原生训练、模型与采样代码;共同指标集中在 `evaluation/`,唯一评价入口为 `eval.py`。
4
-
5
- 在项目根目录执行;服务器模型解释器为 `/work/runrong/.conda/envs/Fwp/bin/python`:
6
-
7
- ```bash
8
- export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python
9
- python train_ours.py -c configs/train.ini
10
- python eval.py render -c configs/train.ini --config configs/eval.ini \
11
- --checkpoint_dir /absolute/checkpoint_directory --step 300000 \
12
- --output /absolute/new_result_directory
13
- ```
14
-
15
- checkpoint 目录的训练归一化记录(或原 `params_full.txt`)必须与配置中的 dataset_scale、gamma 一致。
16
-
17
- 示例为 design_floor1 / 10 视角,参数模板来自原 fence_box 配置,不代表论文完整历史配置。其他场景、3/5 视角需使用真实训练参数和 canonical 测试位姿。保留单值/二维硬件偏移的兼容处理;训练时的编码、裁剪与原生射线模型未重写。
18
-
19
- ## 共同评价协议(V4)
20
-
21
- `eval.py` 是唯一公开评价入口,`render` 和 `saved` 最终均调用 `evaluation/evaluator.py`。`evaluation/renderer.py` 仅适配本方法的模型和射线采样;直方图和图像指标实现与其他两个项目相同。原来的两个 `shared_*` 包、`evaluate_metrics_shared.py`、FWP 的 `eval_ours.py` 和独立旧评分分支已移除。
22
-
23
- ### 强度尺度与直方图 PSNR
24
-
25
- 评分前逐 bin 恢复全曝光光子计数:
26
-
27
- ```
28
- trnerf / transientangelo: prediction_counts = prediction_encoded * actual_training_scale
29
- FlyingWithPhotons: prediction_counts = prediction_encoded ** training_gamma * dataset_scale
30
- reference_counts: 共同参考缓存中的已标定、未独立归一化的光子计数
31
- MSE = mean((prediction_counts - reference_counts)^2) # 共同有效像素的全部 bins / channels
32
- histogram_psnr = 20*log10(P_scene) - 10*log10(MSE)
33
- ```
34
-
35
- `P_scene` 固定于同一场景的十视角训练候选池,在三种方法及 3/5/10 视角配置之间共用。预测峰值、测试最大值和每视角拟合系数都不用于确定它。预测直方图不做上限裁剪、显示 gamma 或曝光拟合;FWP 的逆训练 gamma 在积分前逐 bin 执行。缺失实际训练尺度时直接报错,禁止用测试集最大值代替。TN/FWP 新训练会记录 `image_metric_normalization.json`;TA 将训练尺度写入 checkpoint。历史权重须提供经过核实的训练常数,代码不能从测试集推断它。
36
-
37
- 共同参考由校准后全计数 GT 生成;掩码为硬件有效像素、GT 峰值 ≥100、正信号的交集,独立于预测。直方图峰值 `P_scene` 与积分图像尺度 `D_scene` 是两个不同的固定量。显示图像 PSNR、SSIM、LPIPS 沿用整理前 V4 所采用的显示变换,另报无显示 gamma 的 `linear_psnr`。这些图像分数不应标成直方图 PSNR。SSIM 使用完整有效 7×7 窗口;LPIPS 使用统一环境的 VGG v0.1 / FP32。
38
-
39
- ### 对 Q6–Q8 的代码说明
40
-
41
- - **Q6:不是未经修改的发布版 eval.py。** 当前只提供统一 V4;取消旧 `scale_int` 和动态预测/GT 峰值评分。GT、掩码、固定场景尺度来自同一份 contract。原生测试均执行 30 次前向:TN 每次重新获取带抖动射线,TA 复用同一抖动批次,FWP 复用像素射线。因此不能把三者概括为“30 次独立像素抖动”。这些方法自身的采样逻辑保留。
42
- - **Q7:内部归一化不直接作为比较尺度。** TN/TA 预测乘回实际训练常数;FWP 逐 bin 逆训练 gamma 并乘回训练 dataset_scale;共同 GT 直接使用计数。测试加载器内部即使独立归一化,也不会把它的归一化 GT 或最大值用于评分。这解决当前流程中由训练/测试独立归一化引入的比较尺度不一致。
43
- - **Q8:三种视角设置均使用共同的 canonical test.json 帧及原始位姿。** 九场景合计 158 帧,逐场景 contract 强制核对完整唯一帧集合及位姿,拒绝只评部分帧或同名不同位姿。低视角下剩余训练候选帧不额外加入测试;十视角候选池仍用于冻结共同评价尺度,属于评价标定数据,不作为低视角方法的额外训练输入。
44
-
45
- 以上描述的是修订后的代码协议,不能用来证明历史论文分数已经重算。此次目录整理没有重新训练模型,也没有完成九场景全量模型评测。
46
-
47
- ### 输出、环境与迁移
48
-
49
- 输出为 `prediction_manifest.json` 和 `unified_metrics/` 下的协议记录、逐视角指标、完整集合汇总及浮点评分数组。记录含训练尺度、gamma、共同参考/掩码校验和、评分代码哈希和解释器路径。可加 `--save-predictions` 保存未裁剪编码直方图以便复算;不保存旧口径指标和旧图表。已有结果目录禁止覆盖。
50
-
51
- 三个项目必须使用同一个图像评价环境。服务器运行前设置:
52
-
53
- ```bash
54
- export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python
55
- ```
56
-
57
- 迁移机器后将它改为共同评价环境的 Python 绝对路径。数据、标定、权重、共同参考缓存不复制进代码包;README 中的示例配置仍指向服务器的实际路径,发布数据时需同时提供对应 contract/GT 缓存并改为新路径。每种方法使用同一场景的同一份 contract。保存目录名中的旧日期仅是外部参考数据的位置,不再是代码导入依赖。
58
-
59
- 评分已有预测统一使用 `python eval.py saved --help` 查看参数,例如:
60
-
61
- ```bash
62
- python eval.py saved --prediction-dir /absolute/predictions \
63
- --prediction-manifest /absolute/predictions/prediction_manifest.json \
64
- --prediction-scale ACTUAL_TRAINING_SCALE --prediction-gamma 1 \
65
- --prediction-bin-width-s 7.5e-10 \
66
- --shared-reference-contract /absolute/reference/contract.json \
67
- --output /absolute/new_scores --device cpu
68
- ```
69
-
70
- FWP 编码输出填写真实训练 gamma;已经恢复完整计数的导出填写 scale=1、gamma=1。有单位记录的 manifest 与命令参数冲突时会报错。
71
-
72
- `requirements.txt` 保留各模型依赖。先安装匹配 CUDA 11.8 的 PyTorch 2.5.1 / torchvision 0.20.1,再安装其余依赖和 CUDA 扩展;模型环境可以不同,图像评价子进程保持一致。训练日志中的训练集损失/PSNR 仅用于优化诊断,不是测试集 benchmark 分数。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/__pycache__/train_ours.cpython-312.pyc DELETED
Binary file (12.1 kB)
 
codes/reconstruction/FlyingWithPhotons/__pycache__/utils.cpython-312.pyc DELETED
Binary file (33.3 kB)
 
codes/reconstruction/FlyingWithPhotons/configs/eval.ini DELETED
@@ -1,6 +0,0 @@
1
- # STB design_floor1 / 10 views example. See README for configuration origin.
2
- warped = True
3
- t_min_test = 0
4
- t_max_test = 672
5
- transforms_path = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views/transforms_test.json"
6
- shared_reference_contract = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/contract.json"
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/configs/train.ini DELETED
@@ -1,55 +0,0 @@
1
- # STB design_floor1 / 10 views example. See README for configuration origin.
2
- exp_name = "design_floor1_10views"
3
- dataset_scale = 1000
4
- meas_peak_min = 20
5
- img_scale = 100
6
- data_root = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views"
7
- measurement_root = "/work/runrong/dataset/paper_data/design_floor1"
8
- version = captured
9
- exposure_time = 0.11242217175
10
- n_bins = 672
11
- t_min = 0
12
- t_max = 672
13
- thold_warmup = 20000
14
- gamma = 2
15
- aabb = "[-30.723363, -32.531209, -1.819858, 30.377352, 12.024207, 9.260004]"
16
- depth_global_offset_bins = 17
17
- depth_offset_valid_max = 10.0
18
- img_height = 192
19
- img_width = 256
20
- img_height_test = 192
21
- img_width_test = 256
22
- device = cuda:0
23
- prop_delay = "True"
24
- view_time_align = "True"
25
- view_time_align_quantile = 0.7
26
- view_time_align_target_bin = -1
27
- view_time_align_max_abs_bins = 96
28
- streaming = False
29
- summary = "True"
30
- outpath = "./results"
31
- steps_till_checkpoint = 10000
32
- summary_freq = 10000
33
- max_steps = 150010
34
- target_sample_batch_size = 262054
35
- seed = 42
36
- pixels_to_plot = ["(40, 60)", "(60, 55)", "(30, 55)"]
37
- hardware_shift = "True"
38
- hardware_shift_downsample = 8
39
- hardware_shift_max_abs_bins = 12
40
- intrinsics_path = "/work/runrong/dataset/intrinsics.npy"
41
- alpha_thre = 0
42
- lr = 0.001
43
- weight_decay = 1e-6
44
- render_step_size = 5e-2
45
- cone_angle = 0
46
- near_plane = 0.0
47
- far_plane = 33
48
- init_batch_size = 32
49
- occ_thre = 0.001
50
- grid_resolution = 256
51
- grid_nlvl = 2
52
- img_shape = 256
53
- img_shape_test = 256
54
- final = True
55
- depth_offset_map = "/work/runrong/dataset/paper1_data/offset.txt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/eval.py DELETED
@@ -1,5 +0,0 @@
1
- """The only public evaluation entry: render predictions or score saved histograms."""
2
- from evaluation.cli import main
3
-
4
- if __name__ == "__main__":
5
- main()
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/__init__.py DELETED
@@ -1,4 +0,0 @@
1
- """Common count-domain transient evaluation, independent of model training units."""
2
- PROTOCOL = 'shared_transient_counts_v4_20261016'
3
- TRANSIENT_KEYS = ('histogram_psnr', 'histogram_mse_counts', 'histogram_mae_counts',
4
- 'depth_l1_m', 'transient_iou')
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (471 Bytes)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/arguments.cpython-312.pyc DELETED
Binary file (2.46 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/cli.cpython-312.pyc DELETED
Binary file (5.21 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/core.cpython-312.pyc DELETED
Binary file (7.14 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/evaluator.cpython-312.pyc DELETED
Binary file (18.9 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/image_metrics.cpython-312.pyc DELETED
Binary file (10.9 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/io.cpython-312.pyc DELETED
Binary file (2.76 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/renderer.cpython-312.pyc DELETED
Binary file (7.11 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/units.cpython-312.pyc DELETED
Binary file (6.45 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/worker.cpython-312.pyc DELETED
Binary file (1.94 kB)
 
codes/reconstruction/FlyingWithPhotons/evaluation/arguments.py DELETED
@@ -1,64 +0,0 @@
1
- """Model rendering options; all scoring options are fixed by the reference contract."""
2
- import ast
3
- import configargparse
4
- from utils import str2bool, load_args
5
-
6
- def load_eval_args():
7
- parser = configargparse.ArgumentParser()
8
- parser.add_argument("--output", "--shared-output-dir", "--shared_output_dir", dest="shared_output_dir", default=None,
9
- help="Fresh output directory for unified V4 metrics.")
10
- parser.add_argument(
11
- "--shared-reference-contract", "--shared_reference_contract",
12
- dest="shared_reference_contract", default=None,
13
- help="Scene-bound shared reference contract. Required for a scene without a verified default.",
14
- )
15
- parser.add('--config', '-tc', '--test_config', dest='test_config',
16
- is_config_file=True,
17
- default=None,
18
- help='Test config path.'
19
- )
20
- parser.add_argument(
21
- "--transforms_path",
22
- type=str,
23
- default="",
24
- help="Path to evaluation transforms file.",
25
- )
26
- parser.add_argument(
27
- "--checkpoint_dir",
28
- type=str,
29
- default="/",
30
- help="Directory of the checkpoint.",
31
- )
32
- parser.add_argument(
33
- "--warped",
34
- type=str2bool,
35
- default="true",
36
- help="Render warped or unwarped transients.",
37
- )
38
- parser.add_argument(
39
- "--t_min_test",
40
- type=int,
41
- default=200,
42
- help="Render min bin number.",
43
- )
44
- parser.add_argument(
45
- "--t_max_test",
46
- type=int,
47
- default=700,
48
- help="Render max bin number.",
49
- )
50
- parser.add_argument(
51
- "--unwarp_method",
52
- type=str,
53
- default="depth",
54
- help="Method to perform unwarping.",
55
- )
56
- parser.add_argument(
57
- "--step",
58
- type=int,
59
- default=80000,
60
- help="Which step to evaluate.",
61
- )
62
- parser.add_argument("--save-predictions", action="store_true", help="Save unmodified encoded histograms for re-scoring")
63
- args = load_args(eval=True, parser=parser)
64
- return args
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/cli.py DELETED
@@ -1,54 +0,0 @@
1
- """One entry point and one protocol, for all three methods."""
2
- import argparse
3
- import json
4
- import sys
5
- from pathlib import Path
6
-
7
- def main():
8
- parser = argparse.ArgumentParser(description=__doc__)
9
- parser.add_argument('source', choices=('render', 'saved'),
10
- help='render a checkpoint, or score unmodified saved histograms')
11
- if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
12
- parser.print_help()
13
- return
14
- mode = parser.parse_args(sys.argv[1:2]).source
15
- sys.argv = [sys.argv[0]] + sys.argv[2:]
16
- from . import renderer
17
- if mode == 'render':
18
- return renderer.main()
19
- from .evaluator import EvaluationRun
20
- from .io import load_histogram, write_json, sha256
21
- p = argparse.ArgumentParser(description='Score saved histograms with the same V4 evaluator as render.')
22
- p.add_argument('--prediction-dir', required=True)
23
- p.add_argument('--prediction-pattern', default='{view}_transient_array.npy')
24
- p.add_argument('--prediction-scale', type=float, required=True,
25
- help='ACTUAL TRAINING normalization; 1 only for full-count exports')
26
- p.add_argument('--prediction-gamma', type=float, default=1.)
27
- p.add_argument('--prediction-bin-width-s', type=float, required=True)
28
- p.add_argument('--prediction-manifest', required=True,
29
- help='Actual rendered frames and poses, in prediction-file order')
30
- p.add_argument('--shared-reference-contract', required=True)
31
- p.add_argument('--output', required=True)
32
- p.add_argument('--device', default='cpu')
33
- a = p.parse_args()
34
- a.bin_width_s_loader = a.prediction_bin_width_s
35
- a.n_bins = json.loads(Path(a.shared_reference_contract).read_text())['n_bins']
36
- manifest = json.loads(Path(a.prediction_manifest).read_text())
37
- if (Path(a.output)/'prediction_manifest.json').resolve() == Path(a.prediction_manifest).resolve():
38
- raise ValueError('Use a separate output directory to preserve the source manifest')
39
- # Generated manifests are binding; do not silently override their physical units.
40
- for key, actual in [('prediction_scale', a.prediction_scale),
41
- ('prediction_gamma', a.prediction_gamma),
42
- ('bin_width_s', a.prediction_bin_width_s)]:
43
- if key in manifest and float(manifest[key]) != actual:
44
- raise ValueError('Prediction manifest disagrees with '+key)
45
- frames = manifest['frames']
46
- run = EvaluationRun(renderer.PROJECT, a, a.output, frames, a.prediction_scale,
47
- a.prediction_gamma, rendering=manifest.get('rendering'))
48
- run.evaluator.metadata.update(prediction_manifest=str(Path(a.prediction_manifest).resolve()),
49
- prediction_manifest_sha256=sha256(a.prediction_manifest))
50
- write_json(run.evaluator.output/'evaluation_protocol.json', run.evaluator.metadata)
51
- for i, frame in enumerate(frames):
52
- path = Path(a.prediction_dir)/a.prediction_pattern.format(view=i, stem=Path(frame['file_path']).stem)
53
- run.score(load_histogram(path), i)
54
- print(run.finish())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/core.py DELETED
@@ -1,81 +0,0 @@
1
- """Pure NumPy scoring. No data-dependent exposure fitting or upper clipping."""
2
- import numpy as np
3
-
4
- C = 299792458.0
5
-
6
- def positive(x, name):
7
- x = float(x)
8
- if not np.isfinite(x) or x <= 0:
9
- raise ValueError(name + ' must be finite and positive')
10
- return x
11
-
12
- def histogram(x):
13
- if hasattr(x, 'detach'):
14
- x = x.detach().cpu().numpy()
15
- x = np.asarray(x)
16
- if x.ndim == 3:
17
- x = x[..., None]
18
- if x.ndim != 4 or x.shape[-1] not in (1, 3) or min(x.shape) <= 0:
19
- raise ValueError('Expected H x W x T x (1 or 3) histogram')
20
- return x
21
-
22
- def decode(x, scale, gamma=1.0):
23
- """Inverse training encoding, applied per bin before any summation."""
24
- scale, gamma = positive(scale, 'training scale'), positive(gamma, 'gamma')
25
- x = np.asarray(x, dtype=np.float64)
26
- if not np.isfinite(x).all() or np.any(x < 0):
27
- raise ValueError('Histogram must be finite and nonnegative, even outside the mask')
28
- y = np.power(x, gamma) * scale if gamma != 1.0 else x * scale
29
- if not np.isfinite(y).all():
30
- raise ValueError('Count decoding overflow')
31
- return y
32
-
33
- def score_histograms(prediction, reference, mask, *, prediction_scale,
34
- reference_scale, histogram_peak, bin_width_s,
35
- prediction_gamma=1.0, row_chunk=4):
36
- """MSE over all bins/channels of GT-valid pixels, using a frozen train peak.
37
-
38
- A one-channel capture is broadcast to RGB when necessary. All RGB channels
39
- enter MSE; peak depth uses their arithmetic mean. Chunking bounds RAM use.
40
- """
41
- pred, ref = histogram(prediction), histogram(reference)
42
- if pred.shape[:3] != ref.shape[:3]:
43
- raise ValueError('Prediction/reference pixel grid or temporal window differs')
44
- mask = np.asarray(mask)
45
- if mask.shape != pred.shape[:2] or not np.isin(mask, [0, 1]).all():
46
- raise ValueError('Expected binary HW reference-only mask')
47
- mask = mask.astype(bool)
48
- if not mask.any():
49
- raise ValueError('No valid reference pixels')
50
- peak = positive(histogram_peak, 'fixed histogram peak')
51
- dt = positive(bin_width_s, 'physical bin width')
52
- if int(row_chunk) != row_chunk or row_chunk < 1:
53
- raise ValueError('row_chunk must be a positive integer')
54
- h, w, t = pred.shape[:3]
55
- channels = max(pred.shape[-1], ref.shape[-1])
56
- ip, ig = np.zeros((h,w,3)), np.zeros((h,w,3))
57
- dp, dg = np.zeros((h,w)), np.zeros((h,w))
58
- squared = absolute = intersection = union = 0.0
59
- for start in range(0,h,int(row_chunk)):
60
- sl = slice(start,min(h,start+int(row_chunk)))
61
- p = decode(pred[sl], prediction_scale, prediction_gamma)
62
- g = decode(ref[sl], reference_scale)
63
- ip[sl] = np.broadcast_to(p.sum(axis=-2), (len(p),w,3))
64
- ig[sl] = np.broadcast_to(g.sum(axis=-2), (len(g),w,3))
65
- dp[sl] = p.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0
66
- dg[sl] = g.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0
67
- a,b = np.broadcast_arrays(p[mask[sl]], g[mask[sl]])
68
- error = a-b
69
- squared += np.square(error).sum(dtype=np.float64)
70
- absolute += np.abs(error).sum(dtype=np.float64)
71
- intersection += np.minimum(a,b).sum(dtype=np.float64)
72
- union += np.maximum(a,b).sum(dtype=np.float64)
73
- count = int(mask.sum()) * t * channels
74
- mse = squared/count
75
- psnr = float(20*np.log10(peak)-10*np.log10(mse)) if mse>0 else float('inf')
76
- scores = dict(histogram_psnr=psnr, histogram_mse_counts=float(mse),
77
- histogram_mae_counts=float(absolute/count),
78
- depth_l1_m=float(np.abs(dp[mask]-dg[mask]).mean()),
79
- transient_iou=float(intersection/union) if union>0 else 1.0)
80
- return scores, dict(prediction=ip, reference=ig, mask=mask,
81
- prediction_depth=dp, reference_depth=dg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/evaluator.py DELETED
@@ -1,161 +0,0 @@
1
- """Frame-bound common scoring adapter for all three native and saved entrances."""
2
- import json
3
- import operator
4
- import os
5
- from pathlib import Path
6
- import subprocess
7
- import sys
8
- import numpy as np
9
- from . import PROTOCOL
10
- from .core import C,positive,score_histograms
11
- from .io import sha256,verified,load_histogram,write_json
12
-
13
- BASE=Path(__file__).resolve().parent.parent
14
- PYTHON=os.environ.get('STB_METRICS_PYTHON') or '/work/runrong/.conda/envs/transientangelo/bin/python'
15
-
16
- def resolve_contract(args):
17
- explicit=getattr(args,'shared_reference_contract',None) or os.environ.get('SHARED_REFERENCE_CONTRACT')
18
- if explicit:return Path(explicit).resolve()
19
- measurement=getattr(args,'measurement_root',None)
20
- matches=[]
21
- for p in Path(os.environ.get('STB_REFERENCE_ROOT', str(BASE/'references'))).glob('*/contract.json'):
22
- d=json.loads(p.read_text())
23
- if measurement and Path(d['measurement_root']).resolve()==Path(measurement).resolve():matches.append(p)
24
- if len(matches)!=1:
25
- raise ValueError('A prepared V4 canonical reference is required. Pass --shared-reference-contract '
26
- 'with the matching contract.json; no legacy/test-scale fallback.')
27
- return matches[0]
28
-
29
- class UnifiedEvaluator:
30
- def __init__(self,project,args,output_dir,frames):
31
- if project not in ('trnerf','transientangelo','FlyingWithPhotons'):raise ValueError('Unknown project')
32
- if not Path(PYTHON).is_file():raise FileNotFoundError('Set STB_METRICS_PYTHON to the common evaluation Python: '+str(PYTHON))
33
- self.project=project;self.path=resolve_contract(args);self.digest=sha256(self.path)
34
- self.contract=c=json.loads(self.path.read_text())
35
- if c.get('protocol')!=PROTOCOL:
36
- raise ValueError('V4 needs a histogram reference contract, not an intensity-only V2/V3 contract')
37
- self.peak=positive(c['histogram_peak'],'fixed training histogram peak')
38
- self.display_scale=positive(c['display_scale'],'fixed training display scale')
39
- dt=positive(c['bin_width_s'],'reference bin width')
40
- if not c.get('training_frames') or not c.get('scale_policy') or c.get('time_start')!=0:
41
- raise ValueError('Missing frozen training-scale provenance or invalid time origin')
42
- for k in ('height','width','n_bins'):
43
- if type(c[k]) is not int or c[k]<=0:raise ValueError('Invalid '+k)
44
- measurement=getattr(args,'measurement_root',None)
45
- if measurement and Path(measurement).resolve()!=Path(c['measurement_root']).resolve():
46
- raise ValueError('Measurement scene does not match reference')
47
- intrinsics=getattr(args,'intrinsics',None) or getattr(args,'intrinsics_path',None)
48
- if intrinsics and sha256(intrinsics)!=c['intrinsics_sha256']:raise ValueError('Calibration mismatch')
49
- actual=getattr(args,'bin_width_s_loader',None)
50
- if actual is None:actual=getattr(args,'bin_width_s',None)
51
- if actual is None and hasattr(args,'exposure_time'):
52
- actual=float(args.exposure_time)/(C/2 if project=='FlyingWithPhotons' else C)
53
- if actual is None or not np.isclose(float(actual),dt,rtol=1e-6,atol=0):raise ValueError('Physical bin width mismatch/missing')
54
- # FWP uses one-way range/bin; verify it even when a loader override exists.
55
- if project=='FlyingWithPhotons' and hasattr(args,'exposure_time'):
56
- if not np.isclose(float(args.exposure_time)/(C/2),dt,rtol=1e-6,atol=0):raise ValueError('FWP exposure_time mismatch')
57
- for name,want in [('n_bins',c['n_bins']),('t_min_test',0),('t_max_test',c['n_bins']),
58
- ('img_height_test',c['height']),('img_width_test',c['width'])]:
59
- actual=getattr(args,name,None)
60
- if actual is not None and int(actual)!=want:raise ValueError('Common window/grid mismatch: '+name)
61
- frames=list(frames);records={Path(f['file_path']).stem:f for f in c['frames']}
62
- ids=[Path(f['file_path']).stem for f in frames]
63
- if (not frames or len(records)!=len(c['frames']) or len(set(ids))!=len(ids)
64
- or set(ids)!=set(records)):
65
- raise ValueError('Evaluation must declare the complete, unique canonical test frame set')
66
- self.frames=[]
67
- for f,key in zip(frames,ids):
68
- r=records[key];pose=np.asarray(f['transform_matrix']);rp=np.asarray(r['transform_matrix'])
69
- if pose.shape!=(4,4) or rp.shape!=(4,4) or not np.isfinite(pose).all() or not np.allclose(pose,rp,rtol=0,atol=1e-7):
70
- raise ValueError('Test frame pose differs from canonical reference: '+key)
71
- self.frames.append(r)
72
- self.output=Path(output_dir)/'unified_metrics'
73
- if (self.output/'evaluation_protocol.json').exists():
74
- raise FileExistsError('Use a fresh V4 output directory; existing scores are not overwritten')
75
- self.output.mkdir(parents=True,exist_ok=True);self.rows=[]
76
- self.device=os.environ.get('STB_METRICS_DEVICE') or str(getattr(args,'device','cpu'))
77
- self.metadata=dict(protocol=PROTOCOL,project=project,reference_contract=str(self.path),
78
- reference_sha256=self.digest,scene_id=c['scene_id'],histogram_peak=self.peak,
79
- display_scale=self.display_scale,mask_policy=c['mask_policy'],n_bins=c['n_bins'],bin_width_s=dt,
80
- frames=[f['file_path'] for f in self.frames],
81
- histogram_psnr='20log10(frozen train peak)-10log10(mean squared count error); all valid bins/channels; no upper clipping/gamma',
82
- depth='argmax of channel-mean full-count histogram; bin_index*c*dt/2, metres; canonical GT mask',
83
- aggregation='arithmetic mean of per-view metrics, only complete frame sets receive an aggregate',
84
- training_scale_policy='explicit actual training scale; never test maximum',
85
- evaluator_python=PYTHON,image_metrics_device=self.device,code_sha256={f:sha256(Path(__file__).with_name(f)) for f in ('core.py','evaluator.py','worker.py')},
86
- image_code_sha256=sha256(Path(__file__).with_name('image_metrics.py')))
87
- from .image_metrics import PROTOCOL_INFO
88
- self.metadata['image_metric_definition']=dict(PROTOCOL_INFO,scale=self.display_scale)
89
- self.metadata['checkpoint_dir']=getattr(args,'checkpoint_dir',None)
90
- self.metadata['checkpoint_step']=getattr(args,'step',None)
91
- self.metadata['rendering_note']='Native renderers retain their method-specific sampling; all default native V4 runs use 30 forward repetitions. Saved-output runs must record their rendering settings separately.'
92
- write_json(self.output/'evaluation_protocol.json',self.metadata)
93
-
94
- def score(self,prediction_histogram,frame_index,prediction_scale,prediction_gamma=1.0):
95
- if isinstance(frame_index,(bool,np.bool_)):raise IndexError('Boolean frame index')
96
- i=operator.index(frame_index)
97
- if i<0 or i>=len(self.frames):raise IndexError(i)
98
- if sha256(self.path)!=self.digest:raise ValueError('Reference contract changed during evaluation')
99
- f=self.frames[i];c=self.contract
100
- hp=verified(self.path.parent/f['histogram_path'],f['histogram_sha256'])
101
- mp=verified(self.path.parent/f['mask_path'],f['mask_sha256'])
102
- reference=load_histogram(hp);mask=np.load(mp,allow_pickle=False)
103
- if reference.shape[:3]!=(c['height'],c['width'],c['n_bins']):raise ValueError('Reference shape differs from contract')
104
- scores,arrays=score_histograms(prediction_histogram,reference,mask,
105
- prediction_scale=prediction_scale,reference_scale=f['reference_scale'],
106
- histogram_peak=self.peak,bin_width_s=c['bin_width_s'],prediction_gamma=prediction_gamma)
107
- inp=self.output/f'view{i}_inputs.npz';result=self.output/f'view{i}_image_scores.json';display=self.output/f'view{i}_display.npz'
108
- np.savez_compressed(inp,**arrays)
109
- env=dict(os.environ);env['PYTHONPATH']=str(BASE)+os.pathsep+env.get('PYTHONPATH','')
110
- if self.device=='cpu':env['CUDA_VISIBLE_DEVICES']=''
111
- proc=subprocess.run([PYTHON,'-m','evaluation.worker',
112
- '--input',str(inp),'--output',str(result),'--display',str(display),
113
- '--scale',str(self.display_scale),'--device',self.device],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
114
- if proc.returncode:raise RuntimeError('Common image scorer failed: '+proc.stdout[-5000:])
115
- scores.update(json.loads(result.read_text()))
116
- row=dict(view=i,frame=f['file_path'],prediction_scale=float(prediction_scale),
117
- prediction_gamma=float(prediction_gamma),valid_pixels=int(mask.sum()),**scores)
118
- self.rows=[r for r in self.rows if r['view']!=i]+[row];self.rows.sort(key=lambda r:r['view'])
119
- write_json(self.output/'metrics_per_view.json',self.rows)
120
- complete=len(self.rows)==len(self.frames)
121
- write_json(self.output/'progress.json',dict(completed_views=len(self.rows),expected_views=len(self.frames),complete=complete))
122
- if complete:
123
- write_json(self.output/'metrics_aggregate.json',{k:float(np.mean([r[k] for r in self.rows])) for k in scores})
124
- with np.load(display) as d:p,g=d['prediction'],d['reference']
125
- return dict(scores,psnr=scores['image_psnr'],prediction_display=p,reference_display=g,
126
- reference_histogram=reference,reference_scale=f['reference_scale'],
127
- prediction_intensity_counts=arrays['prediction'],reference_intensity_counts=arrays['reference'],
128
- mask=arrays['mask'],prediction_depth=arrays['prediction_depth'],reference_depth=arrays['reference_depth'],protocol=PROTOCOL)
129
-
130
- class EvaluationRun:
131
- """The same scoring/output path for native rendering and saved predictions."""
132
- def __init__(self, project, args, output_dir, frames, scale, gamma=1.0,
133
- rendering=None, save_predictions=False):
134
- self.scale = positive(scale, 'actual training scale')
135
- self.gamma = positive(gamma, 'actual training gamma')
136
- self.evaluator = UnifiedEvaluator(project, args, output_dir, frames)
137
- self.output = Path(output_dir)
138
- self.save_predictions = save_predictions
139
- manifest = dict(frames=frames, prediction_scale=self.scale,
140
- prediction_gamma=self.gamma,
141
- bin_width_s=self.evaluator.contract['bin_width_s'],
142
- rendering=rendering or {'source': 'saved histograms; see source manifest'})
143
- write_json(self.output/'prediction_manifest.json', manifest)
144
- self.evaluator.metadata.update(prediction_scale=self.scale, prediction_gamma=self.gamma,
145
- rendering=manifest['rendering'])
146
- write_json(self.evaluator.output/'evaluation_protocol.json', self.evaluator.metadata)
147
-
148
- def score(self, prediction, index):
149
- if self.save_predictions:
150
- if hasattr(prediction, 'detach'):
151
- prediction = prediction.detach().cpu().numpy()
152
- np.save(self.output/f'{index}_transient_array.npy', prediction)
153
- scores = self.evaluator.score(prediction, index, self.scale, self.gamma)
154
- print(self.evaluator.project, index, {k: scores[k] for k in
155
- ('histogram_psnr', 'image_psnr', 'ssim', 'lpips', 'depth_l1_m')}, flush=True)
156
- return scores
157
-
158
- def finish(self):
159
- if len(self.evaluator.rows) != len(self.evaluator.frames):
160
- raise ValueError('Incomplete canonical test set: no complete evaluation result')
161
- return self.evaluator.output/'metrics_aggregate.json'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/image_metrics.py DELETED
@@ -1,114 +0,0 @@
1
- """Shared TA-style display metrics, with uncensored linear-count diagnostics.
2
-
3
- Not an exact upstream reproduction: all projects use one reference-only mask,
4
- explicit SSIM settings, a frozen training scale, and FP32 LPIPS.
5
- """
6
- import numpy as np
7
- import torch
8
- import lpips
9
- from contextlib import contextmanager
10
- from scipy.ndimage import minimum_filter
11
- from skimage.metrics import structural_similarity
12
-
13
- PROTOCOL = 'shared_ta_display_psnr_ssim_lpips_v3_20260929'
14
- PRIMARY_KEYS = ('psnr', 'ssim', 'lpips')
15
- AUXILIARY_KEYS = ('linear_psnr', 'prediction_above_scale_percent',
16
- 'reference_above_scale_percent', 'max_prediction_over_scale',
17
- 'max_reference_over_scale')
18
- SCORE_KEYS = PRIMARY_KEYS + AUXILIARY_KEYS
19
- PROTOCOL_INFO = dict(
20
- protocol=PROTOCOL,
21
- scale_policy="explicit frozen per-scene record; no numeric scene fallback",
22
- metric_labels=dict(psnr='PSNR-display', ssim='SSIM-display', lpips='LPIPS-display',
23
- linear_psnr='PSNR-linear (auxiliary)'),
24
- prediction_display='clip(I/D,0,1) ** (1/2.2)',
25
- reference_display='(I/D) ** (1/2.2), no upper clipping',
26
- psnr='-10log10 valid-reference-pixel/RGB display MSE; fixed peak 1',
27
- ssim='RGB, data_range=1, uniform 7x7, sample covariance, complete reference-valid windows',
28
- lpips='same display RGB, common invalid region black, [-1,1] transform, VGG0.1 FP32',
29
- linear_psnr='-10log10 mean(((prediction-reference)/D)^2); no upper clipping or gamma',
30
- above_scale_percent='percentage of reference-valid pixels with ANY RGB channel > D',
31
- aggregation='arithmetic mean of per-view metrics; saturation percentages are mean per-view percentages',
32
- prediction_upper_clip=True, reference_upper_clip=False,
33
- count_domain_upper_clip=False, fitted_test_exposure=False,
34
- preview_png='clip display arrays only for uint8 export; floating scoring arrays are retained',
35
- upstream_exact=False,
36
- )
37
-
38
- @contextmanager
39
- def scoring_precision():
40
- previous = (torch.get_float32_matmul_precision(),
41
- torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32)
42
- try:
43
- torch.set_float32_matmul_precision('highest')
44
- torch.backends.cuda.matmul.allow_tf32=False
45
- torch.backends.cudnn.allow_tf32=False
46
- yield
47
- finally:
48
- torch.set_float32_matmul_precision(previous[0])
49
- torch.backends.cuda.matmul.allow_tf32=previous[1]
50
- torch.backends.cudnn.allow_tf32=previous[2]
51
-
52
- def tone_map(image, scale, *, prediction):
53
- """Role is explicit: upstream prediction and reference transforms differ."""
54
- x=np.asarray(image,dtype=np.float64)
55
- if not np.isfinite(scale) or scale <= 0:
56
- raise ValueError('positive fixed scale required')
57
- if not np.isfinite(x).all() or np.any(x<0):
58
- raise ValueError('Expected finite nonnegative counts; no silent masking/clipping of invalid inputs')
59
- x=x/scale
60
- if prediction:
61
- x=np.clip(x,0.,1.)
62
- return x**(1/2.2)
63
-
64
- def display_pair(prediction, reference, scale, mask=None):
65
- p=tone_map(prediction,scale,prediction=True)
66
- g=tone_map(reference,scale,prediction=False)
67
- if mask is not None:
68
- mask=np.asarray(mask,bool)
69
- p[~mask]=0;g[~mask]=0
70
- return p,g
71
-
72
- def preview_uint8(display_image):
73
- """PNG encoding only. Never pass this output back to a metric."""
74
- return np.rint(np.clip(display_image,0.,1.)*255.).astype(np.uint8)
75
-
76
- def _psnr(mse):
77
- return float(-10*np.log10(mse)) if mse>0 else float('inf')
78
-
79
- class ImageMetrics:
80
- def __init__(self, scale, device='cuda'):
81
- if not np.isfinite(scale) or scale<=0:
82
- raise ValueError('positive fixed scale required')
83
- self.scale=float(scale);self.device=str(device)
84
- self.net=lpips.LPIPS(net='vgg',version='0.1').float().to(device).eval()
85
-
86
- def __call__(self, prediction, reference, mask):
87
- pred=np.asarray(prediction,np.float64);ref=np.asarray(reference,np.float64)
88
- mask=np.asarray(mask,dtype=bool)
89
- if pred.shape!=ref.shape or pred.ndim!=3 or pred.shape[-1]!=3 or mask.shape!=pred.shape[:2]:
90
- raise ValueError('Expected matching HWC3 images and HW reference mask')
91
- if not mask.any():
92
- raise ValueError('No reference-valid pixels')
93
- x,y=display_pair(pred,ref,self.scale)
94
- psnr=_psnr(np.mean((x[mask]-y[mask])**2,dtype=np.float64))
95
- linear_psnr=_psnr(np.mean(((pred[mask]-ref[mask])/self.scale)**2,dtype=np.float64))
96
- windows=minimum_filter(mask.astype(np.uint8),size=7,mode='constant',cval=0).astype(bool)
97
- if not windows.any():
98
- raise ValueError('No complete 7x7 reference-valid SSIM windows')
99
- _,ssim_map=structural_similarity(y,x,data_range=1.,channel_axis=-1,
100
- win_size=7,gaussian_weights=False,use_sample_covariance=True,full=True)
101
- ssim=float(ssim_map[windows].mean())
102
- x[~mask]=0;y[~mask]=0
103
- tensor=lambda z: torch.from_numpy(z.astype(np.float32)).permute(2,0,1)[None].to(self.device)*2-1
104
- with scoring_precision(),torch.no_grad(),torch.autocast(device_type=self.device.split(':')[0],enabled=False):
105
- score=self.net(tensor(x),tensor(y))
106
- return dict(psnr=psnr,ssim=ssim,lpips=float(score.item()),linear_psnr=linear_psnr,
107
- prediction_above_scale_percent=float(np.any(pred[mask]>self.scale,axis=-1).mean()*100),
108
- reference_above_scale_percent=float(np.any(ref[mask]>self.scale,axis=-1).mean()*100),
109
- max_prediction_over_scale=float(pred[mask].max()/self.scale),
110
- max_reference_over_scale=float(ref[mask].max()/self.scale))
111
-
112
- def aggregate(rows):
113
- if not rows:raise ValueError('Cannot aggregate empty results')
114
- return {k:float(np.mean([r[k] for r in rows],dtype=np.float64)) for k in SCORE_KEYS}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/io.py DELETED
@@ -1,30 +0,0 @@
1
- import hashlib
2
- import json
3
- import os
4
- from pathlib import Path
5
- import numpy as np
6
-
7
- def sha256(path):
8
- h=hashlib.sha256()
9
- with Path(path).open('rb') as f:
10
- for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
11
- return h.hexdigest()
12
-
13
- def write_json(path, data):
14
- path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
15
- tmp=path.with_name(path.name+'.%d.tmp'%os.getpid())
16
- tmp.write_text(json.dumps(data,indent=2,allow_nan=True));tmp.replace(path)
17
-
18
- def verified(path, digest):
19
- path=Path(path)
20
- if not path.is_file() or sha256(path)!=digest:
21
- raise ValueError('Frozen input missing or changed: '+str(path))
22
- return path
23
-
24
- def load_histogram(path):
25
- path=Path(path)
26
- if path.suffix=='.npy':return np.load(path,mmap_mode='r',allow_pickle=False)
27
- if path.suffix in ('.h5','.hdf5'):
28
- import h5py
29
- with h5py.File(path,'r') as f:return np.asarray(f['data'])
30
- raise ValueError('Use unclipped .npy or .h5 histogram exports: '+str(path))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/renderer.py DELETED
@@ -1,100 +0,0 @@
1
- """FlyingWithPhotons model loading and rendering; no method-specific scoring."""
2
- import json
3
- from pathlib import Path
4
-
5
- PROJECT = 'FlyingWithPhotons'
6
-
7
- def forward_average_occgrid(
8
- forward_repeats,
9
- radiance_field,
10
- estimator,
11
- rays,
12
- args,
13
- color_channels,
14
- ):
15
- # Match captured_neus.py: average repeated forward passes first, then evaluate metrics once.
16
- rgb_sum = None
17
- acc_sum = None
18
- depth_sum = None
19
-
20
- for rep_idx in range(forward_repeats):
21
- if forward_repeats > 1:
22
- print(f"[FORWARD AVG] rep {rep_idx + 1}/{forward_repeats}")
23
-
24
- rgb_rep, acc_rep, depth_rep, _ = render_image_with_occgrid_test(
25
- 1024,
26
- radiance_field,
27
- estimator,
28
- rays,
29
- args=args,
30
- near_plane=args.near_plane,
31
- far_plane=args.far_plane,
32
- render_step_size=args.render_step_size,
33
- cone_angle=args.cone_angle,
34
- alpha_thre=0.01,
35
- n_output_dim=args.n_bins * color_channels,
36
- prop_delay=args.prop_delay,
37
- unwarp=not args.warped,
38
- )
39
-
40
- if rgb_sum is None:
41
- rgb_sum = torch.zeros_like(rgb_rep)
42
- acc_sum = torch.zeros_like(acc_rep)
43
- depth_sum = torch.zeros_like(depth_rep)
44
-
45
- rgb_sum += rgb_rep
46
- acc_sum += acc_rep
47
- depth_sum += depth_rep
48
-
49
- rgb = rgb_sum / float(forward_repeats)
50
- acc = acc_sum / float(forward_repeats)
51
- depth = depth_sum / float(forward_repeats)
52
- return rgb, acc, depth
53
-
54
-
55
- def main():
56
- global torch, render_image_with_occgrid_test
57
- import torch
58
- import torch.nn.functional as F
59
- from nerfacc import OccGridEstimator
60
- from radiance_fields.ngp import NGPRadianceField
61
- from loaders.utils import Rays
62
- from utils import render_image_with_occgrid_test
63
- from .arguments import load_eval_args
64
- from .units import fwp_training_units
65
- from .evaluator import EvaluationRun
66
-
67
- args = load_eval_args()
68
- if args.version != 'captured' or int(getattr(args, 'eval_repeats', 30)) != 30:
69
- raise ValueError('The captured benchmark requires 30 forward repetitions')
70
- scale, gamma = fwp_training_units(args)
71
- frames = json.loads(Path(args.transforms_path).read_text())['frames']
72
- output = args.shared_output_dir or str(Path(args.checkpoint_dir)/f'evaluation_step{args.step}')
73
- run = EvaluationRun(PROJECT, args, output, frames, scale, gamma,
74
- rendering=dict(forward_repeats=30, sampling='native same pixel rays, average forward outputs',
75
- warped=args.warped), save_predictions=args.save_predictions)
76
- device = args.device
77
- aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
78
- h, w = args.img_height_test, args.img_width_test
79
- sx, sy = w/args.img_width, h/args.img_height
80
- K = torch.tensor([[args.fx*sx,0,args.cx*sx],[0,args.fy*sy,args.cy*sy],[0,0,1]], dtype=torch.float32)
81
- estimator = OccGridEstimator(roi_aabb=aabb, resolution=args.grid_resolution,
82
- levels=args.grid_nlvl).to(device)
83
- model = NGPRadianceField(aabb=estimator.aabbs[-1], radiance_activation=torch.nn.Sigmoid(),
84
- use_viewdirs=True, args=args).to(device)
85
- model.load_state_dict(torch.load(Path(args.checkpoint_dir)/f'radiance_field_{args.step:04d}.pth', map_location=device))
86
- estimator.load_state_dict(torch.load(Path(args.checkpoint_dir)/f'occupancy_grid_{args.step:04d}.pth', map_location=device))
87
- # Preserve the original renderer's mode and same-ray averaging behavior.
88
- with torch.no_grad():
89
- for i, frame in enumerate(frames):
90
- c2w = torch.tensor(frame['transform_matrix']).to(device)
91
- yy, xx = torch.meshgrid(torch.arange(h,device=device), torch.arange(w,device=device), indexing='ij')
92
- camera_dirs = F.pad(torch.stack([(xx-K[0,2]+0.5)/K[0,0],
93
- (yy-K[1,2]+0.5)/K[1,1]], dim=-1), (0,1), value=1.)
94
- directions = (camera_dirs[:,:,None,:]*c2w[:3,:3]).sum(dim=-1)
95
- origins = torch.broadcast_to(c2w[:3,-1], directions.shape)
96
- viewdirs = directions/torch.linalg.norm(directions,dim=-1,keepdims=True)
97
- rays = Rays(origins=origins.reshape(h,w,3), viewdirs=viewdirs.reshape(h,w,3))
98
- rgb, _, _ = forward_average_occgrid(30, model, estimator, rays, args, 1)
99
- run.score(rgb.reshape(h,w,-1,1).cpu().numpy(), i)
100
- print(run.finish())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/units.py DELETED
@@ -1,84 +0,0 @@
1
- import math
2
- """Actual training units; a test-split maximum is never a fallback."""
3
- import ast
4
- import json
5
- from pathlib import Path
6
- from types import SimpleNamespace
7
- from .core import positive
8
- from .io import write_json,sha256
9
-
10
- def record_training_units(directory,scale,gamma,train_poses,project,measurement_root=None,intrinsics=None):
11
- path=Path(directory)/'image_metric_normalization.json'
12
- data=dict(training_scale=positive(scale,'training scale'),training_gamma=positive(gamma,'training gamma'),
13
- project=project,train_poses=str(Path(train_poses).resolve()),train_poses_sha256=sha256(train_poses),
14
- measurement_root=measurement_root,intrinsics=intrinsics,
15
- intrinsics_sha256=sha256(intrinsics) if intrinsics else None,
16
- source='actual training loader/configuration; never computed from test data')
17
- if path.exists():
18
- old=json.loads(path.read_text())
19
- if (float(old['training_scale'])!=data['training_scale'] or
20
- float(old.get('training_gamma',1.0))!=data['training_gamma']):
21
- raise ValueError('Checkpoint directory already records different training units')
22
- for key in ('train_poses_sha256','intrinsics_sha256','measurement_root'):
23
- if key in old and old[key]!=data[key]:
24
- raise ValueError('Checkpoint training provenance differs: '+key)
25
- return
26
- write_json(path,data)
27
-
28
- def fwp_training_units(args):
29
- root=Path(args.checkpoint_dir);metadata=root/'image_metric_normalization.json'
30
- if metadata.exists():
31
- record=json.loads(metadata.read_text())
32
- scale,gamma=record['training_scale'],record['training_gamma']
33
- else:
34
- params=root/'params_full.txt'
35
- if not params.is_file():raise ValueError('FWP requires saved training params_full.txt or normalization metadata')
36
- values={}
37
- for line in params.read_text().splitlines():
38
- if '=' not in line or line.lstrip().startswith('#'):continue
39
- k,v=line.split('=',1)
40
- if k.strip() in ('dataset_scale','gamma'):values[k.strip()]=ast.literal_eval(v.strip())
41
- scale,gamma=values['dataset_scale'],values['gamma']
42
- scale,gamma=positive(scale,'training dataset_scale'),positive(gamma,'training gamma')
43
- if float(args.dataset_scale)!=scale or float(args.gamma)!=gamma:
44
- raise ValueError('Evaluation dataset_scale/gamma differs from saved FWP training units')
45
- return scale,gamma
46
-
47
- def scalar(value):
48
- if hasattr(value, 'detach'):
49
- value = value.detach().cpu().item()
50
- value = float(value)
51
- if not math.isfinite(value) or value <= 0:
52
- raise ValueError('A finite positive count scale is required')
53
- return value
54
-
55
- def resolve_prediction_scale(system):
56
- value = system.config.dataset.get('image_metric_training_scale', None)
57
- if hasattr(system, '_image_metric_training_scale'):
58
- if value is not None and scalar(value) != scalar(system._image_metric_training_scale):
59
- raise ValueError('Explicit training scale conflicts with checkpoint metadata')
60
- return scalar(system._image_metric_training_scale), 'training/checkpoint metadata'
61
- if value is not None:
62
- return scalar(value), 'explicit dataset.image_metric_training_scale'
63
- raise ValueError('Missing actual training scale; use checkpoint metadata or set dataset.image_metric_training_scale. Never substitute the test maximum.')
64
-
65
- def tn_training_scale(args):
66
- """Restore model output units; the independently normalized test split is not valid here."""
67
- explicit = getattr(args, "shared_prediction_scale", None)
68
- path = Path(args.checkpoint_dir) / "image_metric_normalization.json"
69
- recorded = None
70
- if path.is_file():
71
- recorded = json.loads(path.read_text()).get("training_scale")
72
- if explicit is None and recorded is None:
73
- raise ValueError(
74
- "Shared metrics require the TRAINING histogram normalization. "
75
- "Supply --shared-prediction-scale from the training loader, or create "
76
- + str(path) + " with training_scale and its training-data provenance. "
77
- "The test split maximum must never be substituted."
78
- )
79
- if explicit is not None and recorded is not None and float(explicit) != float(recorded):
80
- raise ValueError("Explicit prediction scale conflicts with checkpoint normalization metadata")
81
- value = float(recorded if explicit is None else explicit)
82
- if not math.isfinite(value) or value <= 0:
83
- raise ValueError("Training histogram normalization must be finite and positive")
84
- return value
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/evaluation/worker.py DELETED
@@ -1,21 +0,0 @@
1
- """Run image scoring in the same installed environment for all three methods."""
2
- import argparse
3
- from pathlib import Path
4
- import numpy as np
5
- from .io import write_json
6
-
7
- def main():
8
- p=argparse.ArgumentParser()
9
- for k in ('input','output','display'):p.add_argument('--'+k,required=True)
10
- p.add_argument('--scale',required=True,type=float);p.add_argument('--device',default='cpu')
11
- a=p.parse_args()
12
- from .image_metrics import ImageMetrics,display_pair
13
- with np.load(a.input) as d:
14
- pred,ref,mask=d['prediction'],d['reference'],d['mask'].astype(bool)
15
- scores=ImageMetrics(a.scale,a.device)(pred,ref,mask)
16
- scores['image_psnr']=scores.pop('psnr')
17
- x,y=display_pair(pred,ref,a.scale,mask)
18
- np.savez_compressed(a.display,prediction=x,reference=y)
19
- write_json(a.output,scores)
20
-
21
- if __name__=='__main__':main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/loaders/__init__.py DELETED
File without changes
codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (203 Bytes)
 
codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/calibration.cpython-312.pyc DELETED
Binary file (1.29 kB)
 
codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/regular_loader_our.cpython-312.pyc DELETED
Binary file (23.6 kB)
 
codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/streaming_loader.cpython-312.pyc DELETED
Binary file (13 kB)
 
codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/utils.cpython-312.pyc DELETED
Binary file (862 Bytes)
 
codes/reconstruction/FlyingWithPhotons/loaders/calibration.py DELETED
@@ -1,12 +0,0 @@
1
- """Expand scalar calibration or resize a 2-D map; preserve physical values."""
2
- import torch
3
- import torch.nn.functional as F
4
-
5
- def shift_map(value, height, width, device):
6
- value=torch.as_tensor(value,dtype=torch.float32,device=device).squeeze()
7
- if value.numel()==1:
8
- return value.reshape(1,1).expand(height,width)
9
- if value.ndim!=2:
10
- raise ValueError('Calibration shift must be scalar or a 2-D map')
11
- if tuple(value.shape)==(height,width):return value
12
- return F.interpolate(value[None,None],size=(height,width),mode='bilinear',align_corners=True)[0,0]
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/loaders/regular_loader_our.py DELETED
@@ -1,363 +0,0 @@
1
- """
2
- Copyright (c) 2022 Ruilong Li, UC Berkeley.
3
- Modified for captured SPAD data with Pinhole Model & Hardware Offsets.
4
- """
5
- import json
6
- import os
7
- import re
8
- import numpy as np
9
- import torch
10
- import torch.nn.functional as F
11
- import h5py
12
- import scipy.sparse as sp
13
- from .utils import Rays
14
- import tqdm
15
- import sys
16
- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17
- from utils import compute_transient_valid_mask_torch
18
-
19
- def read_h5(path):
20
- with h5py.File(path, 'r') as f:
21
- frames = np.array(f['data'])
22
- return frames
23
-
24
-
25
- def _load_numpy_coo_npz(path):
26
- pack = np.load(path, allow_pickle=False)
27
- try:
28
- fmt = str(np.asarray(pack["format"]).item())
29
- if fmt != "coo_numpy":
30
- raise ValueError(f"unsupported npz format tag: {fmt}")
31
- shape = tuple(np.asarray(pack["shape"], dtype=np.int64).tolist())
32
- row = np.asarray(pack["row"], dtype=np.int64)
33
- col = np.asarray(pack["col"], dtype=np.int64)
34
- data = np.asarray(pack["data"])
35
- dense = np.zeros(shape, dtype=data.dtype)
36
- np.add.at(dense, (row, col), data)
37
- return dense
38
- finally:
39
- pack.close()
40
-
41
-
42
- def read_npz(path, height, width):
43
- try:
44
- dense_frames = sp.load_npz(path).toarray()
45
- except Exception:
46
- dense_frames = _load_numpy_coo_npz(path)
47
- if dense_frames.ndim == 3:
48
- if dense_frames.shape[:2] != (height, width):
49
- raise ValueError(
50
- f"Measurement shape mismatch for {path}: got {dense_frames.shape[:2]}, "
51
- f"expected {(height, width)}"
52
- )
53
- return dense_frames.astype(np.float32)
54
- if dense_frames.ndim != 2:
55
- raise ValueError(f"Unsupported sparse measurement shape {dense_frames.shape} in {path}")
56
- if dense_frames.shape[0] == height * width:
57
- return dense_frames.reshape(height, width, dense_frames.shape[1]).astype(np.float32)
58
- if dense_frames.shape[1] == height * width:
59
- return dense_frames.T.reshape(height, width, dense_frames.shape[0]).astype(np.float32)
60
- raise ValueError(
61
- f"Measurement pixel count mismatch for {path}: got {dense_frames.shape}, "
62
- f"expected [H*W, bins] or [bins, H*W] with H*W={height * width}"
63
- )
64
-
65
-
66
- def resolve_measurement_path(measurement_root, frame_path):
67
- frame_rel = frame_path or ""
68
- frame_name = os.path.basename(frame_rel)
69
- frame_stem, frame_ext = os.path.splitext(frame_name)
70
-
71
- candidates = []
72
- if frame_rel:
73
- candidates.append(os.path.join(measurement_root, frame_rel))
74
- if frame_name:
75
- candidates.append(os.path.join(measurement_root, frame_name))
76
- if frame_stem:
77
- candidates.append(os.path.join(measurement_root, f"{frame_stem}.h5"))
78
- candidates.append(os.path.join(measurement_root, f"{frame_stem}.npz"))
79
- match = re.search(r"(\d+)$", frame_stem)
80
- if match:
81
- frame_idx = int(match.group(1))
82
- candidates.append(os.path.join(measurement_root, f"transient{frame_idx:03d}.h5"))
83
- candidates.append(os.path.join(measurement_root, f"transient{frame_idx:03d}.npz"))
84
- if frame_ext.lower() in {".h5", ".npz"}:
85
- candidates.insert(0, os.path.join(measurement_root, frame_name))
86
-
87
- seen = set()
88
- for candidate in candidates:
89
- if candidate in seen:
90
- continue
91
- seen.add(candidate)
92
- if os.path.exists(candidate):
93
- return candidate
94
-
95
- raise FileNotFoundError(
96
- f"Cannot find measurement file for frame '{frame_path}' under '{measurement_root}'. "
97
- f"Tried: {candidates[:6]}"
98
- )
99
-
100
-
101
- def read_measurement(path, args):
102
- ext = os.path.splitext(path)[1].lower()
103
- if ext == ".h5":
104
- return read_h5(path)[..., :args.n_bins, :3]
105
- if ext == ".npz":
106
- rgba = read_npz(path, args.img_height, args.img_width)[..., :args.n_bins]
107
- return rgba[..., None]
108
- raise ValueError(f"Unsupported measurement file type: {path}")
109
-
110
-
111
- def select_test_frames(root_fp, frames):
112
- train_json = os.path.join(root_fp, "transforms_train.json")
113
- if not os.path.exists(train_json):
114
- return frames
115
-
116
- with open(train_json, "r") as fp:
117
- train_meta = json.load(fp)
118
-
119
- num_train_frames = len(train_meta.get("frames", []))
120
- if num_train_frames <= 0 or num_train_frames >= len(frames):
121
- return frames
122
-
123
- selected_indices = np.linspace(0, len(frames) - 1, num=num_train_frames, dtype=int)
124
- return [frames[idx] for idx in selected_indices.tolist()]
125
-
126
- def _load_offset_map(path, h, w):
127
- """读取外部的逐像素深度偏移图"""
128
- if path.lower().endswith('.npy'):
129
- arr = np.load(path).astype(np.float32)
130
- else:
131
- arr = np.loadtxt(path, dtype=np.float32)
132
- arr = np.asarray(arr, dtype=np.float32).squeeze()
133
- if arr.size == h * w:
134
- arr = arr.reshape(h, w)
135
- return torch.from_numpy(arr)
136
-
137
- def _load_renderings(root_fp: str, split: str, args):
138
- """Load images from disk with Area Downsampling and Pinhole K Matrix."""
139
- with open(os.path.join(root_fp, f"transforms_{split}.json"), "r") as fp:
140
- meta = json.load(fp)
141
-
142
- frames = meta["frames"]
143
- if split == "test" and getattr(args, "match_test_to_train_views", True):
144
- frames = select_test_frames(root_fp, frames)
145
-
146
- images = []
147
- camtoworlds = []
148
-
149
- for i in tqdm.tqdm(range(len(frames))):
150
- frame = frames[i]
151
- fname = resolve_measurement_path(args.measurement_root, frame.get("file_path", ""))
152
- rgba = read_measurement(fname, args)
153
- camtoworlds.append(frame["transform_matrix"])
154
- images.append(rgba)
155
-
156
- images = np.stack(images, axis=0)
157
-
158
- if args.version == "captured":
159
- images = images.mean(-1)[..., None]
160
-
161
- # 空间下采样的优化:使用面积插值 (Area Interpolation)
162
- if split == "test" and images.shape[1] != args.img_shape_test:
163
- N, H, W, T, C = images.shape
164
- images_pt = torch.from_numpy(images).permute(0, 3, 4, 1, 2).reshape(N * T * C, 1, H, W)
165
- images_pt = F.interpolate(images_pt, size=(args.img_height_test, args.img_width_test), mode='area')
166
- images = images_pt.reshape(N, T, C, args.img_height_test, args.img_width_test).permute(0, 3, 4, 1, 2).numpy()
167
-
168
- images = np.clip(images / args.dataset_scale, 0, 1) ** (1 / args.gamma)
169
- images = images.astype(np.float32)
170
- camtoworlds = np.stack(camtoworlds, axis=0)
171
-
172
- # 保留原 Fwp 的完美针孔相机假设,利用 camera_angle_x 计算内参矩阵 K
173
- h, w = images.shape[1:3]
174
- # fov = float(meta["camera_angle_x"])
175
- # focal = 0.5 * w / np.tan(0.5 * fov)
176
- # K = torch.tensor([
177
- # [focal, 0, w / 2.0],
178
- # [0, focal, h / 2.0],
179
- # [0, 0, 1],
180
- # ], dtype=torch.float32)
181
- K = torch.tensor([
182
- [args.fx, 0, args.cx],
183
- [0, args.fy, args.cy],
184
- [0, 0, 1],
185
- ], dtype=torch.float32)
186
-
187
- # 对内参 K 矩阵也进行对应的降采样缩放
188
- if split == "test":
189
- scale_x = args.img_width_test / w
190
- scale_y = args.img_height_test / h
191
- K[0, :] *= scale_x # 缩放 fx 和 cx
192
- K[1, :] *= scale_y # 缩放 fy 和 cy
193
- K[2, 2] = 1.0 # 保持齐次坐标为1
194
-
195
- return images, camtoworlds, K
196
-
197
-
198
- class SubjectLoader(torch.utils.data.Dataset):
199
- SPLITS = ["train", "val", "trainval", "test"]
200
- OPENGL_CAMERA = False
201
-
202
- def __init__(self, root_fp: str, split: str, subject_id=None, color_bkgd_aug: str="black", num_rays: int=None, near: float=None, far: float=None, batch_over_images: bool=True, args=None):
203
- super().__init__()
204
- self.WIDTH = args.img_width_test if split == "test" else args.img_width
205
- self.HEIGHT = args.img_height_test if split == "test" else args.img_height
206
- self.args = args
207
- self.split = split
208
- self.num_rays = num_rays
209
- self.training = (num_rays is not None) and (split in ["train", "trainval"])
210
- self.color_bkgd_aug = color_bkgd_aug
211
- self.batch_over_images = batch_over_images
212
-
213
- # 加载图像、位姿与针孔内参 K
214
- images, camtoworlds, K = _load_renderings(root_fp, split, args)
215
- self.images = torch.from_numpy(images).to(torch.float32)
216
- self.camtoworlds = torch.from_numpy(camtoworlds).to(torch.float32).to(args.device)
217
- self.K = K.to(args.device)
218
- self.aabb = torch.tensor(args.aabb, dtype=torch.float32, device=args.device).view(1, 6)
219
-
220
- # ---------------------------------------------------------
221
- # 1 & 2. 从 intrinsics.npy 读取已合并的 Shift 硬件偏移
222
- # ---------------------------------------------------------
223
- # 尝试获取 args.intrinsics_path,若未在 ini 中定义,则使用默认路径
224
- intrinsics_path = getattr(args, 'intrinsics_path',
225
- '/work/runrong/project_all/FlyingWithPhotons/ini_generate/intrinsics.npy')
226
-
227
- if os.path.exists(intrinsics_path):
228
- intrinsics = np.load(intrinsics_path, allow_pickle=True).item()
229
- shift_raw = intrinsics["shift"]
230
-
231
- if isinstance(shift_raw, torch.Tensor):
232
- shift_tensor = shift_raw.to(torch.float32).to(args.device)
233
- else:
234
- shift_tensor = torch.from_numpy(np.array(shift_raw, dtype=np.float32)).to(args.device)
235
-
236
- from loaders.calibration import shift_map
237
- shift_tensor = shift_map(shift_tensor, self.HEIGHT, self.WIDTH, args.device)
238
-
239
- # shift 为物理距离(负数),需除以 exposure_time 转换为 bins,再取反用于正向补偿 (与 eval_ours.py 一致)
240
- self.hardware_bin_shift = (-shift_tensor / args.exposure_time).to(torch.float32)
241
- self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool, device=args.device)
242
- else:
243
- print(f"!!! Warning: {intrinsics_path} 不存在,已将硬件补偿回退为 0 !!!")
244
- self.hardware_bin_shift = torch.zeros((self.HEIGHT, self.WIDTH), dtype=torch.float32, device=args.device)
245
- self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool, device=args.device)
246
-
247
- self.output_valid_mask = self.valid_mask.clone()
248
-
249
- def __len__(self):
250
- return len(self.images)
251
-
252
- @torch.no_grad()
253
- def __getitem__(self, index):
254
- data = self.fetch_data(index)
255
- return self.preprocess(data)
256
-
257
- def preprocess(self, data):
258
- rgba, rays, valid_mask = data["rgba"], data["rays"], data["valid_mask"]
259
- color_bkgd = torch.zeros(3, device=self.args.device) if self.training and self.color_bkgd_aug == "black" else torch.ones(3, device=self.args.device)
260
-
261
- return {
262
- "pixels": rgba.to(self.args.device),
263
- "rays": rays,
264
- "color_bkgd": color_bkgd,
265
- "valid_mask": valid_mask,
266
- **{k: v for k, v in data.items() if k not in ["rgba", "rays", "valid_mask"]},
267
- }
268
-
269
- def update_num_rays(self, num_rays):
270
- self.num_rays = num_rays
271
-
272
- def fetch_data(self, index):
273
- num_rays = self.num_rays
274
-
275
- if self.training:
276
- image_id = torch.randint(0, len(self.images), size=(num_rays,), device=self.camtoworlds.device) if self.batch_over_images else [index] * num_rays
277
- x = torch.randint(0, self.WIDTH, size=(num_rays,), device=self.camtoworlds.device)
278
- y = torch.randint(0, self.HEIGHT, size=(num_rays,), device=self.camtoworlds.device)
279
- else:
280
- image_id = [index]
281
- x, y = torch.meshgrid(torch.arange(self.WIDTH, device=self.camtoworlds.device), torch.arange(self.HEIGHT, device=self.camtoworlds.device), indexing="xy")
282
- x, y = x.flatten(), y.flatten()
283
-
284
- idx_y_cpu, idx_x_cpu = y.cpu(), x.cpu()
285
- idx_img_cpu = image_id.cpu() if isinstance(image_id, torch.Tensor) else image_id
286
-
287
- # 获取当前光线的直方图、基础有效掩码和纯硬件偏移
288
- rgba_raw = self.images[idx_img_cpu, idx_y_cpu, idx_x_cpu].to(self.args.device)
289
- base_valid_mask = self.output_valid_mask[y, x]
290
- bin_shift = self.hardware_bin_shift[y, x]
291
-
292
- c2w = self.camtoworlds[image_id]
293
-
294
- # 恢复原 Fwp 使用 Pinhole K 矩阵生成射线方向的逻辑
295
- camera_dirs = F.pad(
296
- torch.stack(
297
- [
298
- (x - self.K[0, 2] + 0.5) / self.K[0, 0] ,
299
- (y - self.K[1, 2] + 0.5) / self.K[1, 1] * (-1.0 if self.OPENGL_CAMERA else 1.0),
300
- ],
301
- dim=-1,
302
- ),
303
- (0, 1),
304
- value=1.0
305
- )
306
-
307
- directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
308
- origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
309
- viewdirs = directions / torch.linalg.norm(directions, dim=-1, keepdims=True)
310
-
311
- n_bins = rgba_raw.shape[1]
312
-
313
- # ---------------------------------------------------------
314
- # 3. 仅应用硬件相关的 Shift (AABB 的半程交点 Shift 已移除)
315
- # ---------------------------------------------------------
316
- rgba_input = rgba_raw.permute(0, 2, 1).unsqueeze(2).contiguous()
317
- t_grid = torch.linspace(-1, 1, n_bins, device=self.args.device)
318
- norm_shift = bin_shift / (n_bins / 2.0)
319
-
320
- # 应用网格偏移 (+ norm_shift)
321
- grid_x = t_grid.view(1, 1, n_bins) + norm_shift.view(-1, 1, 1)
322
- grid_y = torch.zeros_like(grid_x)
323
- grid = torch.stack([grid_x, grid_y], dim=-1).contiguous()
324
-
325
- # 关闭 cudnn 避免 grid_sample 非确定性错误
326
- import torch.backends.cudnn as cudnn
327
- original_cudnn_state = cudnn.enabled
328
- cudnn.enabled = False
329
- try:
330
- rgba_aligned = F.grid_sample(rgba_input, grid, mode='bilinear', padding_mode='zeros', align_corners=True)
331
- finally:
332
- cudnn.enabled = original_cudnn_state
333
-
334
- rgba = rgba_aligned.squeeze(2).permute(0, 2, 1)
335
- valid_mask, meas_peak_mask, signal_mask = compute_transient_valid_mask_torch(
336
- rgba,
337
- self.args,
338
- base_mask=base_valid_mask,
339
- undo_gamma=True,
340
- )
341
- # if torch.rand(1).item() < 0.01: # 抽样打印
342
- # print("DEBUG Train Loader - rgba max:", rgba.max().item())
343
-
344
- # 整理输出形状
345
- if self.training:
346
- origins = origins.view(num_rays, 3)
347
- viewdirs = viewdirs.view(num_rays, 3)
348
- rgba = rgba.view(num_rays, n_bins, -1)
349
- else:
350
- origins = origins.view(self.HEIGHT, self.WIDTH, 3)
351
- viewdirs = viewdirs.view(self.HEIGHT, self.WIDTH, 3)
352
- rgba = rgba.view(self.HEIGHT, self.WIDTH, n_bins, -1)
353
- valid_mask = valid_mask.view(self.HEIGHT, self.WIDTH)
354
- meas_peak_mask = meas_peak_mask.view(self.HEIGHT, self.WIDTH)
355
- signal_mask = signal_mask.view(self.HEIGHT, self.WIDTH)
356
-
357
- return {
358
- "rgba": rgba,
359
- "rays": Rays(origins=origins, viewdirs=viewdirs),
360
- "valid_mask": valid_mask,
361
- "meas_peak_mask": meas_peak_mask,
362
- "signal_mask": signal_mask,
363
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/loaders/streaming_loader.py DELETED
@@ -1,208 +0,0 @@
1
- import json
2
- import os
3
- import numpy as np
4
- import torch
5
- import torch.nn.functional as F
6
- import h5py
7
- from .utils import Rays
8
- import sys
9
- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
10
-
11
- def rays_from_h5(start, end, path, device="cuda:0"):
12
- with h5py.File(os.path.join(path, "samples.h5"), 'r') as f:
13
- data = np.array(f['dataset'][start:end, :, :3])
14
- data = torch.from_numpy(data).to(torch.float32)
15
- data = data.to(device)
16
- return data
17
-
18
- def get_x(start, end, path, device="cuda:0"):
19
- with h5py.File(os.path.join(path, "x.h5"), 'r') as f:
20
- x = torch.tensor(f['dataset'][start:end], device=device)
21
- return x
22
-
23
- def get_y(start, end, path, device="cuda:0"):
24
- with h5py.File(os.path.join(path, "y.h5"), 'r') as f:
25
- y = torch.tensor(f['dataset'][start:end], device=device)
26
- return y
27
-
28
- def get_file_indices(start, end, path):
29
- with h5py.File(os.path.join(path, "file_indices.h5"), 'r') as f:
30
- indices = torch.tensor(f['dataset'][start:end])
31
- indices = indices.type(torch.long)
32
- return indices
33
-
34
-
35
- def _load_renderings_metadata(root_fp: str, subject_id: str, split: str, args):
36
- """Load images from disk."""
37
-
38
- with open(
39
- os.path.join(root_fp, "transforms_{}.json".format(split)), "r"
40
- ) as fp:
41
- meta = json.load(fp)
42
- fnames = []
43
- camtoworlds = []
44
-
45
- for i in range(len(meta["frames"])):
46
- frame = meta["frames"][i]
47
- camtoworlds.append(frame["transform_matrix"])
48
-
49
- camtoworlds = np.stack(camtoworlds, axis=0)
50
-
51
- if args.version == "simulated":
52
- h, w = args.img_shape, args.img_shape
53
- camera_angle_x = float(meta["camera"])
54
- focal = 0.5 * w / np.tan(0.5 * camera_angle_x)
55
- K = torch.tensor(
56
- [
57
- [focal, 0, w / 2.0],
58
- [0, focal, h / 2.0],
59
- [0, 0, 1],
60
- ],
61
- dtype=torch.float32)
62
- else:
63
- K = torch.tensor(np.array(meta["camera"])).to(torch.float32)
64
-
65
- with h5py.File(os.path.join(root_fp, "samples.h5"), 'r') as f:
66
- length = f['dataset'].shape[0]
67
- return length, camtoworlds, K
68
-
69
- class SubjectLoaderIterable(torch.utils.data.IterableDataset):
70
- """Single subject data loader for training and evaluation."""
71
-
72
- SPLITS = ["train", "val", "trainval", "test"]
73
- OPENGL_CAMERA = True
74
-
75
- def __init__(
76
- self,
77
- counter,
78
- num_rays,
79
- root_fp: str,
80
- split: str,
81
- color_bkgd_aug: str = "white",
82
- subject_id = None,
83
- near: float = None,
84
- far: float = None,
85
- args = None,
86
-
87
- ):
88
- super().__init__()
89
- self.WIDTH = args.img_shape
90
- self.HEIGHT = args.img_shape
91
-
92
- self.args = args
93
- self.split = split
94
- self.num_rays = num_rays
95
- self.training = (num_rays is not None) and (
96
- split in ["train", "trainval"]
97
- )
98
- self.color_bkgd_aug = color_bkgd_aug
99
- self.root_fp = root_fp
100
- self.subject_id = subject_id
101
- self.len, self.camtoworlds, K = _load_renderings_metadata(
102
- self.root_fp, self.subject_id, self.split, args
103
- )
104
-
105
- self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32)
106
-
107
- self.K = K
108
- self.camtoworlds = self.camtoworlds.to(self.args.device)
109
- self.K = self.K.to(self.args.device)
110
- self.counter = counter
111
-
112
-
113
- def __iter__(self):
114
- while True:
115
- data = self.fetch_data()
116
- data = self.preprocess(data)
117
- yield data
118
-
119
- def __len__(self):
120
- return self.len
121
-
122
- def preprocess(self, data):
123
- pixels, rays = data["rgba"], data["rays"]
124
- pixels = torch.clip(pixels[...,self.args.t_min:self.args.t_max, :3]/self.args.dataset_scale, 0, 1)**(1/self.args.gamma)
125
-
126
- return {
127
- "pixels": pixels, # [n_rays, 3] or [h, w, 3]
128
- "rays": rays, # [n_rays,] or [h, w]
129
- "color_bkgd": None, # [3,]
130
- **{k: v for k, v in data.items() if k not in ["rgba", "rays"]},
131
- }
132
-
133
-
134
- def fetch_data(self):
135
- with self.num_rays.get_lock(): # ensure that only one worker can update num_rays at a time
136
- num_rays = self.num_rays.value
137
- with self.counter.get_lock(): # ensure that only one worker can update the counter at a time
138
- start_index = self.counter.value
139
- end_index = start_index + num_rays
140
- if end_index > self.len:
141
- self.counter.value = end_index - self.len
142
- elif end_index == self.len:
143
- self.counter.value = 0
144
- start_index = 0
145
- end_index = num_rays
146
- else:
147
- self.counter.value += num_rays
148
-
149
- # Load chunk of data.
150
- if end_index <= self.len:
151
- data = rays_from_h5(start_index, end_index, self.root_fp, self.args.device)
152
- x = get_x(start_index, end_index, self.root_fp, self.args.device)
153
- y = get_y(start_index, end_index, self.root_fp, self.args.device)
154
- cam_index = get_file_indices(start_index, end_index, self.root_fp)
155
-
156
- elif start_index < self.len and end_index > self.len:
157
- first_data = rays_from_h5(start_index, self.len, self.root_fp, self.args.device)
158
- second_data = rays_from_h5(0, end_index - self.len, self.root_fp, self.args.device)
159
- first_x = get_x(start_index, self.len, self.root_fp, self.args.device)
160
- second_x = get_x(0, end_index - self.len, self.root_fp, self.args.device)
161
- first_y = get_y(start_index, self.len, self.root_fp, self.args.device)
162
- second_y = get_y(0, end_index - self.len, self.root_fp, self.args.device)
163
- first_cam_index = get_file_indices(start_index, self.len, self.root_fp)
164
- second_cam_index = get_file_indices(0, end_index - self.len, self.root_fp)
165
-
166
- data = torch.cat((first_data, second_data),axis=0)
167
- x = torch.cat((first_x, second_x),axis=0)
168
- y = torch.cat((first_y, second_y),axis=0)
169
- cam_index = torch.cat((first_cam_index,second_cam_index),axis=0)
170
-
171
-
172
- c2w = self.camtoworlds[cam_index]
173
- rgba = data
174
-
175
- camera_dirs = F.pad(
176
- torch.stack(
177
- [
178
- (x - self.K[0, 2] + 0.5) / self.K[0, 0],
179
- (y - self.K[1, 2] + 0.5)
180
- / self.K[1, 1]
181
- * (-1.0 if self.OPENGL_CAMERA else 1.0),
182
- ],
183
- dim=-1,
184
- ),
185
- (0, 1),
186
- value=(-1.0 if self.OPENGL_CAMERA else 1.0),
187
- ) # [num_rays, 3]
188
-
189
- directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1)
190
- origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape)
191
- viewdirs = directions / torch.linalg.norm(
192
- directions, dim=-1, keepdims=True
193
- )
194
-
195
- if self.training:
196
- origins = torch.reshape(origins, (num_rays, 3))
197
- viewdirs = torch.reshape(viewdirs, (num_rays, 3))
198
- else:
199
- origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3))
200
- viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3))
201
- rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, -1))
202
-
203
- rays = Rays(origins=origins, viewdirs=viewdirs)
204
-
205
- return {
206
- "rgba": rgba, # [h, w, 4] or [num_rays, 4]
207
- "rays": rays, # [h, w, 3] or [num_rays, 3]
208
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/loaders/utils.py DELETED
@@ -1,12 +0,0 @@
1
- """
2
- Copyright (c) 2022 Ruilong Li, UC Berkeley.
3
- """
4
-
5
- import collections
6
-
7
- Rays = collections.namedtuple("Rays", ("origins", "viewdirs"))
8
-
9
-
10
- def namedtuple_map(fn, tup):
11
- """Apply `fn` to each element of `tup` and cast to `tup`'s namedtuple."""
12
- return type(tup)(*(None if x is None else fn(x) for x in tup))
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/misc/__init__.py DELETED
File without changes
codes/reconstruction/FlyingWithPhotons/misc/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (200 Bytes)
 
codes/reconstruction/FlyingWithPhotons/misc/__pycache__/summary.cpython-312.pyc DELETED
Binary file (8.35 kB)
 
codes/reconstruction/FlyingWithPhotons/misc/__pycache__/transient_volrend.cpython-312.pyc DELETED
Binary file (26.2 kB)
 
codes/reconstruction/FlyingWithPhotons/misc/dataset_utils.py DELETED
@@ -1,169 +0,0 @@
1
- import os
2
- import mat73
3
- import torch
4
- import numpy as np
5
- import json
6
- import h5py
7
-
8
- def read_h5(path):
9
- with h5py.File(path, 'r') as f:
10
- frames = np.array(f['data'])
11
- return frames
12
-
13
- def process_captured_data(files_path, savepath):
14
- for file in os.listdir(files_path):
15
- if file[-3:] == "mat" and (file[:-3]+"pt") not in os.listdir(savepath):
16
- filepath = os.path.join(files_path, file)
17
- rgba = mat73.loadmat(filepath)["transient"].transpose(1, 2, 0)[..., :][..., None]
18
- rgba = np.flip(np.flip(rgba, 0), 1)
19
- for i in range(3):
20
- rgba = (rgba[1::2, ::2] + rgba[::2, ::2] + rgba[1::2, 1::2] + rgba[::2, 1::2])/4
21
- torch.save(rgba, os.path.join(savepath, file[:-3]+"pt"))
22
-
23
- def bundle_rays(pathToH5s, outputPath, trainJsonPath):
24
- with open(trainJsonPath, "r") as fp:
25
- meta = json.load(fp)
26
- train_fnames = []
27
- for i in range(len(meta["frames"])):
28
- frame = meta["frames"][i]
29
- fname = frame["filepath"][:-2]+"h5"
30
- train_fnames.append(fname)
31
-
32
- frames = read_h5(os.path.join(pathToH5s, train_fnames[0]))
33
- w = frames.shape[0]
34
- h = frames.shape[1]
35
- bins = frames.shape[2]
36
-
37
- x = np.linspace(0, h-1, h)
38
- y = np.linspace(0, w-1, w)
39
- X, Y = np.meshgrid(x, y)
40
-
41
- if len(frames.shape) == 4:
42
- channels = 3
43
- else:
44
- channels = 1
45
- num_train_files = len(train_fnames)
46
-
47
- data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32)
48
- x_array = np.zeros(w*h*num_train_files)
49
- y_array = np.zeros(w*h*num_train_files)
50
- file_prefix_array = np.zeros(w*h*num_train_files)
51
-
52
- for ind, file in enumerate(train_fnames):
53
- print("Opening: " + file)
54
- frames = read_h5(os.path.join(pathToH5s, file))
55
- frames = frames.reshape(-1, frames.shape[2], frames.shape[3])
56
-
57
- data_array[ind*w*h:(ind+1)*w*h] = frames[..., :3]
58
- x_array[ind*w*h:(ind+1)*w*h] = X.flatten()
59
- y_array[ind*w*h:(ind+1)*w*h] = Y.flatten()
60
- file_prefix_array[ind*w*h:(ind+1)*w*h] = ind
61
-
62
- p = np.random.permutation(data_array.shape[0])
63
- data_array = data_array[p]
64
- x_array = x_array[p]
65
- y_array = y_array[p]
66
- file_prefix_array = file_prefix_array[p]
67
-
68
-
69
- print("Outputting to files")
70
- file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w')
71
- dataset = file.create_dataset(
72
- "dataset", data_array.shape, dtype='f', data=data_array
73
- )
74
- file.close()
75
-
76
- file = h5py.File(os.path.join(outputPath, "x.h5"), 'w')
77
- dataset = file.create_dataset(
78
- "dataset", x_array.shape, dtype='f', data=x_array
79
- )
80
- file.close()
81
-
82
- file = h5py.File(os.path.join(outputPath, "y.h5"), 'w')
83
- dataset = file.create_dataset(
84
- "dataset", y_array.shape, dtype='f', data=y_array
85
- )
86
- file.close()
87
- file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w')
88
- dataset = file.create_dataset(
89
- "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array
90
- )
91
- file.close()
92
-
93
-
94
- def bundle_rays_cap(pathToH5s, outputPath, trainJsonPath):
95
- with open(trainJsonPath, "r") as fp:
96
- meta = json.load(fp)
97
- train_fnames = []
98
- for i in range(len(meta["frames"])):
99
- frame = meta["frames"][i]
100
- fname = frame["filepath"][:-2].split("/")[-1]+"mat"
101
- train_fnames.append(fname)
102
-
103
- # frames = read_h5_dataset(os.path.join(pathToH5s, train_fnames[0]))
104
- frames = mat73.loadmat(os.path.join(pathToH5s, train_fnames[0]))["transient"].transpose(1, 2, 0)
105
- w = frames.shape[0]
106
- h = frames.shape[1]
107
- # bins = frames.shape[2]
108
- bins = 3000
109
-
110
- x = np.linspace(0, h-1, h)
111
- y = np.linspace(0, w-1, w)
112
- X, Y = np.meshgrid(x, y)
113
-
114
- # if len(frames.shape) == 4:
115
- # channels = 3
116
- # else:
117
- channels = 1
118
- num_train_files = len(train_fnames)
119
-
120
- data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32)
121
- x_array = np.zeros(w*h*num_train_files)
122
- y_array = np.zeros(w*h*num_train_files)
123
- file_prefix_array = np.zeros(w*h*num_train_files)
124
-
125
- for ind, file in enumerate(train_fnames):
126
- print("Opening: " + file)
127
- # frames = read_h5_dataset(os.path.join(pathToH5s, file))
128
- frames = mat73.loadmat(os.path.join(pathToH5s, file))["transient"].transpose(1, 2, 0)
129
- frames = frames.reshape(-1, frames.shape[2])
130
-
131
- data_array[ind*w*h:(ind+1)*w*h] = frames[..., :bins, None]
132
- # del frames
133
- x_array[ind*w*h:(ind+1)*w*h] = X.flatten()
134
- y_array[ind*w*h:(ind+1)*w*h] = Y.flatten()
135
- file_prefix_array[ind*w*h:(ind+1)*w*h] = ind
136
-
137
- p = np.random.permutation(data_array.shape[0])
138
- data_array = data_array[p]
139
- x_array = x_array[p]
140
- y_array = y_array[p]
141
- file_prefix_array = file_prefix_array[p]
142
-
143
-
144
- print("Outputting to files")
145
- file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w')
146
- dataset = file.create_dataset(
147
- "dataset", data_array.shape, dtype='f', data=data_array
148
- )
149
- file.close()
150
-
151
- file = h5py.File(os.path.join(outputPath, "x.h5"), 'w')
152
- dataset = file.create_dataset(
153
- "dataset", x_array.shape, dtype='f', data=x_array
154
- )
155
- file.close()
156
-
157
- file = h5py.File(os.path.join(outputPath, "y.h5"), 'w')
158
- dataset = file.create_dataset(
159
- "dataset", y_array.shape, dtype='f', data=y_array
160
- )
161
- file.close()
162
- file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w')
163
- dataset = file.create_dataset(
164
- "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array
165
- )
166
- file.close()
167
-
168
- if __name__=="__main__":
169
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/misc/summary.py DELETED
@@ -1,116 +0,0 @@
1
- import imgviz
2
- import numpy as np
3
- from utils import render_image_with_occgrid_test
4
- import matplotlib.pyplot as plt
5
- import torchvision
6
- import torch
7
- import os
8
-
9
- @torch.no_grad()
10
- def write_summary_histogram(radiance_field, estimator, writer, test_dataset, step, args):
11
- img_scale = args.img_scale
12
- radiance_field.eval()
13
- estimator.eval()
14
- rgb_images = []
15
- depth_images = []
16
- gt_imgs = []
17
- accs = []
18
-
19
- pixels_to_plot = args.pixels_to_plot
20
- plotting_transients = []
21
- plotting_transients_depth = []
22
-
23
- plotting_transients_gt = []
24
-
25
- test_list = list(range(len(test_dataset)))
26
- if args.version == "simulated":
27
- color_channels = 3
28
- else:
29
- color_channels = 1
30
- n_output_dim = args.n_bins*(color_channels)
31
- with torch.no_grad():
32
-
33
- # sample transients from network
34
- for ind, i in enumerate(test_list):
35
- data = test_dataset[i]
36
- render_bkgd = data["color_bkgd"]
37
- rays = data["rays"]
38
- pixels = data["pixels"]
39
-
40
- # rendering
41
- rgb, acc, depth, _ = render_image_with_occgrid_test(
42
- 1024,
43
- # scene
44
- radiance_field,
45
- estimator,
46
- rays,
47
- args=args,
48
- # rendering options
49
- near_plane=args.near_plane,
50
- far_plane=args.far_plane,
51
- render_step_size=args.render_step_size,
52
- render_bkgd=render_bkgd,
53
- cone_angle=args.cone_angle,
54
- alpha_thre=args.alpha_thre,
55
- n_output_dim=n_output_dim,
56
- prop_delay=args.prop_delay
57
- )
58
-
59
- rgb = rgb.reshape(rays.origins.shape[0], rays.origins.shape[1], -1, color_channels)
60
-
61
- torch.save(rgb, os.path.join(args.outpath, f"test_{ind}_conv.pt"))
62
- torch.save(depth, os.path.join(args.outpath, f"test_{ind}_depth.pt"))
63
-
64
- if color_channels ==1:
65
- gt_imgs.append(torch.clip(pixels.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2))
66
- rgb_images.append(torch.clip(rgb.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2))
67
- else:
68
- gt_imgs.append(torch.clip(pixels.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2))
69
- rgb_images.append(torch.clip(rgb.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2))
70
- accs.append(acc.repeat(1, 1, 3).permute(2, 0, 1).cpu())
71
- dp = imgviz.depth2rgb(depth.cpu().squeeze().numpy(), colormap="inferno")
72
- depth_images.append(torch.from_numpy(dp).permute(2, 0, 1))
73
-
74
- if ind == 0:
75
- for pixel in pixels_to_plot:
76
- plotting_transients.append(rgb[pixel[0], pixel[1], :, 0])
77
- plotting_transients_gt.append(pixels[pixel[0], pixel[1], :, 0])
78
- plotting_transients_depth.append(depth[pixel[0], pixel[1]])
79
-
80
-
81
- images = torchvision.utils.make_grid(torch.stack(gt_imgs + rgb_images + depth_images + accs), nrow=len(test_list), normalize=False)
82
- mse = torch.mean((torch.stack(gt_imgs, dim=0) - torch.stack(rgb_images, dim=0))**2, (1,2,3))
83
- psnr = -10.0 * torch.log(mse) / np.log(10.0)
84
- print(f"image psnr: {psnr.mean():.2f}\n")
85
- writer.add_image('rgbdn', images, step)
86
-
87
- figure = plt.figure(figsize=((len(pixels_to_plot)+1), 4), dpi=250)
88
-
89
- # plot the predicted intensity
90
- plt.subplot(2, (len(pixels_to_plot)+1)//2, 1)
91
- plt.imshow(gt_imgs[0].permute(1, 2, 0))
92
- for i, pixel in enumerate(pixels_to_plot):
93
- plt.plot(pixel[1], pixel[0], '.', markersize=10, color='red')
94
- plt.text(pixel[1], pixel[0], str(i), color="yellow", fontsize=10)
95
- plt.gca().set_aspect(1.0/plt.gca().get_data_ratio(), adjustable='box')
96
- plt.title('gt intensity')
97
-
98
- for i, pixel in enumerate(pixels_to_plot):
99
- # plot transients
100
- plt.subplot(2, (len(pixels_to_plot)+1)//2, i+2)
101
- plt.plot(np.arange(args.n_bins), plotting_transients[i].detach().cpu(), label='pred', linewidth=0.5)
102
- plt.plot(np.arange(args.n_bins), plotting_transients_gt[i].detach().cpu(), label='gt', linewidth=0.5)
103
- plt.axvline(x = (plotting_transients_depth[i]/args.exposure_time).detach().cpu().numpy(), color = 'y')
104
- plt.title(f"pixel {i}")
105
- plt.ylabel('intensity')
106
- plt.legend(borderpad=0, labelspacing=0)
107
- plt.gca().set_aspect(1.0 / plt.gca().get_data_ratio(), adjustable='box')
108
-
109
- plt.tight_layout()
110
- writer.add_figure("transient_plots", figure, step)
111
-
112
-
113
- radiance_field.train()
114
- estimator.train()
115
-
116
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/misc/transient_volrend.py DELETED
@@ -1,637 +0,0 @@
1
- from typing import Callable, Dict, Optional, Tuple
2
- import torch
3
- from torch import Tensor
4
- from nerfacc.pack import pack_info
5
- from nerfacc.scan import exclusive_prod, exclusive_sum
6
-
7
- def rendering(
8
- # ray marching results
9
- t_starts: Tensor,
10
- t_ends: Tensor,
11
- ray_indices: Optional[Tensor] = None,
12
- n_rays: Optional[int] = None,
13
- # radiance field
14
- rgb_sigma_fn: Optional[Callable] = None,
15
- rgb_alpha_fn: Optional[Callable] = None,
16
- # rendering options
17
- render_bkgd: Optional[Tensor] = None,
18
- args = None,
19
- t_mins: Optional[Tensor] = None, # 新增:接收每个样本对应射线的 AABB 入射距离
20
- step: int = -1,
21
- ) -> Tuple[Tensor, Tensor, Tensor, Dict]:
22
- """Render the rays through the radience field defined by `rgb_sigma_fn`.
23
-
24
- This function is differentiable to the outputs of `rgb_sigma_fn` so it can
25
- be used for gradient-based optimization. It supports both batched and flattened input tensor.
26
- For flattened input tensor, both `ray_indices` and `n_rays` should be provided.
27
-
28
-
29
- Note:
30
- Either `rgb_sigma_fn` or `rgb_alpha_fn` should be provided.
31
-
32
- Warning:
33
- This function is not differentiable to `t_starts`, `t_ends` and `ray_indices`.
34
-
35
- Args:
36
- t_starts: Per-sample start distance. Tensor with shape (n_rays, n_samples) or (all_samples,).
37
- t_ends: Per-sample end distance. Tensor with shape (n_rays, n_samples) or (all_samples,).
38
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
39
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
40
- rgb_sigma_fn: A function that takes in samples {t_starts, t_ends,
41
- ray indices} and returns the post-activation rgb (..., 3) and density
42
- values (...,). The shape `...` is the same as the shape of `t_starts`.
43
- rgb_alpha_fn: A function that takes in samples {t_starts, t_ends,
44
- ray indices} and returns the post-activation rgb (..., 3) and opacity
45
- values (...,). The shape `...` is the same as the shape of `t_starts`.
46
- render_bkgd: Background color. Tensor with shape (3,).
47
- args: Arguments from config.
48
-
49
- Returns:
50
- Ray colors (n_rays, 3), opacities (n_rays, 1), depths (n_rays, 1) and a dict
51
- containing extra intermediate results (e.g., "weights", "trans", "alphas")
52
- """
53
- if ray_indices is not None:
54
- assert (
55
- t_starts.shape == t_ends.shape == ray_indices.shape
56
- ), "Since nerfacc 0.5.0, t_starts, t_ends and ray_indices must have the same shape (N,). "
57
-
58
- if rgb_sigma_fn is None and rgb_alpha_fn is None:
59
- raise ValueError(
60
- "At least one of `rgb_sigma_fn` and `rgb_alpha_fn` should be specified."
61
- )
62
-
63
- # Query sigma/alpha and color with gradients
64
- if rgb_sigma_fn is not None:
65
- if t_starts.shape[0] != 0:
66
- rgbs, sigmas = rgb_sigma_fn(t_starts, t_ends, ray_indices)
67
-
68
- # Shift for propagaton delay.
69
- if args.prop_delay:
70
- # rgbs = rgbs.reshape(rgbs.shape[0], args.n_bins, -1)
71
- # sample_dist = (t_starts + t_ends).view(-1, 1)
72
- # assert ray_indices.max() < t_mins.shape[0], "ray_indices 超出了 t_mins 的范围!"
73
- # #shift = (t_starts + t_ends)[:, None]/ 2.0
74
- # curr_t_mins = t_mins[ray_indices].view(-1, 1)
75
- # shift = sample_dist - 2.0*curr_t_mins
76
- # assert shift.shape == (t_starts.shape[0], 1), f"Shift 形状错误: {shift.shape}"
77
-
78
- # rgbs= shift_transient_grid_sample_3d(rgbs, shift, args.exposure_time, args.n_bins,chunk_size=16384)[..., None]
79
- #rgbs = rgbs.reshape((rgbs.shape[0], -1))
80
-
81
- # 诊断 1:检查 MLP 原始输出是否为 0
82
- do_debug = (step>=0 and step% 5000==0)
83
- if do_debug:
84
- print(f"\n[STEP{step}诊断]")
85
- print(f"DEBUG: MLP rgbs max before shift: {rgbs.max().item():.6f}")
86
- shift = (t_starts + t_ends)[:, None]/ 2.0
87
- # 诊断 2:检查平移量(Bins)的量级
88
- avg_bins_move = (shift / args.exposure_time).mean().item()
89
- if do_debug:
90
- print(f"DEBUG: Average bins_move: {avg_bins_move:.2f}")
91
- rgbs_transient = rgbs.reshape(rgbs.shape[0], args.n_bins, -1)
92
- # 执行平移
93
- rgbs_shifted = shift_transient_grid_sample_3d(
94
- rgbs_transient,
95
- shift,
96
- args.exposure_time,
97
- args.n_bins,
98
- chunk_size=16384
99
- )
100
- # 诊断 3:检查平移后是否全为 0
101
- if do_debug and rgbs_shifted.max() == 0 and rgbs_transient.max() > 0:
102
- print("警告:grid_sample 将所有信号平移到了有效窗口之外!请检查 exposure_time 和 shift 物理单位���")
103
-
104
- rgbs = rgbs_shifted.reshape((rgbs.shape[0], -1))
105
-
106
-
107
- else:
108
- rgbs = torch.empty((0, 3), device=t_starts.device)
109
- sigmas = torch.empty((0,), device=t_starts.device)
110
- channel_num = 1
111
- assert (
112
- sigmas.shape == t_starts.shape
113
- ), "sigmas must have shape of (N,)! Got {}".format(sigmas.shape)
114
-
115
- # Rendering: compute weights.
116
- weights, trans, alphas = render_weight_from_density(
117
- t_starts,
118
- t_ends,
119
- sigmas,
120
- ray_indices=ray_indices,
121
- n_rays=n_rays,
122
- )
123
- extras = {
124
- "weights": weights,
125
- "alphas": alphas,
126
- "trans": trans,
127
- "sigmas": sigmas,
128
- "rgbs": rgbs,
129
- }
130
- elif rgb_alpha_fn is not None:
131
- if t_starts.shape[0] != 0:
132
- rgbs, alphas = rgb_alpha_fn(t_starts, t_ends, ray_indices)
133
- else:
134
- rgbs = torch.empty((0, 3), device=t_starts.device)
135
- alphas = torch.empty((0,), device=t_starts.device)
136
-
137
- assert (
138
- alphas.shape == t_starts.shape
139
- ), "alphas must have shape of (N,)! Got {}".format(alphas.shape)
140
-
141
- # Rendering: compute weights.
142
- weights, trans = render_weight_from_alpha(
143
- alphas,
144
- ray_indices=ray_indices,
145
- n_rays=n_rays,
146
- )
147
- extras = {
148
- "weights": weights,
149
- "trans": trans,
150
- "rgbs": rgbs,
151
- "alphas": alphas,
152
- }
153
-
154
- # Rendering: accumulate rgbs, opacities, and depths along the rays.
155
- colors = accumulate_along_rays(
156
- weights, values=rgbs, ray_indices=ray_indices, n_rays=n_rays
157
- )
158
- # print("debug:accumulate rgbs:",colors.max())
159
-
160
- opacities = accumulate_along_rays(
161
- weights, values=None, ray_indices=ray_indices, n_rays=n_rays
162
- )
163
- depths = accumulate_along_rays(
164
- weights,
165
- values=(t_starts + t_ends)[..., None] / 2.0,
166
- ray_indices=ray_indices,
167
- n_rays=n_rays,
168
- )
169
- depths = depths / opacities.clamp_min(torch.finfo(rgbs.dtype).eps)
170
- return colors, opacities, depths, extras
171
-
172
- def render_transmittance_from_alpha(
173
- alphas: Tensor,
174
- packed_info: Optional[Tensor] = None,
175
- ray_indices: Optional[Tensor] = None,
176
- n_rays: Optional[int] = None,
177
- prefix_trans: Optional[Tensor] = None,
178
- ) -> Tensor:
179
- """Compute transmittance :math:`T_i` from alpha :math:`\\alpha_i`.
180
-
181
- .. math::
182
- T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j)
183
-
184
- This function supports both batched and flattened input tensor. For flattened input tensor, either
185
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
186
-
187
- Args:
188
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
189
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
190
- of each chunk in the flattened samples, with in total n_rays chunks.
191
- Useful for flattened input.
192
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
193
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
194
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
195
-
196
- Returns:
197
- The rendering transmittance with the same shape as `alphas`.
198
-
199
- Examples:
200
-
201
- .. code-block:: python
202
-
203
- >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
204
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
205
- >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices)
206
- tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0])
207
- """
208
- # FIXME Try not to use exclusive_prod because:
209
- # 1. torch.cumprod is much slower than torch.cumsum
210
- # 2. exclusive_prod gradient on input == 0 is not correct.
211
- if ray_indices is not None and packed_info is None:
212
- packed_info = pack_info(ray_indices, n_rays)
213
-
214
- trans = exclusive_prod(1 - alphas, packed_info)
215
- if prefix_trans is not None:
216
- trans *= prefix_trans
217
- return trans
218
-
219
-
220
- def render_transmittance_from_density(
221
- t_starts: Tensor,
222
- t_ends: Tensor,
223
- sigmas: Tensor,
224
- packed_info: Optional[Tensor] = None,
225
- ray_indices: Optional[Tensor] = None,
226
- n_rays: Optional[int] = None,
227
- prefix_trans: Optional[Tensor] = None,
228
- ) -> Tuple[Tensor, Tensor]:
229
- """Compute transmittance :math:`T_i` from density :math:`\\sigma_i`.
230
-
231
- .. math::
232
- T_i = exp(-\\sum_{j=1}^{i-1}\\sigma_j\delta_j)
233
-
234
- This function supports both batched and flattened input tensor. For flattened input tensor, either
235
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
236
-
237
- Args:
238
- t_starts: Where the frustum-shape sample starts along a ray. Tensor with \
239
- shape (all_samples,) or (n_rays, n_samples).
240
- t_ends: Where the frustum-shape sample ends along a ray. Tensor with \
241
- shape (all_samples,) or (n_rays, n_samples).
242
- sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
243
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
244
- of each chunk in the flattened samples, with in total n_rays chunks.
245
- Useful for flattened input.
246
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
247
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
248
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
249
-
250
- Returns:
251
- The rendering transmittance and opacities, both with the same shape as `sigmas`.
252
-
253
- Examples:
254
-
255
- .. code-block:: python
256
-
257
- >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda")
258
- >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda")
259
- >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
260
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
261
- >>> transmittance, alphas = render_transmittance_from_density(
262
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices)
263
- transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00]
264
- alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59]
265
-
266
- """
267
- if ray_indices is not None and packed_info is None:
268
- packed_info = pack_info(ray_indices, n_rays)
269
-
270
- sigmas_dt = sigmas * (t_ends - t_starts)
271
- alphas = 1.0 - torch.exp(-sigmas_dt)
272
- trans = torch.exp(-exclusive_sum(sigmas_dt, packed_info))
273
- if prefix_trans is not None:
274
- trans *= prefix_trans
275
- return trans, alphas
276
-
277
-
278
- def render_weight_from_alpha(
279
- alphas: Tensor,
280
- packed_info: Optional[Tensor] = None,
281
- ray_indices: Optional[Tensor] = None,
282
- n_rays: Optional[int] = None,
283
- prefix_trans: Optional[Tensor] = None,
284
- ) -> Tuple[Tensor, Tensor]:
285
- """Compute rendering weights :math:`w_i` from opacity :math:`\\alpha_i`.
286
-
287
- .. math::
288
- w_i = T_i\\alpha_i, \\quad\\textrm{where}\\quad T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j)
289
-
290
- This function supports both batched and flattened input tensor. For flattened input tensor, either
291
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
292
-
293
- Args:
294
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
295
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
296
- of each chunk in the flattened samples, with in total n_rays chunks.
297
- Useful for flattened input.
298
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
299
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
300
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
301
-
302
- Returns:
303
- The rendering weights and transmittance, both with the same shape as `alphas`.
304
-
305
- Examples:
306
-
307
- .. code-block:: python
308
-
309
- >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
310
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
311
- >>> weights, transmittance = render_weight_from_alpha(alphas, ray_indices=ray_indices)
312
- weights: [0.4, 0.48, 0.012, 0.8, 0.02, 0.0, 0.9])
313
- transmittance: [1.00, 0.60, 0.12, 1.00, 0.20, 1.00, 1.00]
314
-
315
- """
316
- trans = render_transmittance_from_alpha(
317
- alphas, packed_info, ray_indices, n_rays, prefix_trans
318
- )
319
- weights = trans * alphas
320
- return weights, trans
321
-
322
-
323
- def render_weight_from_density(
324
- t_starts: Tensor,
325
- t_ends: Tensor,
326
- sigmas: Tensor,
327
- packed_info: Optional[Tensor] = None,
328
- ray_indices: Optional[Tensor] = None,
329
- n_rays: Optional[int] = None,
330
- prefix_trans: Optional[Tensor] = None,
331
- ) -> Tuple[Tensor, Tensor, Tensor]:
332
- """Compute rendering weights :math:`w_i` from density :math:`\\sigma_i` and interval :math:`\\delta_i`.
333
-
334
- .. math::
335
- w_i = T_i(1 - exp(-\\sigma_i\delta_i)), \\quad\\textrm{where}\\quad T_i = exp(-\\sum_{j=1}^{i-1}\\sigma_j\delta_j)
336
-
337
- This function supports both batched and flattened input tensor. For flattened input tensor, either
338
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
339
-
340
- Args:
341
- t_starts: The start time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
342
- t_ends: The end time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
343
- sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
344
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
345
- of each chunk in the flattened samples, with in total n_rays chunks.
346
- Useful for flattened input.
347
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
348
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
349
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
350
-
351
- Returns:
352
- The rendering weights, transmittance and opacities, both with the same shape as `sigmas`.
353
-
354
- Examples:
355
-
356
- .. code-block:: python
357
-
358
- >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda")
359
- >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda")
360
- >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
361
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
362
- >>> weights, transmittance, alphas = render_weight_from_density(
363
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices)
364
- weights: [0.33, 0.37, 0.03, 0.55, 0.04, 0.00, 0.59]
365
- transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00]
366
- alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59]
367
-
368
- """
369
- trans, alphas = render_transmittance_from_density(
370
- t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans
371
- )
372
- weights = trans * alphas
373
- return weights, trans, alphas
374
-
375
-
376
- @torch.no_grad()
377
- def render_visibility_from_alpha(
378
- alphas: Tensor,
379
- packed_info: Optional[Tensor] = None,
380
- ray_indices: Optional[Tensor] = None,
381
- n_rays: Optional[int] = None,
382
- early_stop_eps: float = 1e-4,
383
- alpha_thre: float = 0.0,
384
- prefix_trans: Optional[Tensor] = None,
385
- ) -> Tensor:
386
- """Compute visibility from opacity :math:`\\alpha_i`.
387
-
388
- In this function, we first compute the transmittance from the sample opacity. The
389
- transmittance is then used to filter out occluded samples. And opacity is used to
390
- filter out transparent samples. The function returns a boolean tensor indicating
391
- which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`).
392
-
393
- This function supports both batched and flattened input tensor. For flattened input tensor, either
394
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
395
-
396
- Args:
397
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
398
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
399
- of each chunk in the flattened samples, with in total n_rays chunks.
400
- Useful for flattened input.
401
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
402
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
403
- early_stop_eps: The early stopping threshold on transmittance.
404
- alpha_thre: The threshold on opacity.
405
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
406
-
407
- Returns:
408
- A boolean tensor indicating which samples are visible. Same shape as `alphas`.
409
-
410
- Examples:
411
-
412
- .. code-block:: python
413
-
414
- >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
415
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
416
- >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices)
417
- tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0])
418
- >>> visibility = render_visibility_from_alpha(
419
- >>> alphas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2)
420
- tensor([True, True, False, True, False, False, True])
421
-
422
- """
423
- trans = render_transmittance_from_alpha(
424
- alphas, packed_info, ray_indices, n_rays, prefix_trans
425
- )
426
- vis = trans >= early_stop_eps
427
- if alpha_thre > 0:
428
- vis = vis & (alphas >= alpha_thre)
429
- return vis
430
-
431
-
432
- @torch.no_grad()
433
- def render_visibility_from_density(
434
- t_starts: Tensor,
435
- t_ends: Tensor,
436
- sigmas: Tensor,
437
- packed_info: Optional[Tensor] = None,
438
- ray_indices: Optional[Tensor] = None,
439
- n_rays: Optional[int] = None,
440
- early_stop_eps: float = 1e-4,
441
- alpha_thre: float = 0.0,
442
- prefix_trans: Optional[Tensor] = None,
443
- ) -> Tensor:
444
- """Compute visibility from density :math:`\\sigma_i` and interval :math:`\\delta_i`.
445
-
446
- In this function, we first compute the transmittance and opacity from the sample density. The
447
- transmittance is then used to filter out occluded samples. And opacity is used to
448
- filter out transparent samples. The function returns a boolean tensor indicating
449
- which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`).
450
-
451
- This function supports both batched and flattened input tensor. For flattened input tensor, either
452
- (`packed_info`) or (`ray_indices` and `n_rays`) should be provided.
453
-
454
- Args:
455
- alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples).
456
- packed_info: A tensor of shape (n_rays, 2) that specifies the start and count
457
- of each chunk in the flattened samples, with in total n_rays chunks.
458
- Useful for flattened input.
459
- ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples).
460
- n_rays: Number of rays. Only useful when `ray_indices` is provided.
461
- early_stop_eps: The early stopping threshold on transmittance.
462
- alpha_thre: The threshold on opacity.
463
- prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,).
464
-
465
- Returns:
466
- A boolean tensor indicating which samples are visible. Same shape as `alphas`.
467
-
468
- Examples:
469
-
470
- .. code-block:: python
471
-
472
- >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda")
473
- >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda")
474
- >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda")
475
- >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda")
476
- >>> transmittance, alphas = render_transmittance_from_density(
477
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices)
478
- transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00]
479
- alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59]
480
- >>> visibility = render_visibility_from_density(
481
- >>> t_starts, t_ends, sigmas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2)
482
- tensor([True, True, False, True, False, False, True])
483
-
484
- """
485
- trans, alphas = render_transmittance_from_density(
486
- t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans
487
- )
488
- vis = trans >= early_stop_eps
489
- if alpha_thre > 0:
490
- vis = vis & (alphas >= alpha_thre)
491
- return vis
492
-
493
-
494
- def accumulate_along_rays(
495
- weights: Tensor,
496
- values: Optional[Tensor] = None,
497
- ray_indices: Optional[Tensor] = None,
498
- n_rays: Optional[int] = None,
499
- ) -> Tensor:
500
- """Accumulate volumetric values along the ray.
501
-
502
- This function supports both batched inputs and flattened inputs with
503
- `ray_indices` and `n_rays` provided.
504
-
505
- Note:
506
- This function is differentiable to `weights` and `values`.
507
-
508
- Args:
509
- weights: Weights to be accumulated. If `ray_indices` not provided,
510
- `weights` must be batched with shape (n_rays, n_samples). Else it
511
- must be flattened with shape (all_samples,).
512
- values: Values to be accumulated. If `ray_indices` not provided,
513
- `values` must be batched with shape (n_rays, n_samples, D). Else it
514
- must be flattened with shape (all_samples, D). None means
515
- we accumulate weights along rays. Default: None.
516
- ray_indices: Ray indices of the samples with shape (all_samples,).
517
- If provided, `weights` must be a flattened tensor with shape (all_samples,)
518
- and values (if not None) must be a flattened tensor with shape (all_samples, D).
519
- Default: None.
520
- n_rays: Number of rays. Should be provided together with `ray_indices`. Default: None.
521
-
522
- Returns:
523
- Accumulated values with shape (n_rays, D). If `values` is not given we return
524
- the accumulated weights, in which case D == 1.
525
-
526
- Examples:
527
-
528
- .. code-block:: python
529
-
530
- # Rendering: accumulate rgbs, opacities, and depths along the rays.
531
- colors = accumulate_along_rays(weights, rgbs, ray_indices, n_rays)
532
- opacities = accumulate_along_rays(weights, None, ray_indices, n_rays)
533
- depths = accumulate_along_rays(
534
- weights,
535
- (t_starts + t_ends)[:, None] / 2.0,
536
- ray_indices,
537
- n_rays,
538
- )
539
- # (n_rays, 3), (n_rays, 1), (n_rays, 1)
540
- print(colors.shape, opacities.shape, depths.shape)
541
-
542
- """
543
- if values is None:
544
- src = weights[..., None]
545
- else:
546
- assert values.dim() == weights.dim() + 1
547
- assert weights.shape == values.shape[:-1]
548
- src = weights[..., None] * values
549
- if ray_indices is not None:
550
- assert n_rays is not None, "n_rays must be provided"
551
- assert weights.dim() == 1, "weights must be flattened"
552
- outputs = torch.zeros(
553
- (n_rays, src.shape[-1]), device=src.device, dtype=src.dtype
554
- )
555
- outputs.index_add_(0, ray_indices, src)
556
- else:
557
- outputs = torch.sum(src, dim=-2)
558
- return outputs
559
-
560
-
561
- def accumulate_along_rays_(
562
- weights: Tensor,
563
- values: Optional[Tensor] = None,
564
- ray_indices: Optional[Tensor] = None,
565
- outputs: Optional[Tensor] = None,
566
- ) -> None:
567
- """Accumulate volumetric values along the ray.
568
-
569
- Inplace version of :func:`accumulate_along_rays`.
570
- """
571
- if weights.shape[0] == 0:
572
- return 0
573
- if values is None:
574
- src = weights[..., None]
575
- else:
576
- assert values.dim() == weights.dim() + 1
577
- assert weights.shape == values.shape[:-1]
578
- src = weights[..., None] * values
579
- if ray_indices is not None:
580
- # assert weights.dim() == 1, "weights must be flattened"
581
- # assert (
582
- # outputs.dim() == 2 and outputs.shape[-1] == src.shape[-1]
583
- # ), "outputs must be of shape (n_rays, D)"
584
- outputs.index_add_(0, ray_indices, src)
585
- else:
586
- outputs.add_(src.sum(dim=-2))
587
-
588
-
589
- def shift_transient_grid_sample_3d(transient, depth, exposure_time, n_bins, chunk_size=16384):
590
- # 修改移动函数,分块执行1D信号平移,防止显存爆炸
591
- # all_samples = transient.shape[0]
592
- # shifted_chunks = []
593
- # z_base = torch.arange(n_bins, device=transient.device).float().view(1, n_bins)
594
- # for i in range(0, all_samples, chunk_size):
595
- # curr_transient = transient[i : i+chunk_size]
596
- # curr_depth = depth[i : i+chunk_size]
597
- # curr_x_dim = curr_transient.shape[0]
598
- # bins_move = curr_depth / exposure_time
599
- # if curr_x_dim % 2 == 0:
600
- # x = (torch.arange(curr_x_dim, device=transient.device) - curr_x_dim//2+0.5)/(curr_x_dim//2-0.5)
601
- # else:
602
- # x = (torch.arange(curr_x_dim, device=transient.device) - curr_x_dim//2)/(curr_x_dim//2)
603
- # if curr_x_dim == 1:
604
- # x = torch.zeros_like(x)
605
- # z = torch.arange(n_bins, device=transient.device).float()
606
- # X, Z = torch.meshgrid(x, z, indexing="ij")
607
- # Z = Z-bins_move
608
- # Z[Z<0] = n_bins + 1
609
- # Z = (Z-n_bins//2 + 0.5) / (n_bins//2 -0.5)
610
- # grid = torch.stack((Z, X), dim=-1)[None, ...]
611
- # shifted = torch.nn.functional.grid_sample(
612
- # curr_transient.permute(2, 0, 1)[None],
613
- # grid,
614
- # align_corners=True,
615
- # padding_mode='zeros'
616
- # )
617
- # shifted_chunks.append(shifted.squeeze(0).permute(1, 2, 0))
618
- # return torch.cat(shifted_chunks, dim=0)
619
- x_dim = transient.shape[0]
620
- bins_move = depth/exposure_time
621
- if x_dim%2 == 0:
622
- x = (torch.arange(x_dim, device=transient.device)-x_dim//2+0.5)/(x_dim//2-0.5)
623
- else:
624
- x = (torch.arange(x_dim, device=transient.device)-x_dim//2)/(x_dim//2)
625
-
626
- if x_dim == 1:
627
- x = torch.zeros_like(x)
628
-
629
- z = torch.arange(n_bins, device=transient.device).float()
630
- X, Z = torch.meshgrid(x, z, indexing="ij")
631
- Z = Z - bins_move
632
- Z[Z<0] = n_bins+1
633
- Z = (Z-n_bins//2+0.5)/(n_bins//2-0.5)
634
- grid = torch.stack((Z, X), dim=-1)[None, ...]
635
- shifted_transient = torch.nn.functional.grid_sample(transient.permute(2, 0, 1)[None], grid, align_corners=True).squeeze(0).permute(1, 2, 0)
636
- return shifted_transient
637
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/radiance_fields/__init__.py DELETED
File without changes
codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (211 Bytes)
 
codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/ngp.cpython-312.pyc DELETED
Binary file (13 kB)
 
codes/reconstruction/FlyingWithPhotons/radiance_fields/ngp.py DELETED
@@ -1,306 +0,0 @@
1
- """
2
- Copyright (c) 2022 Ruilong Li, UC Berkeley.
3
- """
4
-
5
- from typing import Callable, List, Union
6
-
7
- import numpy as np
8
- import torch
9
- from torch.autograd import Function
10
- from torch.cuda.amp import custom_bwd, custom_fwd
11
- import torch.nn.functional as F
12
-
13
- try:
14
- import tinycudann as tcnn
15
- except ImportError as e:
16
- print(
17
- f"Error: {e}! "
18
- "Please install tinycudann by: "
19
- "pip install git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch"
20
- )
21
- exit()
22
-
23
-
24
- class _TruncExp(Function): # pylint: disable=abstract-method
25
- # Implementation from torch-ngp:
26
- # https://github.com/ashawkey/torch-ngp/blob/93b08a0d4ec1cc6e69d85df7f0acdfb99603b628/activation.py
27
- @staticmethod
28
- @custom_fwd(cast_inputs=torch.float32)
29
- def forward(ctx, x): # pylint: disable=arguments-differ
30
- ctx.save_for_backward(x)
31
- return torch.exp(x)
32
-
33
- @staticmethod
34
- @custom_bwd
35
- def backward(ctx, g): # pylint: disable=arguments-differ
36
- x = ctx.saved_tensors[0]
37
- return g * torch.exp(torch.clamp(x, max=15))
38
-
39
-
40
- trunc_exp = _TruncExp.apply
41
-
42
-
43
- def contract_to_unisphere(
44
- x: torch.Tensor,
45
- aabb: torch.Tensor,
46
- ord: Union[str, int] = 2,
47
- # ord: Union[float, int] = float("inf"),
48
- eps: float = 1e-6,
49
- derivative: bool = False,
50
- ):
51
- aabb_min, aabb_max = torch.split(aabb, 3, dim=-1)
52
- x = (x - aabb_min) / (aabb_max - aabb_min)
53
- x = x * 2 - 1 # aabb is at [-1, 1]
54
- mag = torch.linalg.norm(x, ord=ord, dim=-1, keepdim=True)
55
- mask = mag.squeeze(-1) > 1
56
-
57
- if derivative:
58
- dev = (2 * mag - 1) / mag**2 + 2 * x**2 * (
59
- 1 / mag**3 - (2 * mag - 1) / mag**4
60
- )
61
- dev[~mask] = 1.0
62
- dev = torch.clamp(dev, min=eps)
63
- return dev
64
- else:
65
- x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])
66
- x = x / 4 + 0.5 # [-inf, inf] is at [0, 1]
67
- return x
68
-
69
-
70
- class NGPRadianceField(torch.nn.Module):
71
- """Instance-NGP Radiance Field"""
72
-
73
- def __init__(
74
- self,
75
- aabb: Union[torch.Tensor, List[float]],
76
- num_dim: int = 3,
77
- use_viewdirs: bool = True,
78
- density_activation: Callable = lambda x: trunc_exp(x - 1),
79
- radiance_activation: Callable = lambda x: F.sigmoid(x),
80
- unbounded: bool = False,
81
- base_resolution: int = 16,
82
- max_resolution: int = 4096,
83
- geo_feat_dim: int = 15,
84
- n_levels: int = 16,
85
- log2_hashmap_size: int = 19,
86
- args = None
87
- ) -> None:
88
- super().__init__()
89
- if not isinstance(aabb, torch.Tensor):
90
- aabb = torch.tensor(aabb, dtype=torch.float32)
91
- self.register_buffer("aabb", aabb)
92
- self.num_dim = num_dim
93
- self.radiance_activation = radiance_activation
94
- self.use_viewdirs = use_viewdirs
95
- self.density_activation = density_activation
96
- self.unbounded = unbounded
97
- self.base_resolution = base_resolution
98
- self.max_resolution = max_resolution
99
- self.geo_feat_dim = geo_feat_dim
100
- self.n_levels = n_levels
101
- self.log2_hashmap_size = log2_hashmap_size
102
- self.version = args.version
103
- self.args = args
104
- if self.version == "simulated":
105
- self.colour_channels = 3
106
- else:
107
- self.colour_channels = 1
108
-
109
- self.radiance_activation = radiance_activation
110
- self.n_output_dim = args.n_bins*self.colour_channels
111
-
112
-
113
-
114
-
115
- per_level_scale = np.exp(
116
- (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1)
117
- ).tolist()
118
-
119
- if self.use_viewdirs:
120
- self.direction_encoding = tcnn.Encoding(
121
- n_input_dims=num_dim,
122
- encoding_config={
123
- "otype": "Composite",
124
- "nested": [
125
- {
126
- "n_dims_to_encode": 3,
127
- "otype": "SphericalHarmonics",
128
- "degree": 4,
129
- },
130
- # {"otype": "Identity", "n_bins": 4, "degree": 4},
131
- ],
132
- },
133
- )
134
-
135
- self.mlp_base = tcnn.NetworkWithInputEncoding(
136
- n_input_dims=num_dim,
137
- n_output_dims=1 + self.geo_feat_dim,
138
- encoding_config={
139
- "otype": "HashGrid",
140
- "n_levels": n_levels,
141
- "n_features_per_level": 2,
142
- "log2_hashmap_size": log2_hashmap_size,
143
- "base_resolution": base_resolution,
144
- "per_level_scale": per_level_scale,
145
- },
146
- network_config={
147
- "otype": "FullyFusedMLP",
148
- "activation": "ReLU",
149
- "output_activation": "None",
150
- "n_neurons": 64,
151
- "n_hidden_layers": 1,
152
- },
153
- )
154
- if self.geo_feat_dim > 0:
155
- self.mlp_head = tcnn.Network(
156
- n_input_dims=(
157
- (
158
- self.direction_encoding.n_output_dims
159
- if self.use_viewdirs
160
- else 0
161
- )
162
- + self.geo_feat_dim
163
- ),
164
- n_output_dims=self.n_output_dim,
165
- network_config={
166
- "otype": "FullyFusedMLP",
167
- "activation": "ReLU",
168
- "output_activation": "None",
169
- "n_neurons": 64,
170
- "n_hidden_layers": 2,
171
- },
172
- )
173
-
174
- def query_density(self, x, return_feat: bool = False):
175
- if self.unbounded:
176
- x = contract_to_unisphere(x, self.aabb)
177
- else:
178
- aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1)
179
- x = (x - aabb_min) / (aabb_max - aabb_min)
180
- selector = ((x > 0.0) & (x < 1.0)).all(dim=-1)
181
- x = (
182
- self.mlp_base(x.view(-1, self.num_dim))
183
- .view(list(x.shape[:-1]) + [1 + self.geo_feat_dim])
184
- .to(x)
185
- )
186
- density_before_activation, base_mlp_out = torch.split(
187
- x, [1, self.geo_feat_dim], dim=-1
188
- )
189
- density = (
190
- self.density_activation(density_before_activation)
191
- * selector[..., None]
192
- )
193
- if return_feat:
194
- return density, base_mlp_out
195
- else:
196
- return density
197
-
198
- def _query_rgb(self, dir, embedding, apply_act: bool = True):
199
- # tcnn requires directions in the range [0, 1]
200
- if self.use_viewdirs:
201
- dir = (dir + 1.0) / 2.0
202
- d = self.direction_encoding(dir.reshape(-1, dir.shape[-1]))
203
- h = torch.cat([d, embedding.reshape(-1, self.geo_feat_dim)], dim=-1)
204
- else:
205
- h = embedding.reshape(-1, self.geo_feat_dim)
206
- rgb = (
207
- self.mlp_head(h)
208
- .reshape(list(embedding.shape[:-1]) + [self.n_output_dim])
209
- .to(embedding)
210
- )
211
- if apply_act:
212
- rgb = self.radiance_activation(rgb)
213
-
214
- return rgb
215
-
216
- def forward(
217
- self,
218
- positions: torch.Tensor,
219
- directions: torch.Tensor = None,
220
- ):
221
- if positions.shape[0] == 0:
222
- density = torch.zeros(0, device=positions.device)
223
- color = torch.zeros(0, 1200, device=positions.device)
224
- return color, density
225
-
226
- if self.use_viewdirs and (directions is not None):
227
- assert (
228
- positions.shape == directions.shape
229
- ), f"{positions.shape} v.s. {directions.shape}"
230
- density, embedding = self.query_density(positions, return_feat=True)
231
- rgb = self._query_rgb(directions, embedding=embedding)
232
- else:
233
- density, embedding = self.query_density(positions, return_feat=True)
234
- rgb = self._query_rgb(directions, embedding=embedding)
235
-
236
- return rgb, density # type: ignore
237
-
238
-
239
- class NGPDensityField(torch.nn.Module):
240
- """Instance-NGP Density Field used for resampling"""
241
-
242
- def __init__(
243
- self,
244
- aabb: Union[torch.Tensor, List[float]],
245
- num_dim: int = 3,
246
- density_activation: Callable = lambda x: trunc_exp(x - 1),
247
- unbounded: bool = False,
248
- base_resolution: int = 16,
249
- max_resolution: int = 128,
250
- n_levels: int = 5,
251
- log2_hashmap_size: int = 17,
252
- ) -> None:
253
- super().__init__()
254
- if not isinstance(aabb, torch.Tensor):
255
- aabb = torch.tensor(aabb, dtype=torch.float32)
256
- self.register_buffer("aabb", aabb)
257
- self.num_dim = num_dim
258
- self.density_activation = density_activation
259
- self.unbounded = unbounded
260
- self.base_resolution = base_resolution
261
- self.max_resolution = max_resolution
262
- self.n_levels = n_levels
263
- self.log2_hashmap_size = log2_hashmap_size
264
-
265
- per_level_scale = np.exp(
266
- (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1)
267
- ).tolist()
268
-
269
- self.mlp_base = tcnn.NetworkWithInputEncoding(
270
- n_input_dims=num_dim,
271
- n_output_dims=1,
272
- encoding_config={
273
- "otype": "HashGrid",
274
- "n_levels": n_levels,
275
- "n_features_per_level": 2,
276
- "log2_hashmap_size": log2_hashmap_size,
277
- "base_resolution": base_resolution,
278
- "per_level_scale": per_level_scale,
279
- },
280
- network_config={
281
- "otype": "FullyFusedMLP",
282
- "activation": "ReLU",
283
- "output_activation": "None",
284
- "n_neurons": 64,
285
- "n_hidden_layers": 1,
286
- },
287
- )
288
-
289
- def forward(self, positions: torch.Tensor):
290
- if self.unbounded:
291
- positions = contract_to_unisphere(positions, self.aabb)
292
- else:
293
- aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1)
294
- positions = (positions - aabb_min) / (aabb_max - aabb_min)
295
- selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1)
296
- density_before_activation = (
297
- self.mlp_base(positions.view(-1, self.num_dim))
298
- .view(list(positions.shape[:-1]) + [1])
299
- .to(positions)
300
- )
301
- density = (
302
- self.density_activation(density_before_activation)
303
- * selector[..., None]
304
- )
305
- return density
306
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
codes/reconstruction/FlyingWithPhotons/requirements.txt DELETED
@@ -1,23 +0,0 @@
1
- # Install PyTorch 2.5.1 / CUDA 11.8 first; see README.
2
- ConfigArgParse==1.7.5
3
- ImageIO==2.37.2
4
- PyYAML==6.0.3
5
- h5py==3.15.1
6
- imgviz==1.7.6
7
- lpips==0.1.4
8
- mat73==0.65
9
- matplotlib==3.10.7
10
- nerfacc==0.5.3
11
- numpy==1.26.4
12
- packaging==25.0
13
- pillow==12.0.0
14
- scikit-image==0.25.2
15
- scipy==1.15.3
16
- sparse==0.17.0
17
- tensorboard==2.10.1
18
- torch==2.5.1
19
- torchvision==0.20.1
20
- tqdm==4.67.1
21
-
22
- # CUDA extensions (install after PyTorch; source build needs the CUDA toolchain).
23
- tinycudann @ git+https://github.com/NVlabs/tiny-cuda-nn@38e50edc4a5f785afe0ef21f9c75b8949890be84#subdirectory=bindings/torch