diff --git a/codes/reconstruction/FlyingWithPhotons/.gitignore b/codes/reconstruction/FlyingWithPhotons/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6107427c6ea2f841b6eb0ac6c8b4886c2ba04a85 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.pyc +results/ +exp/ +runs/ +*.pth +*.ckpt diff --git a/codes/reconstruction/FlyingWithPhotons/LICENSE b/codes/reconstruction/FlyingWithPhotons/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/codes/reconstruction/FlyingWithPhotons/README.md b/codes/reconstruction/FlyingWithPhotons/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e64697b8126006e8f5c3a3211c39be6169ad40bb --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/README.md @@ -0,0 +1,72 @@ +# FlyingWithPhotons 最小复现版 + +保留原生训练、模型与采样代码;共同指标集中在 `evaluation/`,唯一评价入口为 `eval.py`。 + +在项目根目录执行;服务器模型解释器为 `/work/runrong/.conda/envs/Fwp/bin/python`: + +```bash +export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python +python train_ours.py -c configs/train.ini +python eval.py render -c configs/train.ini --config configs/eval.ini \ + --checkpoint_dir /absolute/checkpoint_directory --step 300000 \ + --output /absolute/new_result_directory +``` + +checkpoint 目录的训练归一化记录(或原 `params_full.txt`)必须与配置中的 dataset_scale、gamma 一致。 + +示例为 design_floor1 / 10 视角,参数模板来自原 fence_box 配置,不代表论文完整历史配置。其他场景、3/5 视角需使用真实训练参数和 canonical 测试位姿。保留单值/二维硬件偏移的兼容处理;训练时的编码、裁剪与原生射线模型未重写。 + +## 共同评价协议(V4) + +`eval.py` 是唯一公开评价入口,`render` 和 `saved` 最终均调用 `evaluation/evaluator.py`。`evaluation/renderer.py` 仅适配本方法的模型和射线采样;直方图和图像指标实现与其他两个项目相同。原来的两个 `shared_*` 包、`evaluate_metrics_shared.py`、FWP 的 `eval_ours.py` 和独立旧评分分支已移除。 + +### 强度尺度与直方图 PSNR + +评分前逐 bin 恢复全曝光光子计数: + +``` +trnerf / transientangelo: prediction_counts = prediction_encoded * actual_training_scale +FlyingWithPhotons: prediction_counts = prediction_encoded ** training_gamma * dataset_scale +reference_counts: 共同参考缓存中的已标定、未独立归一化的光子计数 +MSE = mean((prediction_counts - reference_counts)^2) # 共同有效像素的全部 bins / channels +histogram_psnr = 20*log10(P_scene) - 10*log10(MSE) +``` + +`P_scene` 固定于同一场景的十视角训练候选池,在三种方法及 3/5/10 视角配置之间共用。预测峰值、测试最大值和每视角拟合系数都不用于确定它。预测直方图不做上限裁剪、显示 gamma 或曝光拟合;FWP 的逆训练 gamma 在积分前逐 bin 执行。缺失实际训练尺度时直接报错,禁止用测试集最大值代替。TN/FWP 新训练会记录 `image_metric_normalization.json`;TA 将训练尺度写入 checkpoint。历史权重须提供经过核实的训练常数,代码不能从测试集推断它。 + +共同参考由校准后全计数 GT 生成;掩码为硬件有效像素、GT 峰值 ≥100、正信号的交集,独立于预测。直方图峰值 `P_scene` 与积分图像尺度 `D_scene` 是两个不同的固定量。显示图像 PSNR、SSIM、LPIPS 沿用整理前 V4 所采用的显示变换,另报无显示 gamma 的 `linear_psnr`。这些图像分数不应标成直方图 PSNR。SSIM 使用完整有效 7×7 窗口;LPIPS 使用统一环境的 VGG v0.1 / FP32。 + +### 对 Q6–Q8 的代码说明 + +- **Q6:不是未经修改的发布版 eval.py。** 当前只提供统一 V4;取消旧 `scale_int` 和动态预测/GT 峰值评分。GT、掩码、固定场景尺度来自同一份 contract。原生测试均执行 30 次前向:TN 每次重新获取带抖动射线,TA 复用同一抖动批次,FWP 复用像素射线。因此不能把三者概括为“30 次独立像素抖动”。这些方法自身的采样逻辑保留。 +- **Q7:内部归一化不直接作为比较尺度。** TN/TA 预测乘回实际训练常数;FWP 逐 bin 逆训练 gamma 并乘回训练 dataset_scale;共同 GT 直接使用计数。测试加载器内部即使独立归一化,也不会把它的归一化 GT 或最大值用于评分。这解决当前流程中由训练/测试独立归一化引入的比较尺度不一致。 +- **Q8:三种视角设置均使用共同的 canonical test.json 帧及原始位姿。** 九场景合计 158 帧,逐场景 contract 强制核对完整唯一帧集合及位姿,拒绝只评部分帧或同名不同位姿。低视角下剩余训练候选帧不额外加入测试;十视角候选池仍用于冻结共同评价尺度,属于评价标定数据,不作为低视角方法的额外训练输入。 + +以上描述的是修订后的代码协议,不能用来证明历史论文分数已经重算。此次目录整理没有重新训练模型,也没有完成九场景全量模型评测。 + +### 输出、环境与迁移 + +输出为 `prediction_manifest.json` 和 `unified_metrics/` 下的协议记录、逐视角指标、完整集合汇总及浮点评分数组。记录含训练尺度、gamma、共同参考/掩码校验和、评分代码哈希和解释器路径。可加 `--save-predictions` 保存未裁剪编码直方图以便复算;不保存旧口径指标和旧图表。已有结果目录禁止覆盖。 + +三个项目必须使用同一个图像评价环境。服务器运行前设置: + +```bash +export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python +``` + +迁移机器后将它改为共同评价环境的 Python 绝对路径。数据、标定、权重、共同参考缓存不复制进代码包;README 中的示例配置仍指向服务器的实际路径,发布数据时需同时提供对应 contract/GT 缓存并改为新路径。每种方法使用同一场景的同一份 contract。保存目录名中的旧日期仅是外部参考数据的位置,不再是代码导入依赖。 + +评分已有预测统一使用 `python eval.py saved --help` 查看参数,例如: + +```bash +python eval.py saved --prediction-dir /absolute/predictions \ + --prediction-manifest /absolute/predictions/prediction_manifest.json \ + --prediction-scale ACTUAL_TRAINING_SCALE --prediction-gamma 1 \ + --prediction-bin-width-s 7.5e-10 \ + --shared-reference-contract /absolute/reference/contract.json \ + --output /absolute/new_scores --device cpu +``` + +FWP 编码输出填写真实训练 gamma;已经恢复完整计数的导出填写 scale=1、gamma=1。有单位记录的 manifest 与命令参数冲突时会报错。 + +`requirements.txt` 保留各模型依赖。先安装匹配 CUDA 11.8 的 PyTorch 2.5.1 / torchvision 0.20.1,再安装其余依赖和 CUDA 扩展;模型环境可以不同,图像评价子进程保持一致。训练日志中的训练集损失/PSNR 仅用于优化诊断,不是测试集 benchmark 分数。 diff --git a/codes/reconstruction/FlyingWithPhotons/__pycache__/train_ours.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/__pycache__/train_ours.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..899a0fbd1a009aef2a993bb86f5846f1cd5a9e52 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/__pycache__/train_ours.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/__pycache__/utils.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98ef83d97fc73de1f6e7a787367810a4e0e9ce9c Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/__pycache__/utils.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/configs/eval.ini b/codes/reconstruction/FlyingWithPhotons/configs/eval.ini new file mode 100644 index 0000000000000000000000000000000000000000..ed15935b3fd49de4ff96cd8b125781e4302264db --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/configs/eval.ini @@ -0,0 +1,6 @@ +# STB design_floor1 / 10 views example. See README for configuration origin. +warped = True +t_min_test = 0 +t_max_test = 672 +transforms_path = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views/transforms_test.json" +shared_reference_contract = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/contract.json" diff --git a/codes/reconstruction/FlyingWithPhotons/configs/train.ini b/codes/reconstruction/FlyingWithPhotons/configs/train.ini new file mode 100644 index 0000000000000000000000000000000000000000..db250aaa47b992a10fb6f83850f899d493734535 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/configs/train.ini @@ -0,0 +1,55 @@ +# STB design_floor1 / 10 views example. See README for configuration origin. +exp_name = "design_floor1_10views" +dataset_scale = 1000 +meas_peak_min = 20 +img_scale = 100 +data_root = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views" +measurement_root = "/work/runrong/dataset/paper_data/design_floor1" +version = captured +exposure_time = 0.11242217175 +n_bins = 672 +t_min = 0 +t_max = 672 +thold_warmup = 20000 +gamma = 2 +aabb = "[-30.723363, -32.531209, -1.819858, 30.377352, 12.024207, 9.260004]" +depth_global_offset_bins = 17 +depth_offset_valid_max = 10.0 +img_height = 192 +img_width = 256 +img_height_test = 192 +img_width_test = 256 +device = cuda:0 +prop_delay = "True" +view_time_align = "True" +view_time_align_quantile = 0.7 +view_time_align_target_bin = -1 +view_time_align_max_abs_bins = 96 +streaming = False +summary = "True" +outpath = "./results" +steps_till_checkpoint = 10000 +summary_freq = 10000 +max_steps = 150010 +target_sample_batch_size = 262054 +seed = 42 +pixels_to_plot = ["(40, 60)", "(60, 55)", "(30, 55)"] +hardware_shift = "True" +hardware_shift_downsample = 8 +hardware_shift_max_abs_bins = 12 +intrinsics_path = "/work/runrong/dataset/intrinsics.npy" +alpha_thre = 0 +lr = 0.001 +weight_decay = 1e-6 +render_step_size = 5e-2 +cone_angle = 0 +near_plane = 0.0 +far_plane = 33 +init_batch_size = 32 +occ_thre = 0.001 +grid_resolution = 256 +grid_nlvl = 2 +img_shape = 256 +img_shape_test = 256 +final = True +depth_offset_map = "/work/runrong/dataset/paper1_data/offset.txt" diff --git a/codes/reconstruction/FlyingWithPhotons/eval.py b/codes/reconstruction/FlyingWithPhotons/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..156428c137ff4a40e071acd2dbb76990a15b8cca --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/eval.py @@ -0,0 +1,5 @@ +"""The only public evaluation entry: render predictions or score saved histograms.""" +from evaluation.cli import main + +if __name__ == "__main__": + main() diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__init__.py b/codes/reconstruction/FlyingWithPhotons/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4587915b0d7bc01640496b06530c1fa02f2321b0 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/__init__.py @@ -0,0 +1,4 @@ +"""Common count-domain transient evaluation, independent of model training units.""" +PROTOCOL = 'shared_transient_counts_v4_20261016' +TRANSIENT_KEYS = ('histogram_psnr', 'histogram_mse_counts', 'histogram_mae_counts', + 'depth_l1_m', 'transient_iou') diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10b9bbd7916f28b1d3963d795c1c8ee733a5286f Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/arguments.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acf07ad9af829f6c8c556a6e698a7b5202cb4a2f Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/arguments.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/cli.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f82b8a852eb0e9f3389a319790e5f5ea163635bf Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/cli.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/core.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e334118d4071d0c9a42e9774aa6ef915b1938cc9 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/core.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/evaluator.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaef5aeba1f86ec122ecabd3112acf3b4521d75b Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/evaluator.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/image_metrics.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/image_metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9347ca553c9dd3d868ecb3c874588f177157b9c9 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/image_metrics.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/io.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f858c30c35daefb33646bca66139beb3eae736f Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/io.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/renderer.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/renderer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..174db4c0e330455d351542fb3bb211e8be0bfd2c Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/renderer.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/units.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/units.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c6a8470978fccd53426755f712727678a7a2686 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/units.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/worker.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2bc2cf39823b5e6a1b5e68e37a5eb14eb3214ac Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/evaluation/__pycache__/worker.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/arguments.py b/codes/reconstruction/FlyingWithPhotons/evaluation/arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..0e921de6ed4dfda102180de3139c03b853bc09f1 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/arguments.py @@ -0,0 +1,64 @@ +"""Model rendering options; all scoring options are fixed by the reference contract.""" +import ast +import configargparse +from utils import str2bool, load_args + +def load_eval_args(): + parser = configargparse.ArgumentParser() + parser.add_argument("--output", "--shared-output-dir", "--shared_output_dir", dest="shared_output_dir", default=None, + help="Fresh output directory for unified V4 metrics.") + parser.add_argument( + "--shared-reference-contract", "--shared_reference_contract", + dest="shared_reference_contract", default=None, + help="Scene-bound shared reference contract. Required for a scene without a verified default.", + ) + parser.add('--config', '-tc', '--test_config', dest='test_config', + is_config_file=True, + default=None, + help='Test config path.' + ) + parser.add_argument( + "--transforms_path", + type=str, + default="", + help="Path to evaluation transforms file.", + ) + parser.add_argument( + "--checkpoint_dir", + type=str, + default="/", + help="Directory of the checkpoint.", + ) + parser.add_argument( + "--warped", + type=str2bool, + default="true", + help="Render warped or unwarped transients.", + ) + parser.add_argument( + "--t_min_test", + type=int, + default=200, + help="Render min bin number.", + ) + parser.add_argument( + "--t_max_test", + type=int, + default=700, + help="Render max bin number.", + ) + parser.add_argument( + "--unwarp_method", + type=str, + default="depth", + help="Method to perform unwarping.", + ) + parser.add_argument( + "--step", + type=int, + default=80000, + help="Which step to evaluate.", + ) + parser.add_argument("--save-predictions", action="store_true", help="Save unmodified encoded histograms for re-scoring") + args = load_args(eval=True, parser=parser) + return args diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/cli.py b/codes/reconstruction/FlyingWithPhotons/evaluation/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..75f1ced0c673a449a2511fb744c102c7384cdaab --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/cli.py @@ -0,0 +1,54 @@ +"""One entry point and one protocol, for all three methods.""" +import argparse +import json +import sys +from pathlib import Path + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', choices=('render', 'saved'), + help='render a checkpoint, or score unmodified saved histograms') + if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'): + parser.print_help() + return + mode = parser.parse_args(sys.argv[1:2]).source + sys.argv = [sys.argv[0]] + sys.argv[2:] + from . import renderer + if mode == 'render': + return renderer.main() + from .evaluator import EvaluationRun + from .io import load_histogram, write_json, sha256 + p = argparse.ArgumentParser(description='Score saved histograms with the same V4 evaluator as render.') + p.add_argument('--prediction-dir', required=True) + p.add_argument('--prediction-pattern', default='{view}_transient_array.npy') + p.add_argument('--prediction-scale', type=float, required=True, + help='ACTUAL TRAINING normalization; 1 only for full-count exports') + p.add_argument('--prediction-gamma', type=float, default=1.) + p.add_argument('--prediction-bin-width-s', type=float, required=True) + p.add_argument('--prediction-manifest', required=True, + help='Actual rendered frames and poses, in prediction-file order') + p.add_argument('--shared-reference-contract', required=True) + p.add_argument('--output', required=True) + p.add_argument('--device', default='cpu') + a = p.parse_args() + a.bin_width_s_loader = a.prediction_bin_width_s + a.n_bins = json.loads(Path(a.shared_reference_contract).read_text())['n_bins'] + manifest = json.loads(Path(a.prediction_manifest).read_text()) + if (Path(a.output)/'prediction_manifest.json').resolve() == Path(a.prediction_manifest).resolve(): + raise ValueError('Use a separate output directory to preserve the source manifest') + # Generated manifests are binding; do not silently override their physical units. + for key, actual in [('prediction_scale', a.prediction_scale), + ('prediction_gamma', a.prediction_gamma), + ('bin_width_s', a.prediction_bin_width_s)]: + if key in manifest and float(manifest[key]) != actual: + raise ValueError('Prediction manifest disagrees with '+key) + frames = manifest['frames'] + run = EvaluationRun(renderer.PROJECT, a, a.output, frames, a.prediction_scale, + a.prediction_gamma, rendering=manifest.get('rendering')) + run.evaluator.metadata.update(prediction_manifest=str(Path(a.prediction_manifest).resolve()), + prediction_manifest_sha256=sha256(a.prediction_manifest)) + write_json(run.evaluator.output/'evaluation_protocol.json', run.evaluator.metadata) + for i, frame in enumerate(frames): + path = Path(a.prediction_dir)/a.prediction_pattern.format(view=i, stem=Path(frame['file_path']).stem) + run.score(load_histogram(path), i) + print(run.finish()) diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/core.py b/codes/reconstruction/FlyingWithPhotons/evaluation/core.py new file mode 100644 index 0000000000000000000000000000000000000000..27d91f197d2e6648591d1ad87e1ff28c6d8e4b8e --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/core.py @@ -0,0 +1,81 @@ +"""Pure NumPy scoring. No data-dependent exposure fitting or upper clipping.""" +import numpy as np + +C = 299792458.0 + +def positive(x, name): + x = float(x) + if not np.isfinite(x) or x <= 0: + raise ValueError(name + ' must be finite and positive') + return x + +def histogram(x): + if hasattr(x, 'detach'): + x = x.detach().cpu().numpy() + x = np.asarray(x) + if x.ndim == 3: + x = x[..., None] + if x.ndim != 4 or x.shape[-1] not in (1, 3) or min(x.shape) <= 0: + raise ValueError('Expected H x W x T x (1 or 3) histogram') + return x + +def decode(x, scale, gamma=1.0): + """Inverse training encoding, applied per bin before any summation.""" + scale, gamma = positive(scale, 'training scale'), positive(gamma, 'gamma') + x = np.asarray(x, dtype=np.float64) + if not np.isfinite(x).all() or np.any(x < 0): + raise ValueError('Histogram must be finite and nonnegative, even outside the mask') + y = np.power(x, gamma) * scale if gamma != 1.0 else x * scale + if not np.isfinite(y).all(): + raise ValueError('Count decoding overflow') + return y + +def score_histograms(prediction, reference, mask, *, prediction_scale, + reference_scale, histogram_peak, bin_width_s, + prediction_gamma=1.0, row_chunk=4): + """MSE over all bins/channels of GT-valid pixels, using a frozen train peak. + + A one-channel capture is broadcast to RGB when necessary. All RGB channels + enter MSE; peak depth uses their arithmetic mean. Chunking bounds RAM use. + """ + pred, ref = histogram(prediction), histogram(reference) + if pred.shape[:3] != ref.shape[:3]: + raise ValueError('Prediction/reference pixel grid or temporal window differs') + mask = np.asarray(mask) + if mask.shape != pred.shape[:2] or not np.isin(mask, [0, 1]).all(): + raise ValueError('Expected binary HW reference-only mask') + mask = mask.astype(bool) + if not mask.any(): + raise ValueError('No valid reference pixels') + peak = positive(histogram_peak, 'fixed histogram peak') + dt = positive(bin_width_s, 'physical bin width') + if int(row_chunk) != row_chunk or row_chunk < 1: + raise ValueError('row_chunk must be a positive integer') + h, w, t = pred.shape[:3] + channels = max(pred.shape[-1], ref.shape[-1]) + ip, ig = np.zeros((h,w,3)), np.zeros((h,w,3)) + dp, dg = np.zeros((h,w)), np.zeros((h,w)) + squared = absolute = intersection = union = 0.0 + for start in range(0,h,int(row_chunk)): + sl = slice(start,min(h,start+int(row_chunk))) + p = decode(pred[sl], prediction_scale, prediction_gamma) + g = decode(ref[sl], reference_scale) + ip[sl] = np.broadcast_to(p.sum(axis=-2), (len(p),w,3)) + ig[sl] = np.broadcast_to(g.sum(axis=-2), (len(g),w,3)) + dp[sl] = p.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0 + dg[sl] = g.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0 + a,b = np.broadcast_arrays(p[mask[sl]], g[mask[sl]]) + error = a-b + squared += np.square(error).sum(dtype=np.float64) + absolute += np.abs(error).sum(dtype=np.float64) + intersection += np.minimum(a,b).sum(dtype=np.float64) + union += np.maximum(a,b).sum(dtype=np.float64) + count = int(mask.sum()) * t * channels + mse = squared/count + psnr = float(20*np.log10(peak)-10*np.log10(mse)) if mse>0 else float('inf') + scores = dict(histogram_psnr=psnr, histogram_mse_counts=float(mse), + histogram_mae_counts=float(absolute/count), + depth_l1_m=float(np.abs(dp[mask]-dg[mask]).mean()), + transient_iou=float(intersection/union) if union>0 else 1.0) + return scores, dict(prediction=ip, reference=ig, mask=mask, + prediction_depth=dp, reference_depth=dg) diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/evaluator.py b/codes/reconstruction/FlyingWithPhotons/evaluation/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..ed102f188ebd8079a33eeca554a87db7a6ce9278 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/evaluator.py @@ -0,0 +1,161 @@ +"""Frame-bound common scoring adapter for all three native and saved entrances.""" +import json +import operator +import os +from pathlib import Path +import subprocess +import sys +import numpy as np +from . import PROTOCOL +from .core import C,positive,score_histograms +from .io import sha256,verified,load_histogram,write_json + +BASE=Path(__file__).resolve().parent.parent +PYTHON=os.environ.get('STB_METRICS_PYTHON') or '/work/runrong/.conda/envs/transientangelo/bin/python' + +def resolve_contract(args): + explicit=getattr(args,'shared_reference_contract',None) or os.environ.get('SHARED_REFERENCE_CONTRACT') + if explicit:return Path(explicit).resolve() + measurement=getattr(args,'measurement_root',None) + matches=[] + for p in Path(os.environ.get('STB_REFERENCE_ROOT', str(BASE/'references'))).glob('*/contract.json'): + d=json.loads(p.read_text()) + if measurement and Path(d['measurement_root']).resolve()==Path(measurement).resolve():matches.append(p) + if len(matches)!=1: + raise ValueError('A prepared V4 canonical reference is required. Pass --shared-reference-contract ' + 'with the matching contract.json; no legacy/test-scale fallback.') + return matches[0] + +class UnifiedEvaluator: + def __init__(self,project,args,output_dir,frames): + if project not in ('trnerf','transientangelo','FlyingWithPhotons'):raise ValueError('Unknown project') + if not Path(PYTHON).is_file():raise FileNotFoundError('Set STB_METRICS_PYTHON to the common evaluation Python: '+str(PYTHON)) + self.project=project;self.path=resolve_contract(args);self.digest=sha256(self.path) + self.contract=c=json.loads(self.path.read_text()) + if c.get('protocol')!=PROTOCOL: + raise ValueError('V4 needs a histogram reference contract, not an intensity-only V2/V3 contract') + self.peak=positive(c['histogram_peak'],'fixed training histogram peak') + self.display_scale=positive(c['display_scale'],'fixed training display scale') + dt=positive(c['bin_width_s'],'reference bin width') + if not c.get('training_frames') or not c.get('scale_policy') or c.get('time_start')!=0: + raise ValueError('Missing frozen training-scale provenance or invalid time origin') + for k in ('height','width','n_bins'): + if type(c[k]) is not int or c[k]<=0:raise ValueError('Invalid '+k) + measurement=getattr(args,'measurement_root',None) + if measurement and Path(measurement).resolve()!=Path(c['measurement_root']).resolve(): + raise ValueError('Measurement scene does not match reference') + intrinsics=getattr(args,'intrinsics',None) or getattr(args,'intrinsics_path',None) + if intrinsics and sha256(intrinsics)!=c['intrinsics_sha256']:raise ValueError('Calibration mismatch') + actual=getattr(args,'bin_width_s_loader',None) + if actual is None:actual=getattr(args,'bin_width_s',None) + if actual is None and hasattr(args,'exposure_time'): + actual=float(args.exposure_time)/(C/2 if project=='FlyingWithPhotons' else C) + if actual is None or not np.isclose(float(actual),dt,rtol=1e-6,atol=0):raise ValueError('Physical bin width mismatch/missing') + # FWP uses one-way range/bin; verify it even when a loader override exists. + if project=='FlyingWithPhotons' and hasattr(args,'exposure_time'): + if not np.isclose(float(args.exposure_time)/(C/2),dt,rtol=1e-6,atol=0):raise ValueError('FWP exposure_time mismatch') + for name,want in [('n_bins',c['n_bins']),('t_min_test',0),('t_max_test',c['n_bins']), + ('img_height_test',c['height']),('img_width_test',c['width'])]: + actual=getattr(args,name,None) + if actual is not None and int(actual)!=want:raise ValueError('Common window/grid mismatch: '+name) + frames=list(frames);records={Path(f['file_path']).stem:f for f in c['frames']} + ids=[Path(f['file_path']).stem for f in frames] + if (not frames or len(records)!=len(c['frames']) or len(set(ids))!=len(ids) + or set(ids)!=set(records)): + raise ValueError('Evaluation must declare the complete, unique canonical test frame set') + self.frames=[] + for f,key in zip(frames,ids): + r=records[key];pose=np.asarray(f['transform_matrix']);rp=np.asarray(r['transform_matrix']) + 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): + raise ValueError('Test frame pose differs from canonical reference: '+key) + self.frames.append(r) + self.output=Path(output_dir)/'unified_metrics' + if (self.output/'evaluation_protocol.json').exists(): + raise FileExistsError('Use a fresh V4 output directory; existing scores are not overwritten') + self.output.mkdir(parents=True,exist_ok=True);self.rows=[] + self.device=os.environ.get('STB_METRICS_DEVICE') or str(getattr(args,'device','cpu')) + self.metadata=dict(protocol=PROTOCOL,project=project,reference_contract=str(self.path), + reference_sha256=self.digest,scene_id=c['scene_id'],histogram_peak=self.peak, + display_scale=self.display_scale,mask_policy=c['mask_policy'],n_bins=c['n_bins'],bin_width_s=dt, + frames=[f['file_path'] for f in self.frames], + histogram_psnr='20log10(frozen train peak)-10log10(mean squared count error); all valid bins/channels; no upper clipping/gamma', + depth='argmax of channel-mean full-count histogram; bin_index*c*dt/2, metres; canonical GT mask', + aggregation='arithmetic mean of per-view metrics, only complete frame sets receive an aggregate', + training_scale_policy='explicit actual training scale; never test maximum', + 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')}, + image_code_sha256=sha256(Path(__file__).with_name('image_metrics.py'))) + from .image_metrics import PROTOCOL_INFO + self.metadata['image_metric_definition']=dict(PROTOCOL_INFO,scale=self.display_scale) + self.metadata['checkpoint_dir']=getattr(args,'checkpoint_dir',None) + self.metadata['checkpoint_step']=getattr(args,'step',None) + 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.' + write_json(self.output/'evaluation_protocol.json',self.metadata) + + def score(self,prediction_histogram,frame_index,prediction_scale,prediction_gamma=1.0): + if isinstance(frame_index,(bool,np.bool_)):raise IndexError('Boolean frame index') + i=operator.index(frame_index) + if i<0 or i>=len(self.frames):raise IndexError(i) + if sha256(self.path)!=self.digest:raise ValueError('Reference contract changed during evaluation') + f=self.frames[i];c=self.contract + hp=verified(self.path.parent/f['histogram_path'],f['histogram_sha256']) + mp=verified(self.path.parent/f['mask_path'],f['mask_sha256']) + reference=load_histogram(hp);mask=np.load(mp,allow_pickle=False) + if reference.shape[:3]!=(c['height'],c['width'],c['n_bins']):raise ValueError('Reference shape differs from contract') + scores,arrays=score_histograms(prediction_histogram,reference,mask, + prediction_scale=prediction_scale,reference_scale=f['reference_scale'], + histogram_peak=self.peak,bin_width_s=c['bin_width_s'],prediction_gamma=prediction_gamma) + 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' + np.savez_compressed(inp,**arrays) + env=dict(os.environ);env['PYTHONPATH']=str(BASE)+os.pathsep+env.get('PYTHONPATH','') + if self.device=='cpu':env['CUDA_VISIBLE_DEVICES']='' + proc=subprocess.run([PYTHON,'-m','evaluation.worker', + '--input',str(inp),'--output',str(result),'--display',str(display), + '--scale',str(self.display_scale),'--device',self.device],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True) + if proc.returncode:raise RuntimeError('Common image scorer failed: '+proc.stdout[-5000:]) + scores.update(json.loads(result.read_text())) + row=dict(view=i,frame=f['file_path'],prediction_scale=float(prediction_scale), + prediction_gamma=float(prediction_gamma),valid_pixels=int(mask.sum()),**scores) + self.rows=[r for r in self.rows if r['view']!=i]+[row];self.rows.sort(key=lambda r:r['view']) + write_json(self.output/'metrics_per_view.json',self.rows) + complete=len(self.rows)==len(self.frames) + write_json(self.output/'progress.json',dict(completed_views=len(self.rows),expected_views=len(self.frames),complete=complete)) + if complete: + write_json(self.output/'metrics_aggregate.json',{k:float(np.mean([r[k] for r in self.rows])) for k in scores}) + with np.load(display) as d:p,g=d['prediction'],d['reference'] + return dict(scores,psnr=scores['image_psnr'],prediction_display=p,reference_display=g, + reference_histogram=reference,reference_scale=f['reference_scale'], + prediction_intensity_counts=arrays['prediction'],reference_intensity_counts=arrays['reference'], + mask=arrays['mask'],prediction_depth=arrays['prediction_depth'],reference_depth=arrays['reference_depth'],protocol=PROTOCOL) + +class EvaluationRun: + """The same scoring/output path for native rendering and saved predictions.""" + def __init__(self, project, args, output_dir, frames, scale, gamma=1.0, + rendering=None, save_predictions=False): + self.scale = positive(scale, 'actual training scale') + self.gamma = positive(gamma, 'actual training gamma') + self.evaluator = UnifiedEvaluator(project, args, output_dir, frames) + self.output = Path(output_dir) + self.save_predictions = save_predictions + manifest = dict(frames=frames, prediction_scale=self.scale, + prediction_gamma=self.gamma, + bin_width_s=self.evaluator.contract['bin_width_s'], + rendering=rendering or {'source': 'saved histograms; see source manifest'}) + write_json(self.output/'prediction_manifest.json', manifest) + self.evaluator.metadata.update(prediction_scale=self.scale, prediction_gamma=self.gamma, + rendering=manifest['rendering']) + write_json(self.evaluator.output/'evaluation_protocol.json', self.evaluator.metadata) + + def score(self, prediction, index): + if self.save_predictions: + if hasattr(prediction, 'detach'): + prediction = prediction.detach().cpu().numpy() + np.save(self.output/f'{index}_transient_array.npy', prediction) + scores = self.evaluator.score(prediction, index, self.scale, self.gamma) + print(self.evaluator.project, index, {k: scores[k] for k in + ('histogram_psnr', 'image_psnr', 'ssim', 'lpips', 'depth_l1_m')}, flush=True) + return scores + + def finish(self): + if len(self.evaluator.rows) != len(self.evaluator.frames): + raise ValueError('Incomplete canonical test set: no complete evaluation result') + return self.evaluator.output/'metrics_aggregate.json' diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/image_metrics.py b/codes/reconstruction/FlyingWithPhotons/evaluation/image_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..21f88ff92b2aefd2895c10990710d0d069d76b61 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/image_metrics.py @@ -0,0 +1,114 @@ +"""Shared TA-style display metrics, with uncensored linear-count diagnostics. + +Not an exact upstream reproduction: all projects use one reference-only mask, +explicit SSIM settings, a frozen training scale, and FP32 LPIPS. +""" +import numpy as np +import torch +import lpips +from contextlib import contextmanager +from scipy.ndimage import minimum_filter +from skimage.metrics import structural_similarity + +PROTOCOL = 'shared_ta_display_psnr_ssim_lpips_v3_20260929' +PRIMARY_KEYS = ('psnr', 'ssim', 'lpips') +AUXILIARY_KEYS = ('linear_psnr', 'prediction_above_scale_percent', + 'reference_above_scale_percent', 'max_prediction_over_scale', + 'max_reference_over_scale') +SCORE_KEYS = PRIMARY_KEYS + AUXILIARY_KEYS +PROTOCOL_INFO = dict( + protocol=PROTOCOL, + scale_policy="explicit frozen per-scene record; no numeric scene fallback", + metric_labels=dict(psnr='PSNR-display', ssim='SSIM-display', lpips='LPIPS-display', + linear_psnr='PSNR-linear (auxiliary)'), + prediction_display='clip(I/D,0,1) ** (1/2.2)', + reference_display='(I/D) ** (1/2.2), no upper clipping', + psnr='-10log10 valid-reference-pixel/RGB display MSE; fixed peak 1', + ssim='RGB, data_range=1, uniform 7x7, sample covariance, complete reference-valid windows', + lpips='same display RGB, common invalid region black, [-1,1] transform, VGG0.1 FP32', + linear_psnr='-10log10 mean(((prediction-reference)/D)^2); no upper clipping or gamma', + above_scale_percent='percentage of reference-valid pixels with ANY RGB channel > D', + aggregation='arithmetic mean of per-view metrics; saturation percentages are mean per-view percentages', + prediction_upper_clip=True, reference_upper_clip=False, + count_domain_upper_clip=False, fitted_test_exposure=False, + preview_png='clip display arrays only for uint8 export; floating scoring arrays are retained', + upstream_exact=False, +) + +@contextmanager +def scoring_precision(): + previous = (torch.get_float32_matmul_precision(), + torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32) + try: + torch.set_float32_matmul_precision('highest') + torch.backends.cuda.matmul.allow_tf32=False + torch.backends.cudnn.allow_tf32=False + yield + finally: + torch.set_float32_matmul_precision(previous[0]) + torch.backends.cuda.matmul.allow_tf32=previous[1] + torch.backends.cudnn.allow_tf32=previous[2] + +def tone_map(image, scale, *, prediction): + """Role is explicit: upstream prediction and reference transforms differ.""" + x=np.asarray(image,dtype=np.float64) + if not np.isfinite(scale) or scale <= 0: + raise ValueError('positive fixed scale required') + if not np.isfinite(x).all() or np.any(x<0): + raise ValueError('Expected finite nonnegative counts; no silent masking/clipping of invalid inputs') + x=x/scale + if prediction: + x=np.clip(x,0.,1.) + return x**(1/2.2) + +def display_pair(prediction, reference, scale, mask=None): + p=tone_map(prediction,scale,prediction=True) + g=tone_map(reference,scale,prediction=False) + if mask is not None: + mask=np.asarray(mask,bool) + p[~mask]=0;g[~mask]=0 + return p,g + +def preview_uint8(display_image): + """PNG encoding only. Never pass this output back to a metric.""" + return np.rint(np.clip(display_image,0.,1.)*255.).astype(np.uint8) + +def _psnr(mse): + return float(-10*np.log10(mse)) if mse>0 else float('inf') + +class ImageMetrics: + def __init__(self, scale, device='cuda'): + if not np.isfinite(scale) or scale<=0: + raise ValueError('positive fixed scale required') + self.scale=float(scale);self.device=str(device) + self.net=lpips.LPIPS(net='vgg',version='0.1').float().to(device).eval() + + def __call__(self, prediction, reference, mask): + pred=np.asarray(prediction,np.float64);ref=np.asarray(reference,np.float64) + mask=np.asarray(mask,dtype=bool) + if pred.shape!=ref.shape or pred.ndim!=3 or pred.shape[-1]!=3 or mask.shape!=pred.shape[:2]: + raise ValueError('Expected matching HWC3 images and HW reference mask') + if not mask.any(): + raise ValueError('No reference-valid pixels') + x,y=display_pair(pred,ref,self.scale) + psnr=_psnr(np.mean((x[mask]-y[mask])**2,dtype=np.float64)) + linear_psnr=_psnr(np.mean(((pred[mask]-ref[mask])/self.scale)**2,dtype=np.float64)) + windows=minimum_filter(mask.astype(np.uint8),size=7,mode='constant',cval=0).astype(bool) + if not windows.any(): + raise ValueError('No complete 7x7 reference-valid SSIM windows') + _,ssim_map=structural_similarity(y,x,data_range=1.,channel_axis=-1, + win_size=7,gaussian_weights=False,use_sample_covariance=True,full=True) + ssim=float(ssim_map[windows].mean()) + x[~mask]=0;y[~mask]=0 + tensor=lambda z: torch.from_numpy(z.astype(np.float32)).permute(2,0,1)[None].to(self.device)*2-1 + with scoring_precision(),torch.no_grad(),torch.autocast(device_type=self.device.split(':')[0],enabled=False): + score=self.net(tensor(x),tensor(y)) + return dict(psnr=psnr,ssim=ssim,lpips=float(score.item()),linear_psnr=linear_psnr, + prediction_above_scale_percent=float(np.any(pred[mask]>self.scale,axis=-1).mean()*100), + reference_above_scale_percent=float(np.any(ref[mask]>self.scale,axis=-1).mean()*100), + max_prediction_over_scale=float(pred[mask].max()/self.scale), + max_reference_over_scale=float(ref[mask].max()/self.scale)) + +def aggregate(rows): + if not rows:raise ValueError('Cannot aggregate empty results') + return {k:float(np.mean([r[k] for r in rows],dtype=np.float64)) for k in SCORE_KEYS} diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/io.py b/codes/reconstruction/FlyingWithPhotons/evaluation/io.py new file mode 100644 index 0000000000000000000000000000000000000000..7e60dcd7d8efcae23e61ced00e87642448edd9f3 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/io.py @@ -0,0 +1,30 @@ +import hashlib +import json +import os +from pathlib import Path +import numpy as np + +def sha256(path): + h=hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block) + return h.hexdigest() + +def write_json(path, data): + path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) + tmp=path.with_name(path.name+'.%d.tmp'%os.getpid()) + tmp.write_text(json.dumps(data,indent=2,allow_nan=True));tmp.replace(path) + +def verified(path, digest): + path=Path(path) + if not path.is_file() or sha256(path)!=digest: + raise ValueError('Frozen input missing or changed: '+str(path)) + return path + +def load_histogram(path): + path=Path(path) + if path.suffix=='.npy':return np.load(path,mmap_mode='r',allow_pickle=False) + if path.suffix in ('.h5','.hdf5'): + import h5py + with h5py.File(path,'r') as f:return np.asarray(f['data']) + raise ValueError('Use unclipped .npy or .h5 histogram exports: '+str(path)) diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/renderer.py b/codes/reconstruction/FlyingWithPhotons/evaluation/renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..a54c1f2bbe58599a3a2783fd6ef2daa4e7a1f2a7 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/renderer.py @@ -0,0 +1,100 @@ +"""FlyingWithPhotons model loading and rendering; no method-specific scoring.""" +import json +from pathlib import Path + +PROJECT = 'FlyingWithPhotons' + +def forward_average_occgrid( + forward_repeats, + radiance_field, + estimator, + rays, + args, + color_channels, +): + # Match captured_neus.py: average repeated forward passes first, then evaluate metrics once. + rgb_sum = None + acc_sum = None + depth_sum = None + + for rep_idx in range(forward_repeats): + if forward_repeats > 1: + print(f"[FORWARD AVG] rep {rep_idx + 1}/{forward_repeats}") + + rgb_rep, acc_rep, depth_rep, _ = render_image_with_occgrid_test( + 1024, + radiance_field, + estimator, + rays, + args=args, + near_plane=args.near_plane, + far_plane=args.far_plane, + render_step_size=args.render_step_size, + cone_angle=args.cone_angle, + alpha_thre=0.01, + n_output_dim=args.n_bins * color_channels, + prop_delay=args.prop_delay, + unwarp=not args.warped, + ) + + if rgb_sum is None: + rgb_sum = torch.zeros_like(rgb_rep) + acc_sum = torch.zeros_like(acc_rep) + depth_sum = torch.zeros_like(depth_rep) + + rgb_sum += rgb_rep + acc_sum += acc_rep + depth_sum += depth_rep + + rgb = rgb_sum / float(forward_repeats) + acc = acc_sum / float(forward_repeats) + depth = depth_sum / float(forward_repeats) + return rgb, acc, depth + + +def main(): + global torch, render_image_with_occgrid_test + import torch + import torch.nn.functional as F + from nerfacc import OccGridEstimator + from radiance_fields.ngp import NGPRadianceField + from loaders.utils import Rays + from utils import render_image_with_occgrid_test + from .arguments import load_eval_args + from .units import fwp_training_units + from .evaluator import EvaluationRun + + args = load_eval_args() + if args.version != 'captured' or int(getattr(args, 'eval_repeats', 30)) != 30: + raise ValueError('The captured benchmark requires 30 forward repetitions') + scale, gamma = fwp_training_units(args) + frames = json.loads(Path(args.transforms_path).read_text())['frames'] + output = args.shared_output_dir or str(Path(args.checkpoint_dir)/f'evaluation_step{args.step}') + run = EvaluationRun(PROJECT, args, output, frames, scale, gamma, + rendering=dict(forward_repeats=30, sampling='native same pixel rays, average forward outputs', + warped=args.warped), save_predictions=args.save_predictions) + device = args.device + aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device) + h, w = args.img_height_test, args.img_width_test + sx, sy = w/args.img_width, h/args.img_height + K = torch.tensor([[args.fx*sx,0,args.cx*sx],[0,args.fy*sy,args.cy*sy],[0,0,1]], dtype=torch.float32) + estimator = OccGridEstimator(roi_aabb=aabb, resolution=args.grid_resolution, + levels=args.grid_nlvl).to(device) + model = NGPRadianceField(aabb=estimator.aabbs[-1], radiance_activation=torch.nn.Sigmoid(), + use_viewdirs=True, args=args).to(device) + model.load_state_dict(torch.load(Path(args.checkpoint_dir)/f'radiance_field_{args.step:04d}.pth', map_location=device)) + estimator.load_state_dict(torch.load(Path(args.checkpoint_dir)/f'occupancy_grid_{args.step:04d}.pth', map_location=device)) + # Preserve the original renderer's mode and same-ray averaging behavior. + with torch.no_grad(): + for i, frame in enumerate(frames): + c2w = torch.tensor(frame['transform_matrix']).to(device) + yy, xx = torch.meshgrid(torch.arange(h,device=device), torch.arange(w,device=device), indexing='ij') + camera_dirs = F.pad(torch.stack([(xx-K[0,2]+0.5)/K[0,0], + (yy-K[1,2]+0.5)/K[1,1]], dim=-1), (0,1), value=1.) + directions = (camera_dirs[:,:,None,:]*c2w[:3,:3]).sum(dim=-1) + origins = torch.broadcast_to(c2w[:3,-1], directions.shape) + viewdirs = directions/torch.linalg.norm(directions,dim=-1,keepdims=True) + rays = Rays(origins=origins.reshape(h,w,3), viewdirs=viewdirs.reshape(h,w,3)) + rgb, _, _ = forward_average_occgrid(30, model, estimator, rays, args, 1) + run.score(rgb.reshape(h,w,-1,1).cpu().numpy(), i) + print(run.finish()) diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/units.py b/codes/reconstruction/FlyingWithPhotons/evaluation/units.py new file mode 100644 index 0000000000000000000000000000000000000000..00b727d7a5b2f38cb6231a55ea00deb768afdee8 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/units.py @@ -0,0 +1,84 @@ +import math +"""Actual training units; a test-split maximum is never a fallback.""" +import ast +import json +from pathlib import Path +from types import SimpleNamespace +from .core import positive +from .io import write_json,sha256 + +def record_training_units(directory,scale,gamma,train_poses,project,measurement_root=None,intrinsics=None): + path=Path(directory)/'image_metric_normalization.json' + data=dict(training_scale=positive(scale,'training scale'),training_gamma=positive(gamma,'training gamma'), + project=project,train_poses=str(Path(train_poses).resolve()),train_poses_sha256=sha256(train_poses), + measurement_root=measurement_root,intrinsics=intrinsics, + intrinsics_sha256=sha256(intrinsics) if intrinsics else None, + source='actual training loader/configuration; never computed from test data') + if path.exists(): + old=json.loads(path.read_text()) + if (float(old['training_scale'])!=data['training_scale'] or + float(old.get('training_gamma',1.0))!=data['training_gamma']): + raise ValueError('Checkpoint directory already records different training units') + for key in ('train_poses_sha256','intrinsics_sha256','measurement_root'): + if key in old and old[key]!=data[key]: + raise ValueError('Checkpoint training provenance differs: '+key) + return + write_json(path,data) + +def fwp_training_units(args): + root=Path(args.checkpoint_dir);metadata=root/'image_metric_normalization.json' + if metadata.exists(): + record=json.loads(metadata.read_text()) + scale,gamma=record['training_scale'],record['training_gamma'] + else: + params=root/'params_full.txt' + if not params.is_file():raise ValueError('FWP requires saved training params_full.txt or normalization metadata') + values={} + for line in params.read_text().splitlines(): + if '=' not in line or line.lstrip().startswith('#'):continue + k,v=line.split('=',1) + if k.strip() in ('dataset_scale','gamma'):values[k.strip()]=ast.literal_eval(v.strip()) + scale,gamma=values['dataset_scale'],values['gamma'] + scale,gamma=positive(scale,'training dataset_scale'),positive(gamma,'training gamma') + if float(args.dataset_scale)!=scale or float(args.gamma)!=gamma: + raise ValueError('Evaluation dataset_scale/gamma differs from saved FWP training units') + return scale,gamma + +def scalar(value): + if hasattr(value, 'detach'): + value = value.detach().cpu().item() + value = float(value) + if not math.isfinite(value) or value <= 0: + raise ValueError('A finite positive count scale is required') + return value + +def resolve_prediction_scale(system): + value = system.config.dataset.get('image_metric_training_scale', None) + if hasattr(system, '_image_metric_training_scale'): + if value is not None and scalar(value) != scalar(system._image_metric_training_scale): + raise ValueError('Explicit training scale conflicts with checkpoint metadata') + return scalar(system._image_metric_training_scale), 'training/checkpoint metadata' + if value is not None: + return scalar(value), 'explicit dataset.image_metric_training_scale' + raise ValueError('Missing actual training scale; use checkpoint metadata or set dataset.image_metric_training_scale. Never substitute the test maximum.') + +def tn_training_scale(args): + """Restore model output units; the independently normalized test split is not valid here.""" + explicit = getattr(args, "shared_prediction_scale", None) + path = Path(args.checkpoint_dir) / "image_metric_normalization.json" + recorded = None + if path.is_file(): + recorded = json.loads(path.read_text()).get("training_scale") + if explicit is None and recorded is None: + raise ValueError( + "Shared metrics require the TRAINING histogram normalization. " + "Supply --shared-prediction-scale from the training loader, or create " + + str(path) + " with training_scale and its training-data provenance. " + "The test split maximum must never be substituted." + ) + if explicit is not None and recorded is not None and float(explicit) != float(recorded): + raise ValueError("Explicit prediction scale conflicts with checkpoint normalization metadata") + value = float(recorded if explicit is None else explicit) + if not math.isfinite(value) or value <= 0: + raise ValueError("Training histogram normalization must be finite and positive") + return value diff --git a/codes/reconstruction/FlyingWithPhotons/evaluation/worker.py b/codes/reconstruction/FlyingWithPhotons/evaluation/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..2e99015d8a945dbd42af07654af354978dffcb1f --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/evaluation/worker.py @@ -0,0 +1,21 @@ +"""Run image scoring in the same installed environment for all three methods.""" +import argparse +from pathlib import Path +import numpy as np +from .io import write_json + +def main(): + p=argparse.ArgumentParser() + for k in ('input','output','display'):p.add_argument('--'+k,required=True) + p.add_argument('--scale',required=True,type=float);p.add_argument('--device',default='cpu') + a=p.parse_args() + from .image_metrics import ImageMetrics,display_pair + with np.load(a.input) as d: + pred,ref,mask=d['prediction'],d['reference'],d['mask'].astype(bool) + scores=ImageMetrics(a.scale,a.device)(pred,ref,mask) + scores['image_psnr']=scores.pop('psnr') + x,y=display_pair(pred,ref,a.scale,mask) + np.savez_compressed(a.display,prediction=x,reference=y) + write_json(a.output,scores) + +if __name__=='__main__':main() diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/__init__.py b/codes/reconstruction/FlyingWithPhotons/loaders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27ec6124adcfb12255b5ba2d75fce3cac18a1f3e Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/calibration.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/calibration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91626825d832263c1eb5af7b04862b624154c6cd Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/calibration.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/regular_loader_our.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/regular_loader_our.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9cb18a2fac3672e6bd348057aefdbe380850648 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/regular_loader_our.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/streaming_loader.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/streaming_loader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d4dda2a8534ccf390db5e10426f90cd835d8224 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/streaming_loader.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/utils.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30de75046ffacf236b51bafa480d9c10df6540e3 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/loaders/__pycache__/utils.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/calibration.py b/codes/reconstruction/FlyingWithPhotons/loaders/calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..382f7f180ea4c273c6d5e891fc9eaa8801e048c7 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/loaders/calibration.py @@ -0,0 +1,12 @@ +"""Expand scalar calibration or resize a 2-D map; preserve physical values.""" +import torch +import torch.nn.functional as F + +def shift_map(value, height, width, device): + value=torch.as_tensor(value,dtype=torch.float32,device=device).squeeze() + if value.numel()==1: + return value.reshape(1,1).expand(height,width) + if value.ndim!=2: + raise ValueError('Calibration shift must be scalar or a 2-D map') + if tuple(value.shape)==(height,width):return value + return F.interpolate(value[None,None],size=(height,width),mode='bilinear',align_corners=True)[0,0] diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/regular_loader_our.py b/codes/reconstruction/FlyingWithPhotons/loaders/regular_loader_our.py new file mode 100644 index 0000000000000000000000000000000000000000..8da2163d23dd2545a4fdf55938b7a2d37bb0247f --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/loaders/regular_loader_our.py @@ -0,0 +1,363 @@ +""" +Copyright (c) 2022 Ruilong Li, UC Berkeley. +Modified for captured SPAD data with Pinhole Model & Hardware Offsets. +""" +import json +import os +import re +import numpy as np +import torch +import torch.nn.functional as F +import h5py +import scipy.sparse as sp +from .utils import Rays +import tqdm +import sys +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from utils import compute_transient_valid_mask_torch + +def read_h5(path): + with h5py.File(path, 'r') as f: + frames = np.array(f['data']) + return frames + + +def _load_numpy_coo_npz(path): + pack = np.load(path, allow_pickle=False) + try: + fmt = str(np.asarray(pack["format"]).item()) + if fmt != "coo_numpy": + raise ValueError(f"unsupported npz format tag: {fmt}") + shape = tuple(np.asarray(pack["shape"], dtype=np.int64).tolist()) + row = np.asarray(pack["row"], dtype=np.int64) + col = np.asarray(pack["col"], dtype=np.int64) + data = np.asarray(pack["data"]) + dense = np.zeros(shape, dtype=data.dtype) + np.add.at(dense, (row, col), data) + return dense + finally: + pack.close() + + +def read_npz(path, height, width): + try: + dense_frames = sp.load_npz(path).toarray() + except Exception: + dense_frames = _load_numpy_coo_npz(path) + if dense_frames.ndim == 3: + if dense_frames.shape[:2] != (height, width): + raise ValueError( + f"Measurement shape mismatch for {path}: got {dense_frames.shape[:2]}, " + f"expected {(height, width)}" + ) + return dense_frames.astype(np.float32) + if dense_frames.ndim != 2: + raise ValueError(f"Unsupported sparse measurement shape {dense_frames.shape} in {path}") + if dense_frames.shape[0] == height * width: + return dense_frames.reshape(height, width, dense_frames.shape[1]).astype(np.float32) + if dense_frames.shape[1] == height * width: + return dense_frames.T.reshape(height, width, dense_frames.shape[0]).astype(np.float32) + raise ValueError( + f"Measurement pixel count mismatch for {path}: got {dense_frames.shape}, " + f"expected [H*W, bins] or [bins, H*W] with H*W={height * width}" + ) + + +def resolve_measurement_path(measurement_root, frame_path): + frame_rel = frame_path or "" + frame_name = os.path.basename(frame_rel) + frame_stem, frame_ext = os.path.splitext(frame_name) + + candidates = [] + if frame_rel: + candidates.append(os.path.join(measurement_root, frame_rel)) + if frame_name: + candidates.append(os.path.join(measurement_root, frame_name)) + if frame_stem: + candidates.append(os.path.join(measurement_root, f"{frame_stem}.h5")) + candidates.append(os.path.join(measurement_root, f"{frame_stem}.npz")) + match = re.search(r"(\d+)$", frame_stem) + if match: + frame_idx = int(match.group(1)) + candidates.append(os.path.join(measurement_root, f"transient{frame_idx:03d}.h5")) + candidates.append(os.path.join(measurement_root, f"transient{frame_idx:03d}.npz")) + if frame_ext.lower() in {".h5", ".npz"}: + candidates.insert(0, os.path.join(measurement_root, frame_name)) + + seen = set() + for candidate in candidates: + if candidate in seen: + continue + seen.add(candidate) + if os.path.exists(candidate): + return candidate + + raise FileNotFoundError( + f"Cannot find measurement file for frame '{frame_path}' under '{measurement_root}'. " + f"Tried: {candidates[:6]}" + ) + + +def read_measurement(path, args): + ext = os.path.splitext(path)[1].lower() + if ext == ".h5": + return read_h5(path)[..., :args.n_bins, :3] + if ext == ".npz": + rgba = read_npz(path, args.img_height, args.img_width)[..., :args.n_bins] + return rgba[..., None] + raise ValueError(f"Unsupported measurement file type: {path}") + + +def select_test_frames(root_fp, frames): + train_json = os.path.join(root_fp, "transforms_train.json") + if not os.path.exists(train_json): + return frames + + with open(train_json, "r") as fp: + train_meta = json.load(fp) + + num_train_frames = len(train_meta.get("frames", [])) + if num_train_frames <= 0 or num_train_frames >= len(frames): + return frames + + selected_indices = np.linspace(0, len(frames) - 1, num=num_train_frames, dtype=int) + return [frames[idx] for idx in selected_indices.tolist()] + +def _load_offset_map(path, h, w): + """读取外部的逐像素深度偏移图""" + if path.lower().endswith('.npy'): + arr = np.load(path).astype(np.float32) + else: + arr = np.loadtxt(path, dtype=np.float32) + arr = np.asarray(arr, dtype=np.float32).squeeze() + if arr.size == h * w: + arr = arr.reshape(h, w) + return torch.from_numpy(arr) + +def _load_renderings(root_fp: str, split: str, args): + """Load images from disk with Area Downsampling and Pinhole K Matrix.""" + with open(os.path.join(root_fp, f"transforms_{split}.json"), "r") as fp: + meta = json.load(fp) + + frames = meta["frames"] + if split == "test" and getattr(args, "match_test_to_train_views", True): + frames = select_test_frames(root_fp, frames) + + images = [] + camtoworlds = [] + + for i in tqdm.tqdm(range(len(frames))): + frame = frames[i] + fname = resolve_measurement_path(args.measurement_root, frame.get("file_path", "")) + rgba = read_measurement(fname, args) + camtoworlds.append(frame["transform_matrix"]) + images.append(rgba) + + images = np.stack(images, axis=0) + + if args.version == "captured": + images = images.mean(-1)[..., None] + + # 空间下采样的优化:使用面积插值 (Area Interpolation) + if split == "test" and images.shape[1] != args.img_shape_test: + N, H, W, T, C = images.shape + images_pt = torch.from_numpy(images).permute(0, 3, 4, 1, 2).reshape(N * T * C, 1, H, W) + images_pt = F.interpolate(images_pt, size=(args.img_height_test, args.img_width_test), mode='area') + images = images_pt.reshape(N, T, C, args.img_height_test, args.img_width_test).permute(0, 3, 4, 1, 2).numpy() + + images = np.clip(images / args.dataset_scale, 0, 1) ** (1 / args.gamma) + images = images.astype(np.float32) + camtoworlds = np.stack(camtoworlds, axis=0) + + # 保留原 Fwp 的完美针孔相机假设,利用 camera_angle_x 计算内参矩阵 K + h, w = images.shape[1:3] + # fov = float(meta["camera_angle_x"]) + # focal = 0.5 * w / np.tan(0.5 * fov) + # K = torch.tensor([ + # [focal, 0, w / 2.0], + # [0, focal, h / 2.0], + # [0, 0, 1], + # ], dtype=torch.float32) + K = torch.tensor([ + [args.fx, 0, args.cx], + [0, args.fy, args.cy], + [0, 0, 1], + ], dtype=torch.float32) + + # 对内参 K 矩阵也进行对应的降采样缩放 + if split == "test": + scale_x = args.img_width_test / w + scale_y = args.img_height_test / h + K[0, :] *= scale_x # 缩放 fx 和 cx + K[1, :] *= scale_y # 缩放 fy 和 cy + K[2, 2] = 1.0 # 保持齐次坐标为1 + + return images, camtoworlds, K + + +class SubjectLoader(torch.utils.data.Dataset): + SPLITS = ["train", "val", "trainval", "test"] + OPENGL_CAMERA = False + + 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): + super().__init__() + self.WIDTH = args.img_width_test if split == "test" else args.img_width + self.HEIGHT = args.img_height_test if split == "test" else args.img_height + self.args = args + self.split = split + self.num_rays = num_rays + self.training = (num_rays is not None) and (split in ["train", "trainval"]) + self.color_bkgd_aug = color_bkgd_aug + self.batch_over_images = batch_over_images + + # 加载图像、位姿与针孔内参 K + images, camtoworlds, K = _load_renderings(root_fp, split, args) + self.images = torch.from_numpy(images).to(torch.float32) + self.camtoworlds = torch.from_numpy(camtoworlds).to(torch.float32).to(args.device) + self.K = K.to(args.device) + self.aabb = torch.tensor(args.aabb, dtype=torch.float32, device=args.device).view(1, 6) + + # --------------------------------------------------------- + # 1 & 2. 从 intrinsics.npy 读取已合并的 Shift 硬件偏移 + # --------------------------------------------------------- + # 尝试获取 args.intrinsics_path,若未在 ini 中定义,则使用默认路径 + intrinsics_path = getattr(args, 'intrinsics_path', + '/work/runrong/project_all/FlyingWithPhotons/ini_generate/intrinsics.npy') + + if os.path.exists(intrinsics_path): + intrinsics = np.load(intrinsics_path, allow_pickle=True).item() + shift_raw = intrinsics["shift"] + + if isinstance(shift_raw, torch.Tensor): + shift_tensor = shift_raw.to(torch.float32).to(args.device) + else: + shift_tensor = torch.from_numpy(np.array(shift_raw, dtype=np.float32)).to(args.device) + + from loaders.calibration import shift_map + shift_tensor = shift_map(shift_tensor, self.HEIGHT, self.WIDTH, args.device) + + # shift 为物理距离(负数),需除以 exposure_time 转换为 bins,再取反用于正向补偿 (与 eval_ours.py 一致) + self.hardware_bin_shift = (-shift_tensor / args.exposure_time).to(torch.float32) + self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool, device=args.device) + else: + print(f"!!! Warning: {intrinsics_path} 不存在,已将硬件补偿回退为 0 !!!") + self.hardware_bin_shift = torch.zeros((self.HEIGHT, self.WIDTH), dtype=torch.float32, device=args.device) + self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool, device=args.device) + + self.output_valid_mask = self.valid_mask.clone() + + def __len__(self): + return len(self.images) + + @torch.no_grad() + def __getitem__(self, index): + data = self.fetch_data(index) + return self.preprocess(data) + + def preprocess(self, data): + rgba, rays, valid_mask = data["rgba"], data["rays"], data["valid_mask"] + 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) + + return { + "pixels": rgba.to(self.args.device), + "rays": rays, + "color_bkgd": color_bkgd, + "valid_mask": valid_mask, + **{k: v for k, v in data.items() if k not in ["rgba", "rays", "valid_mask"]}, + } + + def update_num_rays(self, num_rays): + self.num_rays = num_rays + + def fetch_data(self, index): + num_rays = self.num_rays + + if self.training: + image_id = torch.randint(0, len(self.images), size=(num_rays,), device=self.camtoworlds.device) if self.batch_over_images else [index] * num_rays + x = torch.randint(0, self.WIDTH, size=(num_rays,), device=self.camtoworlds.device) + y = torch.randint(0, self.HEIGHT, size=(num_rays,), device=self.camtoworlds.device) + else: + image_id = [index] + x, y = torch.meshgrid(torch.arange(self.WIDTH, device=self.camtoworlds.device), torch.arange(self.HEIGHT, device=self.camtoworlds.device), indexing="xy") + x, y = x.flatten(), y.flatten() + + idx_y_cpu, idx_x_cpu = y.cpu(), x.cpu() + idx_img_cpu = image_id.cpu() if isinstance(image_id, torch.Tensor) else image_id + + # 获取当前光线的直方图、基础有效掩码和纯硬件偏移 + rgba_raw = self.images[idx_img_cpu, idx_y_cpu, idx_x_cpu].to(self.args.device) + base_valid_mask = self.output_valid_mask[y, x] + bin_shift = self.hardware_bin_shift[y, x] + + c2w = self.camtoworlds[image_id] + + # 恢复原 Fwp 使用 Pinhole K 矩阵生成射线方向的逻辑 + camera_dirs = F.pad( + torch.stack( + [ + (x - self.K[0, 2] + 0.5) / self.K[0, 0] , + (y - self.K[1, 2] + 0.5) / self.K[1, 1] * (-1.0 if self.OPENGL_CAMERA else 1.0), + ], + dim=-1, + ), + (0, 1), + value=1.0 + ) + + directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1) + origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape) + viewdirs = directions / torch.linalg.norm(directions, dim=-1, keepdims=True) + + n_bins = rgba_raw.shape[1] + + # --------------------------------------------------------- + # 3. 仅应用硬件相关的 Shift (AABB 的半程交点 Shift 已移除) + # --------------------------------------------------------- + rgba_input = rgba_raw.permute(0, 2, 1).unsqueeze(2).contiguous() + t_grid = torch.linspace(-1, 1, n_bins, device=self.args.device) + norm_shift = bin_shift / (n_bins / 2.0) + + # 应用网格偏移 (+ norm_shift) + grid_x = t_grid.view(1, 1, n_bins) + norm_shift.view(-1, 1, 1) + grid_y = torch.zeros_like(grid_x) + grid = torch.stack([grid_x, grid_y], dim=-1).contiguous() + + # 关闭 cudnn 避免 grid_sample 非确定性错误 + import torch.backends.cudnn as cudnn + original_cudnn_state = cudnn.enabled + cudnn.enabled = False + try: + rgba_aligned = F.grid_sample(rgba_input, grid, mode='bilinear', padding_mode='zeros', align_corners=True) + finally: + cudnn.enabled = original_cudnn_state + + rgba = rgba_aligned.squeeze(2).permute(0, 2, 1) + valid_mask, meas_peak_mask, signal_mask = compute_transient_valid_mask_torch( + rgba, + self.args, + base_mask=base_valid_mask, + undo_gamma=True, + ) + # if torch.rand(1).item() < 0.01: # 抽样打印 + # print("DEBUG Train Loader - rgba max:", rgba.max().item()) + + # 整理输出形状 + if self.training: + origins = origins.view(num_rays, 3) + viewdirs = viewdirs.view(num_rays, 3) + rgba = rgba.view(num_rays, n_bins, -1) + else: + origins = origins.view(self.HEIGHT, self.WIDTH, 3) + viewdirs = viewdirs.view(self.HEIGHT, self.WIDTH, 3) + rgba = rgba.view(self.HEIGHT, self.WIDTH, n_bins, -1) + valid_mask = valid_mask.view(self.HEIGHT, self.WIDTH) + meas_peak_mask = meas_peak_mask.view(self.HEIGHT, self.WIDTH) + signal_mask = signal_mask.view(self.HEIGHT, self.WIDTH) + + return { + "rgba": rgba, + "rays": Rays(origins=origins, viewdirs=viewdirs), + "valid_mask": valid_mask, + "meas_peak_mask": meas_peak_mask, + "signal_mask": signal_mask, + } diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/streaming_loader.py b/codes/reconstruction/FlyingWithPhotons/loaders/streaming_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..adb4315ba0f8b31207e88b67bb7fbc8397061e64 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/loaders/streaming_loader.py @@ -0,0 +1,208 @@ +import json +import os +import numpy as np +import torch +import torch.nn.functional as F +import h5py +from .utils import Rays +import sys +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +def rays_from_h5(start, end, path, device="cuda:0"): + with h5py.File(os.path.join(path, "samples.h5"), 'r') as f: + data = np.array(f['dataset'][start:end, :, :3]) + data = torch.from_numpy(data).to(torch.float32) + data = data.to(device) + return data + +def get_x(start, end, path, device="cuda:0"): + with h5py.File(os.path.join(path, "x.h5"), 'r') as f: + x = torch.tensor(f['dataset'][start:end], device=device) + return x + +def get_y(start, end, path, device="cuda:0"): + with h5py.File(os.path.join(path, "y.h5"), 'r') as f: + y = torch.tensor(f['dataset'][start:end], device=device) + return y + +def get_file_indices(start, end, path): + with h5py.File(os.path.join(path, "file_indices.h5"), 'r') as f: + indices = torch.tensor(f['dataset'][start:end]) + indices = indices.type(torch.long) + return indices + + +def _load_renderings_metadata(root_fp: str, subject_id: str, split: str, args): + """Load images from disk.""" + + with open( + os.path.join(root_fp, "transforms_{}.json".format(split)), "r" + ) as fp: + meta = json.load(fp) + fnames = [] + camtoworlds = [] + + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + camtoworlds.append(frame["transform_matrix"]) + + camtoworlds = np.stack(camtoworlds, axis=0) + + if args.version == "simulated": + h, w = args.img_shape, args.img_shape + camera_angle_x = float(meta["camera"]) + focal = 0.5 * w / np.tan(0.5 * camera_angle_x) + K = torch.tensor( + [ + [focal, 0, w / 2.0], + [0, focal, h / 2.0], + [0, 0, 1], + ], + dtype=torch.float32) + else: + K = torch.tensor(np.array(meta["camera"])).to(torch.float32) + + with h5py.File(os.path.join(root_fp, "samples.h5"), 'r') as f: + length = f['dataset'].shape[0] + return length, camtoworlds, K + +class SubjectLoaderIterable(torch.utils.data.IterableDataset): + """Single subject data loader for training and evaluation.""" + + SPLITS = ["train", "val", "trainval", "test"] + OPENGL_CAMERA = True + + def __init__( + self, + counter, + num_rays, + root_fp: str, + split: str, + color_bkgd_aug: str = "white", + subject_id = None, + near: float = None, + far: float = None, + args = None, + + ): + super().__init__() + self.WIDTH = args.img_shape + self.HEIGHT = args.img_shape + + self.args = args + self.split = split + self.num_rays = num_rays + self.training = (num_rays is not None) and ( + split in ["train", "trainval"] + ) + self.color_bkgd_aug = color_bkgd_aug + self.root_fp = root_fp + self.subject_id = subject_id + self.len, self.camtoworlds, K = _load_renderings_metadata( + self.root_fp, self.subject_id, self.split, args + ) + + self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32) + + self.K = K + self.camtoworlds = self.camtoworlds.to(self.args.device) + self.K = self.K.to(self.args.device) + self.counter = counter + + + def __iter__(self): + while True: + data = self.fetch_data() + data = self.preprocess(data) + yield data + + def __len__(self): + return self.len + + def preprocess(self, data): + pixels, rays = data["rgba"], data["rays"] + pixels = torch.clip(pixels[...,self.args.t_min:self.args.t_max, :3]/self.args.dataset_scale, 0, 1)**(1/self.args.gamma) + + return { + "pixels": pixels, # [n_rays, 3] or [h, w, 3] + "rays": rays, # [n_rays,] or [h, w] + "color_bkgd": None, # [3,] + **{k: v for k, v in data.items() if k not in ["rgba", "rays"]}, + } + + + def fetch_data(self): + with self.num_rays.get_lock(): # ensure that only one worker can update num_rays at a time + num_rays = self.num_rays.value + with self.counter.get_lock(): # ensure that only one worker can update the counter at a time + start_index = self.counter.value + end_index = start_index + num_rays + if end_index > self.len: + self.counter.value = end_index - self.len + elif end_index == self.len: + self.counter.value = 0 + start_index = 0 + end_index = num_rays + else: + self.counter.value += num_rays + + # Load chunk of data. + if end_index <= self.len: + data = rays_from_h5(start_index, end_index, self.root_fp, self.args.device) + x = get_x(start_index, end_index, self.root_fp, self.args.device) + y = get_y(start_index, end_index, self.root_fp, self.args.device) + cam_index = get_file_indices(start_index, end_index, self.root_fp) + + elif start_index < self.len and end_index > self.len: + first_data = rays_from_h5(start_index, self.len, self.root_fp, self.args.device) + second_data = rays_from_h5(0, end_index - self.len, self.root_fp, self.args.device) + first_x = get_x(start_index, self.len, self.root_fp, self.args.device) + second_x = get_x(0, end_index - self.len, self.root_fp, self.args.device) + first_y = get_y(start_index, self.len, self.root_fp, self.args.device) + second_y = get_y(0, end_index - self.len, self.root_fp, self.args.device) + first_cam_index = get_file_indices(start_index, self.len, self.root_fp) + second_cam_index = get_file_indices(0, end_index - self.len, self.root_fp) + + data = torch.cat((first_data, second_data),axis=0) + x = torch.cat((first_x, second_x),axis=0) + y = torch.cat((first_y, second_y),axis=0) + cam_index = torch.cat((first_cam_index,second_cam_index),axis=0) + + + c2w = self.camtoworlds[cam_index] + rgba = data + + camera_dirs = F.pad( + torch.stack( + [ + (x - self.K[0, 2] + 0.5) / self.K[0, 0], + (y - self.K[1, 2] + 0.5) + / self.K[1, 1] + * (-1.0 if self.OPENGL_CAMERA else 1.0), + ], + dim=-1, + ), + (0, 1), + value=(-1.0 if self.OPENGL_CAMERA else 1.0), + ) # [num_rays, 3] + + directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1) + origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape) + viewdirs = directions / torch.linalg.norm( + directions, dim=-1, keepdims=True + ) + + if self.training: + origins = torch.reshape(origins, (num_rays, 3)) + viewdirs = torch.reshape(viewdirs, (num_rays, 3)) + else: + origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3)) + viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3)) + rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, -1)) + + rays = Rays(origins=origins, viewdirs=viewdirs) + + return { + "rgba": rgba, # [h, w, 4] or [num_rays, 4] + "rays": rays, # [h, w, 3] or [num_rays, 3] + } \ No newline at end of file diff --git a/codes/reconstruction/FlyingWithPhotons/loaders/utils.py b/codes/reconstruction/FlyingWithPhotons/loaders/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..04d223f54022448c9827f4f26768a2b5973ba37a --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/loaders/utils.py @@ -0,0 +1,12 @@ +""" +Copyright (c) 2022 Ruilong Li, UC Berkeley. +""" + +import collections + +Rays = collections.namedtuple("Rays", ("origins", "viewdirs")) + + +def namedtuple_map(fn, tup): + """Apply `fn` to each element of `tup` and cast to `tup`'s namedtuple.""" + return type(tup)(*(None if x is None else fn(x) for x in tup)) diff --git a/codes/reconstruction/FlyingWithPhotons/misc/__init__.py b/codes/reconstruction/FlyingWithPhotons/misc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dc1d2dff001c71450ec6432d5ad518ed34f6045 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/summary.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/summary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4b5e0e401f4490212d1e4f92748d3445feb5f04 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/summary.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/transient_volrend.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/transient_volrend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68b8473e7f9c523f0192874f24cc2d10eac2fc7b Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/misc/__pycache__/transient_volrend.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/misc/dataset_utils.py b/codes/reconstruction/FlyingWithPhotons/misc/dataset_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4538af85beee39b58ba38ff8655fc7bcc4ffe0 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/misc/dataset_utils.py @@ -0,0 +1,169 @@ +import os +import mat73 +import torch +import numpy as np +import json +import h5py + +def read_h5(path): + with h5py.File(path, 'r') as f: + frames = np.array(f['data']) + return frames + +def process_captured_data(files_path, savepath): + for file in os.listdir(files_path): + if file[-3:] == "mat" and (file[:-3]+"pt") not in os.listdir(savepath): + filepath = os.path.join(files_path, file) + rgba = mat73.loadmat(filepath)["transient"].transpose(1, 2, 0)[..., :][..., None] + rgba = np.flip(np.flip(rgba, 0), 1) + for i in range(3): + rgba = (rgba[1::2, ::2] + rgba[::2, ::2] + rgba[1::2, 1::2] + rgba[::2, 1::2])/4 + torch.save(rgba, os.path.join(savepath, file[:-3]+"pt")) + +def bundle_rays(pathToH5s, outputPath, trainJsonPath): + with open(trainJsonPath, "r") as fp: + meta = json.load(fp) + train_fnames = [] + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + fname = frame["filepath"][:-2]+"h5" + train_fnames.append(fname) + + frames = read_h5(os.path.join(pathToH5s, train_fnames[0])) + w = frames.shape[0] + h = frames.shape[1] + bins = frames.shape[2] + + x = np.linspace(0, h-1, h) + y = np.linspace(0, w-1, w) + X, Y = np.meshgrid(x, y) + + if len(frames.shape) == 4: + channels = 3 + else: + channels = 1 + num_train_files = len(train_fnames) + + data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32) + x_array = np.zeros(w*h*num_train_files) + y_array = np.zeros(w*h*num_train_files) + file_prefix_array = np.zeros(w*h*num_train_files) + + for ind, file in enumerate(train_fnames): + print("Opening: " + file) + frames = read_h5(os.path.join(pathToH5s, file)) + frames = frames.reshape(-1, frames.shape[2], frames.shape[3]) + + data_array[ind*w*h:(ind+1)*w*h] = frames[..., :3] + x_array[ind*w*h:(ind+1)*w*h] = X.flatten() + y_array[ind*w*h:(ind+1)*w*h] = Y.flatten() + file_prefix_array[ind*w*h:(ind+1)*w*h] = ind + + p = np.random.permutation(data_array.shape[0]) + data_array = data_array[p] + x_array = x_array[p] + y_array = y_array[p] + file_prefix_array = file_prefix_array[p] + + + print("Outputting to files") + file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w') + dataset = file.create_dataset( + "dataset", data_array.shape, dtype='f', data=data_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "x.h5"), 'w') + dataset = file.create_dataset( + "dataset", x_array.shape, dtype='f', data=x_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "y.h5"), 'w') + dataset = file.create_dataset( + "dataset", y_array.shape, dtype='f', data=y_array + ) + file.close() + file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w') + dataset = file.create_dataset( + "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array + ) + file.close() + + +def bundle_rays_cap(pathToH5s, outputPath, trainJsonPath): + with open(trainJsonPath, "r") as fp: + meta = json.load(fp) + train_fnames = [] + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + fname = frame["filepath"][:-2].split("/")[-1]+"mat" + train_fnames.append(fname) + + # frames = read_h5_dataset(os.path.join(pathToH5s, train_fnames[0])) + frames = mat73.loadmat(os.path.join(pathToH5s, train_fnames[0]))["transient"].transpose(1, 2, 0) + w = frames.shape[0] + h = frames.shape[1] + # bins = frames.shape[2] + bins = 3000 + + x = np.linspace(0, h-1, h) + y = np.linspace(0, w-1, w) + X, Y = np.meshgrid(x, y) + + # if len(frames.shape) == 4: + # channels = 3 + # else: + channels = 1 + num_train_files = len(train_fnames) + + data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32) + x_array = np.zeros(w*h*num_train_files) + y_array = np.zeros(w*h*num_train_files) + file_prefix_array = np.zeros(w*h*num_train_files) + + for ind, file in enumerate(train_fnames): + print("Opening: " + file) + # frames = read_h5_dataset(os.path.join(pathToH5s, file)) + frames = mat73.loadmat(os.path.join(pathToH5s, file))["transient"].transpose(1, 2, 0) + frames = frames.reshape(-1, frames.shape[2]) + + data_array[ind*w*h:(ind+1)*w*h] = frames[..., :bins, None] + # del frames + x_array[ind*w*h:(ind+1)*w*h] = X.flatten() + y_array[ind*w*h:(ind+1)*w*h] = Y.flatten() + file_prefix_array[ind*w*h:(ind+1)*w*h] = ind + + p = np.random.permutation(data_array.shape[0]) + data_array = data_array[p] + x_array = x_array[p] + y_array = y_array[p] + file_prefix_array = file_prefix_array[p] + + + print("Outputting to files") + file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w') + dataset = file.create_dataset( + "dataset", data_array.shape, dtype='f', data=data_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "x.h5"), 'w') + dataset = file.create_dataset( + "dataset", x_array.shape, dtype='f', data=x_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "y.h5"), 'w') + dataset = file.create_dataset( + "dataset", y_array.shape, dtype='f', data=y_array + ) + file.close() + file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w') + dataset = file.create_dataset( + "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array + ) + file.close() + +if __name__=="__main__": + pass \ No newline at end of file diff --git a/codes/reconstruction/FlyingWithPhotons/misc/summary.py b/codes/reconstruction/FlyingWithPhotons/misc/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..54509446d44a3f2191b7b1e1f9c705ae7e008804 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/misc/summary.py @@ -0,0 +1,116 @@ +import imgviz +import numpy as np +from utils import render_image_with_occgrid_test +import matplotlib.pyplot as plt +import torchvision +import torch +import os + +@torch.no_grad() +def write_summary_histogram(radiance_field, estimator, writer, test_dataset, step, args): + img_scale = args.img_scale + radiance_field.eval() + estimator.eval() + rgb_images = [] + depth_images = [] + gt_imgs = [] + accs = [] + + pixels_to_plot = args.pixels_to_plot + plotting_transients = [] + plotting_transients_depth = [] + + plotting_transients_gt = [] + + test_list = list(range(len(test_dataset))) + if args.version == "simulated": + color_channels = 3 + else: + color_channels = 1 + n_output_dim = args.n_bins*(color_channels) + with torch.no_grad(): + + # sample transients from network + for ind, i in enumerate(test_list): + data = test_dataset[i] + render_bkgd = data["color_bkgd"] + rays = data["rays"] + pixels = data["pixels"] + + # rendering + rgb, acc, depth, _ = render_image_with_occgrid_test( + 1024, + # scene + radiance_field, + estimator, + rays, + args=args, + # rendering options + near_plane=args.near_plane, + far_plane=args.far_plane, + render_step_size=args.render_step_size, + render_bkgd=render_bkgd, + cone_angle=args.cone_angle, + alpha_thre=args.alpha_thre, + n_output_dim=n_output_dim, + prop_delay=args.prop_delay + ) + + rgb = rgb.reshape(rays.origins.shape[0], rays.origins.shape[1], -1, color_channels) + + torch.save(rgb, os.path.join(args.outpath, f"test_{ind}_conv.pt")) + torch.save(depth, os.path.join(args.outpath, f"test_{ind}_depth.pt")) + + if color_channels ==1: + gt_imgs.append(torch.clip(pixels.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)) + rgb_images.append(torch.clip(rgb.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)) + else: + gt_imgs.append(torch.clip(pixels.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)) + rgb_images.append(torch.clip(rgb.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)) + accs.append(acc.repeat(1, 1, 3).permute(2, 0, 1).cpu()) + dp = imgviz.depth2rgb(depth.cpu().squeeze().numpy(), colormap="inferno") + depth_images.append(torch.from_numpy(dp).permute(2, 0, 1)) + + if ind == 0: + for pixel in pixels_to_plot: + plotting_transients.append(rgb[pixel[0], pixel[1], :, 0]) + plotting_transients_gt.append(pixels[pixel[0], pixel[1], :, 0]) + plotting_transients_depth.append(depth[pixel[0], pixel[1]]) + + + images = torchvision.utils.make_grid(torch.stack(gt_imgs + rgb_images + depth_images + accs), nrow=len(test_list), normalize=False) + mse = torch.mean((torch.stack(gt_imgs, dim=0) - torch.stack(rgb_images, dim=0))**2, (1,2,3)) + psnr = -10.0 * torch.log(mse) / np.log(10.0) + print(f"image psnr: {psnr.mean():.2f}\n") + writer.add_image('rgbdn', images, step) + + figure = plt.figure(figsize=((len(pixels_to_plot)+1), 4), dpi=250) + + # plot the predicted intensity + plt.subplot(2, (len(pixels_to_plot)+1)//2, 1) + plt.imshow(gt_imgs[0].permute(1, 2, 0)) + for i, pixel in enumerate(pixels_to_plot): + plt.plot(pixel[1], pixel[0], '.', markersize=10, color='red') + plt.text(pixel[1], pixel[0], str(i), color="yellow", fontsize=10) + plt.gca().set_aspect(1.0/plt.gca().get_data_ratio(), adjustable='box') + plt.title('gt intensity') + + for i, pixel in enumerate(pixels_to_plot): + # plot transients + plt.subplot(2, (len(pixels_to_plot)+1)//2, i+2) + plt.plot(np.arange(args.n_bins), plotting_transients[i].detach().cpu(), label='pred', linewidth=0.5) + plt.plot(np.arange(args.n_bins), plotting_transients_gt[i].detach().cpu(), label='gt', linewidth=0.5) + plt.axvline(x = (plotting_transients_depth[i]/args.exposure_time).detach().cpu().numpy(), color = 'y') + plt.title(f"pixel {i}") + plt.ylabel('intensity') + plt.legend(borderpad=0, labelspacing=0) + plt.gca().set_aspect(1.0 / plt.gca().get_data_ratio(), adjustable='box') + + plt.tight_layout() + writer.add_figure("transient_plots", figure, step) + + + radiance_field.train() + estimator.train() + + diff --git a/codes/reconstruction/FlyingWithPhotons/misc/transient_volrend.py b/codes/reconstruction/FlyingWithPhotons/misc/transient_volrend.py new file mode 100644 index 0000000000000000000000000000000000000000..00b95e59700968332bf0adf44519c7d8fbcbe188 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/misc/transient_volrend.py @@ -0,0 +1,637 @@ +from typing import Callable, Dict, Optional, Tuple +import torch +from torch import Tensor +from nerfacc.pack import pack_info +from nerfacc.scan import exclusive_prod, exclusive_sum + +def rendering( + # ray marching results + t_starts: Tensor, + t_ends: Tensor, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + # radiance field + rgb_sigma_fn: Optional[Callable] = None, + rgb_alpha_fn: Optional[Callable] = None, + # rendering options + render_bkgd: Optional[Tensor] = None, + args = None, + t_mins: Optional[Tensor] = None, # 新增:接收每个样本对应射线的 AABB 入射距离 + step: int = -1, +) -> Tuple[Tensor, Tensor, Tensor, Dict]: + """Render the rays through the radience field defined by `rgb_sigma_fn`. + + This function is differentiable to the outputs of `rgb_sigma_fn` so it can + be used for gradient-based optimization. It supports both batched and flattened input tensor. + For flattened input tensor, both `ray_indices` and `n_rays` should be provided. + + + Note: + Either `rgb_sigma_fn` or `rgb_alpha_fn` should be provided. + + Warning: + This function is not differentiable to `t_starts`, `t_ends` and `ray_indices`. + + Args: + t_starts: Per-sample start distance. Tensor with shape (n_rays, n_samples) or (all_samples,). + t_ends: Per-sample end distance. Tensor with shape (n_rays, n_samples) or (all_samples,). + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + rgb_sigma_fn: A function that takes in samples {t_starts, t_ends, + ray indices} and returns the post-activation rgb (..., 3) and density + values (...,). The shape `...` is the same as the shape of `t_starts`. + rgb_alpha_fn: A function that takes in samples {t_starts, t_ends, + ray indices} and returns the post-activation rgb (..., 3) and opacity + values (...,). The shape `...` is the same as the shape of `t_starts`. + render_bkgd: Background color. Tensor with shape (3,). + args: Arguments from config. + + Returns: + Ray colors (n_rays, 3), opacities (n_rays, 1), depths (n_rays, 1) and a dict + containing extra intermediate results (e.g., "weights", "trans", "alphas") + """ + if ray_indices is not None: + assert ( + t_starts.shape == t_ends.shape == ray_indices.shape + ), "Since nerfacc 0.5.0, t_starts, t_ends and ray_indices must have the same shape (N,). " + + if rgb_sigma_fn is None and rgb_alpha_fn is None: + raise ValueError( + "At least one of `rgb_sigma_fn` and `rgb_alpha_fn` should be specified." + ) + + # Query sigma/alpha and color with gradients + if rgb_sigma_fn is not None: + if t_starts.shape[0] != 0: + rgbs, sigmas = rgb_sigma_fn(t_starts, t_ends, ray_indices) + + # Shift for propagaton delay. + if args.prop_delay: + # rgbs = rgbs.reshape(rgbs.shape[0], args.n_bins, -1) + # sample_dist = (t_starts + t_ends).view(-1, 1) + # assert ray_indices.max() < t_mins.shape[0], "ray_indices 超出了 t_mins 的范围!" + # #shift = (t_starts + t_ends)[:, None]/ 2.0 + # curr_t_mins = t_mins[ray_indices].view(-1, 1) + # shift = sample_dist - 2.0*curr_t_mins + # assert shift.shape == (t_starts.shape[0], 1), f"Shift 形状错误: {shift.shape}" + + # rgbs= shift_transient_grid_sample_3d(rgbs, shift, args.exposure_time, args.n_bins,chunk_size=16384)[..., None] + #rgbs = rgbs.reshape((rgbs.shape[0], -1)) + + # 诊断 1:检查 MLP 原始输出是否为 0 + do_debug = (step>=0 and step% 5000==0) + if do_debug: + print(f"\n[STEP{step}诊断]") + print(f"DEBUG: MLP rgbs max before shift: {rgbs.max().item():.6f}") + shift = (t_starts + t_ends)[:, None]/ 2.0 + # 诊断 2:检查平移量(Bins)的量级 + avg_bins_move = (shift / args.exposure_time).mean().item() + if do_debug: + print(f"DEBUG: Average bins_move: {avg_bins_move:.2f}") + rgbs_transient = rgbs.reshape(rgbs.shape[0], args.n_bins, -1) + # 执行平移 + rgbs_shifted = shift_transient_grid_sample_3d( + rgbs_transient, + shift, + args.exposure_time, + args.n_bins, + chunk_size=16384 + ) + # 诊断 3:检查平移后是否全为 0 + if do_debug and rgbs_shifted.max() == 0 and rgbs_transient.max() > 0: + print("警告:grid_sample 将所有信号平移到了有效窗口之外!请检查 exposure_time 和 shift 物理单位。") + + rgbs = rgbs_shifted.reshape((rgbs.shape[0], -1)) + + + else: + rgbs = torch.empty((0, 3), device=t_starts.device) + sigmas = torch.empty((0,), device=t_starts.device) + channel_num = 1 + assert ( + sigmas.shape == t_starts.shape + ), "sigmas must have shape of (N,)! Got {}".format(sigmas.shape) + + # Rendering: compute weights. + weights, trans, alphas = render_weight_from_density( + t_starts, + t_ends, + sigmas, + ray_indices=ray_indices, + n_rays=n_rays, + ) + extras = { + "weights": weights, + "alphas": alphas, + "trans": trans, + "sigmas": sigmas, + "rgbs": rgbs, + } + elif rgb_alpha_fn is not None: + if t_starts.shape[0] != 0: + rgbs, alphas = rgb_alpha_fn(t_starts, t_ends, ray_indices) + else: + rgbs = torch.empty((0, 3), device=t_starts.device) + alphas = torch.empty((0,), device=t_starts.device) + + assert ( + alphas.shape == t_starts.shape + ), "alphas must have shape of (N,)! Got {}".format(alphas.shape) + + # Rendering: compute weights. + weights, trans = render_weight_from_alpha( + alphas, + ray_indices=ray_indices, + n_rays=n_rays, + ) + extras = { + "weights": weights, + "trans": trans, + "rgbs": rgbs, + "alphas": alphas, + } + + # Rendering: accumulate rgbs, opacities, and depths along the rays. + colors = accumulate_along_rays( + weights, values=rgbs, ray_indices=ray_indices, n_rays=n_rays + ) + # print("debug:accumulate rgbs:",colors.max()) + + opacities = accumulate_along_rays( + weights, values=None, ray_indices=ray_indices, n_rays=n_rays + ) + depths = accumulate_along_rays( + weights, + values=(t_starts + t_ends)[..., None] / 2.0, + ray_indices=ray_indices, + n_rays=n_rays, + ) + depths = depths / opacities.clamp_min(torch.finfo(rgbs.dtype).eps) + return colors, opacities, depths, extras + +def render_transmittance_from_alpha( + alphas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tensor: + """Compute transmittance :math:`T_i` from alpha :math:`\\alpha_i`. + + .. math:: + T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering transmittance with the same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices) + tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0]) + """ + # FIXME Try not to use exclusive_prod because: + # 1. torch.cumprod is much slower than torch.cumsum + # 2. exclusive_prod gradient on input == 0 is not correct. + if ray_indices is not None and packed_info is None: + packed_info = pack_info(ray_indices, n_rays) + + trans = exclusive_prod(1 - alphas, packed_info) + if prefix_trans is not None: + trans *= prefix_trans + return trans + + +def render_transmittance_from_density( + t_starts: Tensor, + t_ends: Tensor, + sigmas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Compute transmittance :math:`T_i` from density :math:`\\sigma_i`. + + .. math:: + T_i = exp(-\\sum_{j=1}^{i-1}\\sigma_j\delta_j) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + t_starts: Where the frustum-shape sample starts along a ray. Tensor with \ + shape (all_samples,) or (n_rays, n_samples). + t_ends: Where the frustum-shape sample ends along a ray. Tensor with \ + shape (all_samples,) or (n_rays, n_samples). + sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering transmittance and opacities, both with the same shape as `sigmas`. + + Examples: + + .. code-block:: python + + >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda") + >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda") + >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance, alphas = render_transmittance_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices) + transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00] + alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59] + + """ + if ray_indices is not None and packed_info is None: + packed_info = pack_info(ray_indices, n_rays) + + sigmas_dt = sigmas * (t_ends - t_starts) + alphas = 1.0 - torch.exp(-sigmas_dt) + trans = torch.exp(-exclusive_sum(sigmas_dt, packed_info)) + if prefix_trans is not None: + trans *= prefix_trans + return trans, alphas + + +def render_weight_from_alpha( + alphas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Compute rendering weights :math:`w_i` from opacity :math:`\\alpha_i`. + + .. math:: + w_i = T_i\\alpha_i, \\quad\\textrm{where}\\quad T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering weights and transmittance, both with the same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> weights, transmittance = render_weight_from_alpha(alphas, ray_indices=ray_indices) + weights: [0.4, 0.48, 0.012, 0.8, 0.02, 0.0, 0.9]) + transmittance: [1.00, 0.60, 0.12, 1.00, 0.20, 1.00, 1.00] + + """ + trans = render_transmittance_from_alpha( + alphas, packed_info, ray_indices, n_rays, prefix_trans + ) + weights = trans * alphas + return weights, trans + + +def render_weight_from_density( + t_starts: Tensor, + t_ends: Tensor, + sigmas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor, Tensor]: + """Compute rendering weights :math:`w_i` from density :math:`\\sigma_i` and interval :math:`\\delta_i`. + + .. math:: + 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) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + t_starts: The start time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + t_ends: The end time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering weights, transmittance and opacities, both with the same shape as `sigmas`. + + Examples: + + .. code-block:: python + + >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda") + >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda") + >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> weights, transmittance, alphas = render_weight_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices) + weights: [0.33, 0.37, 0.03, 0.55, 0.04, 0.00, 0.59] + transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00] + alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59] + + """ + trans, alphas = render_transmittance_from_density( + t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans + ) + weights = trans * alphas + return weights, trans, alphas + + +@torch.no_grad() +def render_visibility_from_alpha( + alphas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + early_stop_eps: float = 1e-4, + alpha_thre: float = 0.0, + prefix_trans: Optional[Tensor] = None, +) -> Tensor: + """Compute visibility from opacity :math:`\\alpha_i`. + + In this function, we first compute the transmittance from the sample opacity. The + transmittance is then used to filter out occluded samples. And opacity is used to + filter out transparent samples. The function returns a boolean tensor indicating + which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`). + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + early_stop_eps: The early stopping threshold on transmittance. + alpha_thre: The threshold on opacity. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + A boolean tensor indicating which samples are visible. Same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices) + tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0]) + >>> visibility = render_visibility_from_alpha( + >>> alphas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2) + tensor([True, True, False, True, False, False, True]) + + """ + trans = render_transmittance_from_alpha( + alphas, packed_info, ray_indices, n_rays, prefix_trans + ) + vis = trans >= early_stop_eps + if alpha_thre > 0: + vis = vis & (alphas >= alpha_thre) + return vis + + +@torch.no_grad() +def render_visibility_from_density( + t_starts: Tensor, + t_ends: Tensor, + sigmas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + early_stop_eps: float = 1e-4, + alpha_thre: float = 0.0, + prefix_trans: Optional[Tensor] = None, +) -> Tensor: + """Compute visibility from density :math:`\\sigma_i` and interval :math:`\\delta_i`. + + In this function, we first compute the transmittance and opacity from the sample density. The + transmittance is then used to filter out occluded samples. And opacity is used to + filter out transparent samples. The function returns a boolean tensor indicating + which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`). + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + early_stop_eps: The early stopping threshold on transmittance. + alpha_thre: The threshold on opacity. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + A boolean tensor indicating which samples are visible. Same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda") + >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda") + >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance, alphas = render_transmittance_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices) + transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00] + alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59] + >>> visibility = render_visibility_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2) + tensor([True, True, False, True, False, False, True]) + + """ + trans, alphas = render_transmittance_from_density( + t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans + ) + vis = trans >= early_stop_eps + if alpha_thre > 0: + vis = vis & (alphas >= alpha_thre) + return vis + + +def accumulate_along_rays( + weights: Tensor, + values: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, +) -> Tensor: + """Accumulate volumetric values along the ray. + + This function supports both batched inputs and flattened inputs with + `ray_indices` and `n_rays` provided. + + Note: + This function is differentiable to `weights` and `values`. + + Args: + weights: Weights to be accumulated. If `ray_indices` not provided, + `weights` must be batched with shape (n_rays, n_samples). Else it + must be flattened with shape (all_samples,). + values: Values to be accumulated. If `ray_indices` not provided, + `values` must be batched with shape (n_rays, n_samples, D). Else it + must be flattened with shape (all_samples, D). None means + we accumulate weights along rays. Default: None. + ray_indices: Ray indices of the samples with shape (all_samples,). + If provided, `weights` must be a flattened tensor with shape (all_samples,) + and values (if not None) must be a flattened tensor with shape (all_samples, D). + Default: None. + n_rays: Number of rays. Should be provided together with `ray_indices`. Default: None. + + Returns: + Accumulated values with shape (n_rays, D). If `values` is not given we return + the accumulated weights, in which case D == 1. + + Examples: + + .. code-block:: python + + # Rendering: accumulate rgbs, opacities, and depths along the rays. + colors = accumulate_along_rays(weights, rgbs, ray_indices, n_rays) + opacities = accumulate_along_rays(weights, None, ray_indices, n_rays) + depths = accumulate_along_rays( + weights, + (t_starts + t_ends)[:, None] / 2.0, + ray_indices, + n_rays, + ) + # (n_rays, 3), (n_rays, 1), (n_rays, 1) + print(colors.shape, opacities.shape, depths.shape) + + """ + if values is None: + src = weights[..., None] + else: + assert values.dim() == weights.dim() + 1 + assert weights.shape == values.shape[:-1] + src = weights[..., None] * values + if ray_indices is not None: + assert n_rays is not None, "n_rays must be provided" + assert weights.dim() == 1, "weights must be flattened" + outputs = torch.zeros( + (n_rays, src.shape[-1]), device=src.device, dtype=src.dtype + ) + outputs.index_add_(0, ray_indices, src) + else: + outputs = torch.sum(src, dim=-2) + return outputs + + +def accumulate_along_rays_( + weights: Tensor, + values: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + outputs: Optional[Tensor] = None, +) -> None: + """Accumulate volumetric values along the ray. + + Inplace version of :func:`accumulate_along_rays`. + """ + if weights.shape[0] == 0: + return 0 + if values is None: + src = weights[..., None] + else: + assert values.dim() == weights.dim() + 1 + assert weights.shape == values.shape[:-1] + src = weights[..., None] * values + if ray_indices is not None: + # assert weights.dim() == 1, "weights must be flattened" + # assert ( + # outputs.dim() == 2 and outputs.shape[-1] == src.shape[-1] + # ), "outputs must be of shape (n_rays, D)" + outputs.index_add_(0, ray_indices, src) + else: + outputs.add_(src.sum(dim=-2)) + + +def shift_transient_grid_sample_3d(transient, depth, exposure_time, n_bins, chunk_size=16384): + # 修改移动函数,分块执行1D信号平移,防止显存爆炸 + # all_samples = transient.shape[0] + # shifted_chunks = [] + # z_base = torch.arange(n_bins, device=transient.device).float().view(1, n_bins) + # for i in range(0, all_samples, chunk_size): + # curr_transient = transient[i : i+chunk_size] + # curr_depth = depth[i : i+chunk_size] + # curr_x_dim = curr_transient.shape[0] + # bins_move = curr_depth / exposure_time + # if curr_x_dim % 2 == 0: + # x = (torch.arange(curr_x_dim, device=transient.device) - curr_x_dim//2+0.5)/(curr_x_dim//2-0.5) + # else: + # x = (torch.arange(curr_x_dim, device=transient.device) - curr_x_dim//2)/(curr_x_dim//2) + # if curr_x_dim == 1: + # x = torch.zeros_like(x) + # z = torch.arange(n_bins, device=transient.device).float() + # X, Z = torch.meshgrid(x, z, indexing="ij") + # Z = Z-bins_move + # Z[Z<0] = n_bins + 1 + # Z = (Z-n_bins//2 + 0.5) / (n_bins//2 -0.5) + # grid = torch.stack((Z, X), dim=-1)[None, ...] + # shifted = torch.nn.functional.grid_sample( + # curr_transient.permute(2, 0, 1)[None], + # grid, + # align_corners=True, + # padding_mode='zeros' + # ) + # shifted_chunks.append(shifted.squeeze(0).permute(1, 2, 0)) + # return torch.cat(shifted_chunks, dim=0) + x_dim = transient.shape[0] + bins_move = depth/exposure_time + if x_dim%2 == 0: + x = (torch.arange(x_dim, device=transient.device)-x_dim//2+0.5)/(x_dim//2-0.5) + else: + x = (torch.arange(x_dim, device=transient.device)-x_dim//2)/(x_dim//2) + + if x_dim == 1: + x = torch.zeros_like(x) + + z = torch.arange(n_bins, device=transient.device).float() + X, Z = torch.meshgrid(x, z, indexing="ij") + Z = Z - bins_move + Z[Z<0] = n_bins+1 + Z = (Z-n_bins//2+0.5)/(n_bins//2-0.5) + grid = torch.stack((Z, X), dim=-1)[None, ...] + shifted_transient = torch.nn.functional.grid_sample(transient.permute(2, 0, 1)[None], grid, align_corners=True).squeeze(0).permute(1, 2, 0) + return shifted_transient + diff --git a/codes/reconstruction/FlyingWithPhotons/radiance_fields/__init__.py b/codes/reconstruction/FlyingWithPhotons/radiance_fields/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a58f3bf18734999056f1435388cbf13abe6d7ff2 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/ngp.cpython-312.pyc b/codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/ngp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87ea5ef0df508570061223a50e640a79721f50e1 Binary files /dev/null and b/codes/reconstruction/FlyingWithPhotons/radiance_fields/__pycache__/ngp.cpython-312.pyc differ diff --git a/codes/reconstruction/FlyingWithPhotons/radiance_fields/ngp.py b/codes/reconstruction/FlyingWithPhotons/radiance_fields/ngp.py new file mode 100644 index 0000000000000000000000000000000000000000..ce9cca2dd6975fd9f503313eb2d69410336f0039 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/radiance_fields/ngp.py @@ -0,0 +1,306 @@ +""" +Copyright (c) 2022 Ruilong Li, UC Berkeley. +""" + +from typing import Callable, List, Union + +import numpy as np +import torch +from torch.autograd import Function +from torch.cuda.amp import custom_bwd, custom_fwd +import torch.nn.functional as F + +try: + import tinycudann as tcnn +except ImportError as e: + print( + f"Error: {e}! " + "Please install tinycudann by: " + "pip install git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch" + ) + exit() + + +class _TruncExp(Function): # pylint: disable=abstract-method + # Implementation from torch-ngp: + # https://github.com/ashawkey/torch-ngp/blob/93b08a0d4ec1cc6e69d85df7f0acdfb99603b628/activation.py + @staticmethod + @custom_fwd(cast_inputs=torch.float32) + def forward(ctx, x): # pylint: disable=arguments-differ + ctx.save_for_backward(x) + return torch.exp(x) + + @staticmethod + @custom_bwd + def backward(ctx, g): # pylint: disable=arguments-differ + x = ctx.saved_tensors[0] + return g * torch.exp(torch.clamp(x, max=15)) + + +trunc_exp = _TruncExp.apply + + +def contract_to_unisphere( + x: torch.Tensor, + aabb: torch.Tensor, + ord: Union[str, int] = 2, + # ord: Union[float, int] = float("inf"), + eps: float = 1e-6, + derivative: bool = False, +): + aabb_min, aabb_max = torch.split(aabb, 3, dim=-1) + x = (x - aabb_min) / (aabb_max - aabb_min) + x = x * 2 - 1 # aabb is at [-1, 1] + mag = torch.linalg.norm(x, ord=ord, dim=-1, keepdim=True) + mask = mag.squeeze(-1) > 1 + + if derivative: + dev = (2 * mag - 1) / mag**2 + 2 * x**2 * ( + 1 / mag**3 - (2 * mag - 1) / mag**4 + ) + dev[~mask] = 1.0 + dev = torch.clamp(dev, min=eps) + return dev + else: + x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask]) + x = x / 4 + 0.5 # [-inf, inf] is at [0, 1] + return x + + +class NGPRadianceField(torch.nn.Module): + """Instance-NGP Radiance Field""" + + def __init__( + self, + aabb: Union[torch.Tensor, List[float]], + num_dim: int = 3, + use_viewdirs: bool = True, + density_activation: Callable = lambda x: trunc_exp(x - 1), + radiance_activation: Callable = lambda x: F.sigmoid(x), + unbounded: bool = False, + base_resolution: int = 16, + max_resolution: int = 4096, + geo_feat_dim: int = 15, + n_levels: int = 16, + log2_hashmap_size: int = 19, + args = None + ) -> None: + super().__init__() + if not isinstance(aabb, torch.Tensor): + aabb = torch.tensor(aabb, dtype=torch.float32) + self.register_buffer("aabb", aabb) + self.num_dim = num_dim + self.radiance_activation = radiance_activation + self.use_viewdirs = use_viewdirs + self.density_activation = density_activation + self.unbounded = unbounded + self.base_resolution = base_resolution + self.max_resolution = max_resolution + self.geo_feat_dim = geo_feat_dim + self.n_levels = n_levels + self.log2_hashmap_size = log2_hashmap_size + self.version = args.version + self.args = args + if self.version == "simulated": + self.colour_channels = 3 + else: + self.colour_channels = 1 + + self.radiance_activation = radiance_activation + self.n_output_dim = args.n_bins*self.colour_channels + + + + + per_level_scale = np.exp( + (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1) + ).tolist() + + if self.use_viewdirs: + self.direction_encoding = tcnn.Encoding( + n_input_dims=num_dim, + encoding_config={ + "otype": "Composite", + "nested": [ + { + "n_dims_to_encode": 3, + "otype": "SphericalHarmonics", + "degree": 4, + }, + # {"otype": "Identity", "n_bins": 4, "degree": 4}, + ], + }, + ) + + self.mlp_base = tcnn.NetworkWithInputEncoding( + n_input_dims=num_dim, + n_output_dims=1 + self.geo_feat_dim, + encoding_config={ + "otype": "HashGrid", + "n_levels": n_levels, + "n_features_per_level": 2, + "log2_hashmap_size": log2_hashmap_size, + "base_resolution": base_resolution, + "per_level_scale": per_level_scale, + }, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 1, + }, + ) + if self.geo_feat_dim > 0: + self.mlp_head = tcnn.Network( + n_input_dims=( + ( + self.direction_encoding.n_output_dims + if self.use_viewdirs + else 0 + ) + + self.geo_feat_dim + ), + n_output_dims=self.n_output_dim, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 2, + }, + ) + + def query_density(self, x, return_feat: bool = False): + if self.unbounded: + x = contract_to_unisphere(x, self.aabb) + else: + aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1) + x = (x - aabb_min) / (aabb_max - aabb_min) + selector = ((x > 0.0) & (x < 1.0)).all(dim=-1) + x = ( + self.mlp_base(x.view(-1, self.num_dim)) + .view(list(x.shape[:-1]) + [1 + self.geo_feat_dim]) + .to(x) + ) + density_before_activation, base_mlp_out = torch.split( + x, [1, self.geo_feat_dim], dim=-1 + ) + density = ( + self.density_activation(density_before_activation) + * selector[..., None] + ) + if return_feat: + return density, base_mlp_out + else: + return density + + def _query_rgb(self, dir, embedding, apply_act: bool = True): + # tcnn requires directions in the range [0, 1] + if self.use_viewdirs: + dir = (dir + 1.0) / 2.0 + d = self.direction_encoding(dir.reshape(-1, dir.shape[-1])) + h = torch.cat([d, embedding.reshape(-1, self.geo_feat_dim)], dim=-1) + else: + h = embedding.reshape(-1, self.geo_feat_dim) + rgb = ( + self.mlp_head(h) + .reshape(list(embedding.shape[:-1]) + [self.n_output_dim]) + .to(embedding) + ) + if apply_act: + rgb = self.radiance_activation(rgb) + + return rgb + + def forward( + self, + positions: torch.Tensor, + directions: torch.Tensor = None, + ): + if positions.shape[0] == 0: + density = torch.zeros(0, device=positions.device) + color = torch.zeros(0, 1200, device=positions.device) + return color, density + + if self.use_viewdirs and (directions is not None): + assert ( + positions.shape == directions.shape + ), f"{positions.shape} v.s. {directions.shape}" + density, embedding = self.query_density(positions, return_feat=True) + rgb = self._query_rgb(directions, embedding=embedding) + else: + density, embedding = self.query_density(positions, return_feat=True) + rgb = self._query_rgb(directions, embedding=embedding) + + return rgb, density # type: ignore + + +class NGPDensityField(torch.nn.Module): + """Instance-NGP Density Field used for resampling""" + + def __init__( + self, + aabb: Union[torch.Tensor, List[float]], + num_dim: int = 3, + density_activation: Callable = lambda x: trunc_exp(x - 1), + unbounded: bool = False, + base_resolution: int = 16, + max_resolution: int = 128, + n_levels: int = 5, + log2_hashmap_size: int = 17, + ) -> None: + super().__init__() + if not isinstance(aabb, torch.Tensor): + aabb = torch.tensor(aabb, dtype=torch.float32) + self.register_buffer("aabb", aabb) + self.num_dim = num_dim + self.density_activation = density_activation + self.unbounded = unbounded + self.base_resolution = base_resolution + self.max_resolution = max_resolution + self.n_levels = n_levels + self.log2_hashmap_size = log2_hashmap_size + + per_level_scale = np.exp( + (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1) + ).tolist() + + self.mlp_base = tcnn.NetworkWithInputEncoding( + n_input_dims=num_dim, + n_output_dims=1, + encoding_config={ + "otype": "HashGrid", + "n_levels": n_levels, + "n_features_per_level": 2, + "log2_hashmap_size": log2_hashmap_size, + "base_resolution": base_resolution, + "per_level_scale": per_level_scale, + }, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 1, + }, + ) + + def forward(self, positions: torch.Tensor): + if self.unbounded: + positions = contract_to_unisphere(positions, self.aabb) + else: + aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1) + positions = (positions - aabb_min) / (aabb_max - aabb_min) + selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1) + density_before_activation = ( + self.mlp_base(positions.view(-1, self.num_dim)) + .view(list(positions.shape[:-1]) + [1]) + .to(positions) + ) + density = ( + self.density_activation(density_before_activation) + * selector[..., None] + ) + return density + \ No newline at end of file diff --git a/codes/reconstruction/FlyingWithPhotons/requirements.txt b/codes/reconstruction/FlyingWithPhotons/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..55a8f2077df96843a39151e20567bbabbae54069 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/requirements.txt @@ -0,0 +1,23 @@ +# Install PyTorch 2.5.1 / CUDA 11.8 first; see README. +ConfigArgParse==1.7.5 +ImageIO==2.37.2 +PyYAML==6.0.3 +h5py==3.15.1 +imgviz==1.7.6 +lpips==0.1.4 +mat73==0.65 +matplotlib==3.10.7 +nerfacc==0.5.3 +numpy==1.26.4 +packaging==25.0 +pillow==12.0.0 +scikit-image==0.25.2 +scipy==1.15.3 +sparse==0.17.0 +tensorboard==2.10.1 +torch==2.5.1 +torchvision==0.20.1 +tqdm==4.67.1 + +# CUDA extensions (install after PyTorch; source build needs the CUDA toolchain). +tinycudann @ git+https://github.com/NVlabs/tiny-cuda-nn@38e50edc4a5f785afe0ef21f9c75b8949890be84#subdirectory=bindings/torch diff --git a/codes/reconstruction/FlyingWithPhotons/train_ours.py b/codes/reconstruction/FlyingWithPhotons/train_ours.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf4bf0a10b3175f01e52e58cfbcd32d78cc1e47 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/train_ours.py @@ -0,0 +1,257 @@ +import os +from loaders.streaming_loader import SubjectLoaderIterable +from loaders.regular_loader_our import SubjectLoader +from misc.summary import write_summary_histogram +import time +import numpy as np +import torch +import tqdm +from radiance_fields.ngp import NGPRadianceField +from torch.utils.tensorboard import SummaryWriter +import os +import torch.multiprocessing as mp +from multiprocessing import Value +from ctypes import c_longlong +from torch.utils.data import DataLoader +from nerfacc.estimators.occ_grid import OccGridEstimator + +from utils import ( + make_save_folder, + make_save_folder_final, + render_image_with_occgrid, + set_random_seed, + load_args + ) + +if mp.get_start_method(allow_none=True) is None: + mp.set_start_method('spawn') # or 'forkserver' + +def run(): + torch.cuda.empty_cache() + args = load_args() + device = args.device + set_random_seed(args.seed) + aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device) + train_dataset_kwargs = {} + test_dataset_kwargs = {} + + # Setup training dataset and loader. + if args.streaming: + num_rays_value = Value(c_longlong, args.init_batch_size) + counter = Value(c_longlong, 0) + + train_dataset = SubjectLoaderIterable( + root_fp=args.data_root, + split="train", + counter= counter, + num_rays = num_rays_value, + args = args, + **train_dataset_kwargs, + ) + train_data_loader = DataLoader(train_dataset, batch_size=None, num_workers=args.num_workers) + else: + train_dataset = SubjectLoader( + root_fp=args.data_root, + split="train", + num_rays = args.init_batch_size, + args = args, + **train_dataset_kwargs, + ) + train_data_loader = DataLoader(train_dataset, batch_size=None, num_workers=0) + + if args.summary: + test_dataset = SubjectLoader( + root_fp= args.data_root, + split="test", + num_rays=None, + args = args, + **test_dataset_kwargs, + ) + + estimator = OccGridEstimator( + roi_aabb=aabb, resolution=args.grid_resolution, levels=args.grid_nlvl + ).to(device) + + + # Setup the radiance field we want to train. + grad_scaler = torch.cuda.amp.GradScaler(2**10) + radiance_field = NGPRadianceField(aabb=estimator.aabbs[-1], radiance_activation=torch.nn.Sigmoid(), use_viewdirs=True, args=args) + radiance_field = radiance_field.to("cpu") + radiance_field = radiance_field.to(device) + + optimizer = torch.optim.Adam( + list(radiance_field.parameters()), lr=args.lr, eps=1e-15, weight_decay=args.weight_decay + ) + + scheduler = torch.optim.lr_scheduler.ChainedScheduler( + [ + torch.optim.lr_scheduler.LinearLR( + optimizer, start_factor=0.01, total_iters=100 + ), + torch.optim.lr_scheduler.MultiStepLR( + optimizer, + milestones=[ + args.max_steps // 2, + args.max_steps * 3 // 4, + args.max_steps * 9 // 10, + ], + gamma=0.33, + ), + ] + ) + + # Make save folder. + if args.final: + writer, step, outpath = make_save_folder_final(args, optimizer, scheduler, radiance_field, estimator) + args.outpath = outpath + else: + outpath = make_save_folder(args) + args.outpath = outpath + writer = SummaryWriter(log_dir=outpath) + step = 0 + + + import sys + from pathlib import Path + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from evaluation.units import record_training_units + record_training_units(outpath, args.dataset_scale, args.gamma, + Path(args.data_root)/"transforms_train.json", "FlyingWithPhotons", + measurement_root=getattr(args, 'measurement_root', None), + intrinsics=getattr(args, 'intrinsics_path', None)) + + # Training. + tic = time.time() + pbar = tqdm.tqdm(total=args.max_steps) + + while step < args.max_steps: + for data in train_data_loader: + + pbar.update(1) + + radiance_field.train() + estimator.train() + + render_bkgd = data["color_bkgd"] + rays = data["rays"] + pixels = data["pixels"] + valid_mask = data["valid_mask"].reshape(-1).to(device=device, dtype=torch.bool) + #检测pixels的最大值 + if step == 0: + print("debug:pixels max:",pixels.max()) + print("debug:pixels mean:",pixels.mean()) + + def occ_eval_fn(x): + density = radiance_field.query_density(x) + return density * args.render_step_size + + # Warmup occupancy threshold. + if args.version == "captured": + if step 0: + # Dynamic batch size for rays to keep sample batch size constant. + num_rays = len(pixels) + num_rays = int( + num_rays * (args.target_sample_batch_size / float(n_rendering_samples)) + ) + if args.streaming: + with num_rays_value.get_lock(): + num_rays_value.value = num_rays + else: + train_dataset.update_num_rays(num_rays) + + rgb_reshaped = rgb.reshape(rgb.shape[0], args.n_bins, -1) + supervised_ratio = valid_mask.float().mean() + if valid_mask.any(): + loss = torch.nn.functional.smooth_l1_loss( + rgb_reshaped[valid_mask], + pixels[valid_mask], + ) + else: + loss = rgb_reshaped.sum() * 0.0 + + optimizer.zero_grad() + + # Double grad scaler to avoid nans and rescale loss. + grad_scaler.scale(grad_scaler.scale(loss)).backward() + grad_scaler.step(optimizer) + scheduler.step() + grad_scaler.update() + step += 1 + writer.add_scalar('Loss/train', torch.log(loss.clamp_min(1e-12)).detach().cpu().numpy(), step) + writer.add_scalar('Mask/supervised_ratio', supervised_ratio.detach().cpu().item(), step) + + if step % args.summary_freq == 0: + elapsed_time = time.time() - tic + if valid_mask.any(): + mse = torch.nn.functional.mse_loss( + rgb_reshaped[valid_mask], + pixels[valid_mask], + ) + psnr = -10.0 * torch.log(mse) / np.log(10.0) + psnr_value = float(psnr.detach().cpu().item()) + else: + mse = rgb_reshaped.sum() * 0.0 + psnr_value = float("nan") + #提取acc的统计信息 + acc_max = acc.max().item() if acc.numel() > 0 else 0.0 + acc_mean = acc.mean().item() if acc.numel() > 0 else 0.0 + + print( + f"elapsed_time={elapsed_time:.2f}s | step={step} | " + f"loss={loss:.5f} | transient psnr={psnr_value:.2f} | " + f"supervised_ratio={supervised_ratio.item():.4f} | " + f"n_rendering_samples={n_rendering_samples:d} | num_rays={len(pixels):d} | " + f"max_depth={depth.max():.3f} | " + f"acc_max={acc_max:.4f} | acc_mean={acc_mean:.4f} | " + ) + + if args.summary: + write_summary_histogram(radiance_field, estimator, writer, test_dataset, step, args) + + + if not step % args.steps_till_checkpoint or step == args.max_steps: + torch.save(radiance_field.state_dict(), os.path.join(outpath, 'radiance_field_%04d.pth' % (step))) + torch.save(estimator.state_dict(), os.path.join(outpath, 'occupancy_grid_%04d.pth' % (step))) + torch.save(optimizer.state_dict(), os.path.join(outpath, 'optimizer_%04d.pth' % (step))) + torch.save(scheduler.state_dict(), os.path.join(outpath, 'scheduler_%04d.pth' % (step))) + torch.save({'step': step}, os.path.join(outpath, 'variables.pth')) + + + if step >= args.max_steps: + break + + +if __name__=="__main__": + run() diff --git a/codes/reconstruction/FlyingWithPhotons/utils.py b/codes/reconstruction/FlyingWithPhotons/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..12ff8e45441bf47a466abcea17652656d0970054 --- /dev/null +++ b/codes/reconstruction/FlyingWithPhotons/utils.py @@ -0,0 +1,893 @@ +from datetime import datetime +import random +from typing import Optional +import ast +import configargparse +import os +import numpy as np +import torch +from loaders.utils import Rays, namedtuple_map +from nerfacc.estimators.occ_grid import OccGridEstimator +from nerfacc.grid import ray_aabb_intersect, traverse_grids +from misc.transient_volrend import ( + accumulate_along_rays_, + render_weight_from_density, + rendering, + shift_transient_grid_sample_3d, +) +from torch.utils.tensorboard import SummaryWriter +import shutil + + +def set_random_seed(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + +def render_image_with_occgrid( + # scene + radiance_field: torch.nn.Module, + estimator: OccGridEstimator, + rays: Rays, + args = None, + # rendering options + near_plane: float = 0.0, + far_plane: float = 1e10, + render_step_size: float = 1e-3, + render_bkgd: Optional[torch.Tensor] = None, + cone_angle: float = 0.0, + alpha_thre: float = 0.0, + # test options + test_chunk_size: int = 8192, + # only useful for dnerf + timestamps: Optional[torch.Tensor] = None, + step = -1 +): + + rendering_func = rendering + def rgb_sigma_fn(t_starts, t_ends, ray_indices): + t_origins = chunk_rays.origins[ray_indices] + t_dirs = chunk_rays.viewdirs[ray_indices] + positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0 + if timestamps is not None: + # dnerf + t = ( + timestamps[ray_indices] + if radiance_field.training + else timestamps.expand_as(positions[:, :1]) + ) + rgbs, sigmas = radiance_field(positions, t, t_dirs) + else: + rgbs, sigmas = radiance_field(positions, t_dirs) + + return rgbs, sigmas.squeeze(-1) + + """Render the pixels of an image.""" + rays_shape = rays.origins.shape + if len(rays_shape) == 3: + height, width, _ = rays_shape + num_rays = height * width + rays = namedtuple_map( + lambda r: r.reshape([num_rays] + list(r.shape[2:])), rays + ) + else: + num_rays, _ = rays_shape + + def sigma_fn(t_starts, t_ends, ray_indices): + t_origins = chunk_rays.origins[ray_indices] + t_dirs = chunk_rays.viewdirs[ray_indices] + positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0 + if timestamps is not None: + # dnerf + t = ( + timestamps[ray_indices] + if radiance_field.training + else timestamps.expand_as(positions[:, :1]) + ) + sigmas = radiance_field.query_density(positions, t) + else: + sigmas = radiance_field.query_density(positions) + return sigmas.squeeze(-1) + + results = [] + chunk = ( + torch.iinfo(torch.int32).max + if radiance_field.training + else test_chunk_size + ) + for i in range(0, num_rays, chunk): + chunk_rays = namedtuple_map(lambda r: r[i : i + chunk], rays) + # 假设 estimator.aabbs 是场景包围盒 + t_mins_chunk, _, hits_chunk = ray_aabb_intersect(chunk_rays.origins, chunk_rays.viewdirs, estimator.aabbs) + ray_indices, t_starts, t_ends = estimator.sampling( + chunk_rays.origins, + chunk_rays.viewdirs, + sigma_fn=sigma_fn, + near_plane=near_plane, + far_plane=far_plane, + render_step_size=render_step_size, + stratified=radiance_field.training, + cone_angle=cone_angle, + alpha_thre=alpha_thre, + ) + rgb, opacity, depth, _ = rendering_func( + t_starts, + t_ends, + ray_indices, + args = args, + n_rays=chunk_rays.origins.shape[0], + rgb_sigma_fn=rgb_sigma_fn, + render_bkgd=render_bkgd, + t_mins=t_mins_chunk[ray_indices], + step=step + ) + chunk_results = [rgb, opacity, depth, len(t_starts)] + results.append(chunk_results) + colors, opacities, depths, n_rendering_samples = [ + torch.cat(r, dim=0) if isinstance(r[0], torch.Tensor) else r + for r in zip(*results) + ] + return ( + colors.view((*rays_shape[:-1], -1)), + opacities.view((*rays_shape[:-1], -1)), + depths.view((*rays_shape[:-1], -1)), + sum(n_rendering_samples), + ) + +@torch.no_grad() +def render_image_with_occgrid_test( + max_samples: int, + # scene + radiance_field: torch.nn.Module, + estimator: OccGridEstimator, + rays: Rays, + args = None, + # rendering options + near_plane: float = 0.0, + far_plane: float = 1e10, + render_step_size: float = 1e-3, + render_bkgd: Optional[torch.Tensor] = None, + cone_angle: float = 0.0, + alpha_thre: float = 0.0, + early_stop_eps: float = 1e-4, + # only useful for dnerf + timestamps: Optional[torch.Tensor] = None, + n_output_dim = 3, + prop_delay = True, + unwarp = False, + test_chunk_size = 20000 +): + """Render the pixels of an image.""" + rays_shape = rays.origins.shape + if len(rays_shape) == 3: + height, width, _ = rays_shape + num_rays = height * width + rays = namedtuple_map( + lambda r: r.reshape([num_rays] + list(r.shape[2:])), rays + ) + else: + num_rays, _ = rays_shape + + def rgb_sigma_fn(t_starts, t_ends, ray_indices): + t_origins = rays.origins[ray_indices] + t_dirs = rays.viewdirs[ray_indices] + positions = ( + t_origins + t_dirs * (t_starts[:, None] + t_ends[:, None]) / 2.0 + ) + if timestamps is not None: + # dnerf + t = ( + timestamps[ray_indices] + if radiance_field.training + else timestamps.expand_as(positions[:, :1]) + ) + rgbs, sigmas = radiance_field(positions, t, t_dirs) + else: + rgbs, sigmas = radiance_field(positions, t_dirs) + + return rgbs, sigmas.squeeze(-1) + + device = rays.origins.device + opacity = torch.zeros(num_rays, 1, device=device) + depth = torch.zeros(num_rays, 1, device=device) + rgb = torch.zeros(num_rays, n_output_dim, device=device) + + ray_mask = torch.ones(num_rays, device=device).bool() + + # 1 for synthetic scenes, 4 for real scenes + min_samples = 1 if cone_angle == 0 else 4 + + iter_samples = total_samples = 0 + + rays_o = rays.origins + rays_d = rays.viewdirs + + near_planes = torch.full_like(rays_o[..., 0], fill_value=near_plane) + far_planes = torch.full_like(rays_o[..., 0], fill_value=far_plane) + + t_mins, t_maxs, hits = ray_aabb_intersect(rays_o, rays_d, estimator.aabbs) + + n_grids = estimator.binaries.size(0) + + if n_grids > 1: + t_sorted, t_indices = torch.sort(torch.cat([t_mins, t_maxs], -1), -1) + else: + t_sorted = torch.cat([t_mins, t_maxs], -1) + t_indices = torch.arange( + 0, n_grids * 2, device=t_mins.device, dtype=torch.int64 + ).expand(num_rays, n_grids * 2) + + opc_thre = 1 - early_stop_eps + + while iter_samples < max_samples: + + n_alive = ray_mask.sum().item() + if n_alive == 0: + break + + # The number of samples to add on each ray. + n_samples = max(min(num_rays // n_alive, 64), min_samples) + iter_samples += n_samples + + # ray marching + (intervals, samples, termination_planes) = traverse_grids( + # rays + rays_o, # [n_rays, 3] + rays_d, # [n_rays, 3] + # grids + estimator.binaries, # [m, resx, resy, resz] + estimator.aabbs, # [m, 6] + # options + near_planes, # [n_rays] + far_planes, # [n_rays] + render_step_size, + cone_angle, + n_samples, + True, + ray_mask, + # pre-compute intersections + t_sorted, # [n_rays, m*2] + t_indices, # [n_rays, m*2] + hits, # [n_rays, m] + ) + t_starts = intervals.vals[intervals.is_left] + t_ends = intervals.vals[intervals.is_right] + ray_indices = samples.ray_indices[samples.is_valid] + packed_info = samples.packed_info + + # Get rgb and sigma from radiance field. + rgbs, sigmas = rgb_sigma_fn(t_starts, t_ends, ray_indices) + if rgbs.shape[0] != 0: + if prop_delay: + shift = (t_starts + t_ends)[:, None]/ 2.0 + #更改为减去相机到AABB的最小距离 + #shift = (t_starts + t_ends)[:, None] - 2.0*t_mins[ray_indices] + rgbs = rgbs.reshape(rgbs.shape[0], args.n_bins, -1) + chunk_size = test_chunk_size + for chunk_number in range(0, rgbs.shape[0], chunk_size): + chunk = rgbs[chunk_number : chunk_number + chunk_size] + chunk_d = shift[chunk_number : chunk_number + chunk_size] + rgbs[chunk_number : chunk_number + chunk_size] = shift_transient_grid_sample_3d(chunk, chunk_d, args.exposure_time, args.n_bins) + + rgbs = rgbs.reshape(rgbs.shape[0], -1) + + # Volume rendering using native cuda scan. + weights, _, alphas = render_weight_from_density( + t_starts, + t_ends, + sigmas, + ray_indices=ray_indices, + n_rays=num_rays, + prefix_trans=1 - opacity[ray_indices].squeeze(-1), + ) + if alpha_thre > 0: + vis_mask = alphas >= alpha_thre + ray_indices, rgbs, weights, t_starts, t_ends = ( + ray_indices[vis_mask], + rgbs[vis_mask], + weights[vis_mask], + t_starts[vis_mask], + t_ends[vis_mask], + ) + + accumulate_along_rays_( + weights, + values=rgbs, + ray_indices=ray_indices, + outputs=rgb, + ) + accumulate_along_rays_( + weights, + values=None, + ray_indices=ray_indices, + outputs=opacity, + ) + accumulate_along_rays_( + weights, + values=(t_starts + t_ends)[..., None] / 2.0, + ray_indices=ray_indices, + outputs=depth, + ) + # Update near_planes using termination planes. + near_planes = termination_planes + # Update rays status. + ray_mask = torch.logical_and( + # Early stopping. + opacity.view(-1) <= opc_thre, + # Remove rays that have reached the far plane. + packed_info[:, 1] == n_samples, + ) + total_samples += ray_indices.shape[0] + + depth = depth / opacity.clamp_min(torch.finfo(rgbs.dtype).eps) + + # Unwapring different methods -- values hardocded. + if unwarp: + if args.unwarp_method == "depth": + dists = depth + elif args.unwarp_method == "sphere": + dists = intersect_sphere(rays.origins.cpu(), rays.viewdirs.cpu(), np.sqrt(2)).to(depth.device) + elif args.unwarp_method == "cube": + dists = intersect_cube(rays.origins.cpu(), rays.viewdirs.cpu(), 1).to(depth.device) + + chunk_size = test_chunk_size + for chunk_number in range(0, rgb.shape[0], chunk_size): + chunk = rgb[chunk_number : chunk_number + chunk_size] + chunk_d = dists[chunk_number : chunk_number + chunk_size] + rgb[chunk_number : chunk_number + chunk_size] = depth_unwarp(chunk.reshape(chunk.shape[0], args.n_bins, -1), chunk_d, args.exposure_time, args.n_bins).reshape(chunk.shape[0], -1) + + + return ( + rgb.view((*rays_shape[:-1], -1)), + opacity.view((*rays_shape[:-1], -1)), + depth.view((*rays_shape[:-1], -1)), + total_samples, + ) + + +def intersect_sphere(rays_o, rays_d, R): + # Intersection of rays with sphere, distances. + odotd = torch.sum(rays_o*rays_d, 1) + d_norm_sq = torch.sum(rays_d**2, 1) + o_norm_sq = torch.sum(rays_o**2, 1) + determinant = odotd**2+(R-o_norm_sq)*d_norm_sq + valid = determinant>=0 + distances = torch.zeros(rays_o.shape[0]) + distances[valid] = (torch.sqrt(determinant[valid])-odotd[valid])/d_norm_sq[valid] + return distances[:, None] + +def intersect_cube(rays_o, rays_d, R): + # Intersection of rays with cube, distances. + t1 = (R - rays_o)/rays_d + t2 = (-R - rays_o)/rays_d + combined_mins = torch.concat([t1, t2], dim=-1) + dists = torch.topk(combined_mins, 3, dim=1)[0][:, 2][:, None] + return dists + + +def parse_list(arg): + try: + return ast.literal_eval(arg) + except (SyntaxError, ValueError): + raise configargparse.ArgumentTypeError(f"Invalid list format: {arg}") + +def depth_unwarp(transient, depth, exposure_time, n_bins): + # Depth based unwapring. + x_dim = transient.shape[0] + bins_move = depth/exposure_time + if x_dim%2 == 0: + x = (torch.arange(x_dim, device=transient.device)-x_dim//2+0.5)/(x_dim//2-0.5) + else: + x = (torch.arange(x_dim, device=transient.device)-x_dim//2)/(x_dim//2) + + z = torch.arange(n_bins, device=transient.device).float() + X, Z = torch.meshgrid(x, z, indexing="ij") + Z = Z + bins_move + Z[Z<0] = n_bins+1 + Z = (Z-n_bins//2+0.5)/(n_bins//2-0.5) + grid = torch.stack((Z, X), dim=-1)[None, ...] + shifted_transient = torch.nn.functional.grid_sample(transient.permute(2, 0, 1)[None], grid, align_corners=True).squeeze(0).permute(1, 2, 0) + return shifted_transient + +def str2bool(v): + if isinstance(v, bool): + return v + if v.lower() in ('yes', 'true', 't', 'y', '1'): + return True + elif v.lower() in ('no', 'false', 'f', 'n', '0'): + return False + else: + raise configargparse.ArgumentTypeError('Boolean value expected.') + + +def get_meas_peak_threshold(args): + meas_peak_min = float(getattr(args, "meas_peak_min", 0.0)) + if meas_peak_min <= 0: + return None + dataset_scale = max(float(getattr(args, "dataset_scale", 1.0)), 1e-8) + return meas_peak_min / dataset_scale + + +def compute_transient_valid_mask_torch(transient, args, base_mask=None, undo_gamma=False): + channel = transient[..., 0] + if undo_gamma: + gamma = float(getattr(args, "gamma", 1.0)) + if gamma != 1.0: + channel = channel.clamp_min(0.0).pow(gamma) + + signal_mask = channel.sum(dim=-1) > 0 + peak_threshold = get_meas_peak_threshold(args) + if peak_threshold is None: + meas_peak_mask = torch.ones_like(signal_mask, dtype=torch.bool) + else: + meas_peak_mask = torch.amax(channel, dim=-1) >= float(peak_threshold) + + valid_mask = signal_mask & meas_peak_mask + if base_mask is not None: + valid_mask = valid_mask & base_mask.to(dtype=torch.bool, device=valid_mask.device) + return valid_mask, meas_peak_mask, signal_mask + + +def compute_transient_valid_mask_numpy(transient, args, base_mask=None): + channel = transient[..., 0] + signal_mask = channel.sum(axis=-1) > 0 + peak_threshold = get_meas_peak_threshold(args) + if peak_threshold is None: + meas_peak_mask = np.ones_like(signal_mask, dtype=bool) + else: + meas_peak_mask = np.max(channel, axis=-1) >= float(peak_threshold) + + valid_mask = signal_mask & meas_peak_mask + if base_mask is not None: + valid_mask = valid_mask & np.asarray(base_mask, dtype=bool) + return valid_mask, meas_peak_mask, signal_mask + + + + +def load_args(eval = False, parser= None): + if not eval: + parser = configargparse.ArgumentParser() + parser.add('-c', '--my-config', + is_config_file=True, + default=None, + help='Path to config file.' + ) + parser.add_argument( + '--exp_name', + type=str, + default='coke', + help='Experiment name.' + ) + parser.add_argument( + "--prop_delay", + type= str2bool, + default="true", + help="Model propagation delay.", + ) + parser.add_argument( + "--data_root", + type=str, + default="/home/anagh/PycharmProjects/multiview_lif/data/regular-cornell/diverse_cams/training_files", + help="The root of the dataset directory.", + ) + parser.add_argument( + "--num_workers", + type=int, + default=2, + help="Number of workers.", + ) + parser.add_argument( + "--final", + type= str2bool, + default="false", + help="Train final version or not.", + ) + parser.add_argument( + "--streaming", + type= str2bool, + default="true", + help="Stream with dataloader.", + ) + parser.add_argument( + "--version", + type=str, + default="simulated", + choices=["captured", "simulated"], + help="Dataset being trained, captured or simulated.", + ) + parser.add_argument( + "--outpath", + type=str, + default="/home/anagh/PycharmProjects/multiview_lif/results", + help="Path to results folder.", + ) + parser.add_argument( + "--n_bins", + type=int, + default=700, + help="Number of bins.", + ) + parser.add_argument( + "--exposure_time", + type=float, + default=0.01, + help="Exposure time per bin.", + ) + parser.add_argument( + "--steps_till_checkpoint", + type=int, + default=5000, + help="Number of steps till checkpoint saved.", + ) + parser.add_argument( + "--summary_freq", + type=int, + default=5000, + help="Number of steps till summary logged.", + ) + parser.add_argument( + "--max_steps", + type=int, + default=200000, + help="Total number of steps trained for.", + ) + parser.add_argument( + "--alpha_thre", + type=float, + default=0, + help="Alpha threshold for skipping empty space.", + ) + parser.add_argument( + "--lr", + type=float, + default=0.005, + help="Learning rate.", + ) + parser.add_argument( + "--weight_decay", + type=float, + default=1e-6, + help="Weight decay value for optimizer.", + ) + parser.add_argument( + "--render_step_size", + type=float, + default=5e-3, + help="Step size in rendering.", + ) + parser.add_argument( + "--cone_angle", + type=float, + default=0, + help="Cone angle for linearly increased step size.", + ) + parser.add_argument( + "--target_sample_batch_size", + type=int, + default=2**16, + help="Number of points per batch.", + ) + parser.add_argument( + "--near_plane", + type=float, + default=0, + help="Near plane for sampling.", + ) + parser.add_argument( + "--gamma", + type=int, + default=2, + help="Near plane for sampling.", + ) + parser.add_argument( + "--far_plane", + type=float, + default=2**15, + help="Far plane for sampling.", + ) + parser.add_argument( + "--dataset_scale", + type=int, + default=46, + # default=(5.5*10**6), + help="Scale for all transient images.", + ) + parser.add_argument( + "--meas_peak_min", + type=float, + default=10.0, + help="Minimum GT transient peak (in pre-normalization units) required for supervision/evaluation.", + ) + parser.add_argument( + "--t_min", + type=int, + default=200, + help="Time to start bins at.", + ) + parser.add_argument( + "--t_max", + type=int, + default=800, + help="Time to end bins at.", + ) + parser.add_argument( + "--init_batch_size", + type=int, + default=32, + help="Starting batch size.", + ) + parser.add_argument( + "--seed", + type=int, + default=42, + help="Starting batch size.", + ) + parser.add_argument( + "--occ_thre", + type=float, + default=0.01, + help="Occupancy threshold", + ) + parser.add_argument( + "--thold_warmup", + type=int, + default=-1, + help="Warmup period for the occupancy threshold.", + ) + parser.add_argument( + "--grid_resolution", + type=int, + default=128, + help="Starting batch size.", + ) + parser.add_argument( + "--grid_nlvl", + type=int, + default=1, + help="Starting batch size.", + ) + parser.add_argument( + "--img_shape", + type=int, + default=64, + help="Image shape.", + ) + parser.add_argument( + "--summary", + type= str2bool, + default="true", + help="Print tensorboard summary.", + ) + parser.add_argument( + "--img_shape_test", + type=int, + default=64, + help="Image shape for summary.", + ) + parser.add_argument( + "--aabb", + nargs='+', + type = lambda s: ast.literal_eval(s), + default="[-1.5,-1.5,-1.5,1.5,1.5, 1.5]", + help="AABB size.", + ) + parser.add_argument( + "--laser_pos", + nargs='+', + type = lambda s: ast.literal_eval(s), + default=[(16, 16), (20, 16), (28, 25)], + help="Laser position.", + ) + parser.add_argument( + "--pixels_to_plot", + nargs='+', + type = lambda s: ast.literal_eval(s), + default=[(16, 16), (20, 16), (28, 25)], + help="Pixels used for plotting in the summary.", + ) + parser.add_argument( + "--img_scale", + type=int, + default=100, + help="Image scale used in summary.", + ) + parser.add_argument( + "--device", + type=str, + default="cuda:4", + help="Cuda device.", + ) + #add other params + parser.add_argument( + "--measurement_root", + type=str, + default="/work/runrong/dataset/paper1_data/chair_dinasour/without_occlusion/h5/", + help="root data", + ) + parser.add_argument( + "--depth_global_offset_bins", + type=int, + default=0, + help="global shift", + ) + parser.add_argument( + "--depth_offset_map", + type=str, + default="/work/runrong/project_all/FlyingWithPhotons/ini_generate/offset.txt" + ) + parser.add_argument( + "--depth_offset_valid_max", + type=float, + default=10.0, + ) + parser.add_argument( + "--img_height", + type=int, + default=192, + ) + parser.add_argument( + "--img_width", + type=int, + default=256, + ) + parser.add_argument( + "--img_height_test", + type=int, + default=192, + ) + parser.add_argument( + "--img_width_test", + type=int, + default=256, + ) + parser.add_argument( + "--fx", + type=float, + default=118.6514575329715, + help="Focal length x" + ) + parser.add_argument( + "--fy", + type=float, + default=118.7964934010577, + help="Focal length y" + ) + parser.add_argument( + "--cx", + type=float, + default=130.6802784645003, + help="Principal point x" + ) + parser.add_argument( + "--cy", + type=float, + default=100.360570246814, + help="Principal point y" + ) + parser.add_argument( + "--view_time_align", + type=str2bool, + default="false", + help="Apply per-view global bin alignment in data preprocessing.", + ) + parser.add_argument( + "--view_time_align_quantile", + type=float, + default=0.7, + help="Quantile used to select strong pixels when estimating per-view peak bin.", + ) + parser.add_argument( + "--view_time_align_target_bin", + type=int, + default=-1, + help="Target bin for alignment. If < 0, use median peak bin from available frames.", + ) + parser.add_argument( + "--view_time_align_max_abs_bins", + type=int, + default=96, + help="Clamp per-view global bin offset to [-max_abs, max_abs].", + ) + parser.add_argument( + "--hardware_shift", + type=str2bool, + default="false", + help="Apply hardware shift from intrinsics.npy in preprocessing.", + ) + parser.add_argument( + "--hardware_shift_downsample", + type=int, + default=1, + help="Downsample factor for low-pass filtering hardware shift before resizing back.", + ) + parser.add_argument( + "--hardware_shift_max_abs_bins", + type=float, + default=-1.0, + help="Optional clamp for hardware shift in bins. Negative disables clamping.", + ) + parser.add_argument( + "--intrinsics_path", + type=str, + default="/work/runrong/project_all/FlyingWithPhotons/ini_generate/intrinsics.npy", + help="Path to intrinsics.npy containing per-pixel shift.", + ) + # args, _ = parser.parse_known_args() + args = parser.parse_args() + assert args.n_bins == args.t_max - args.t_min + return args + +def make_save_folder(args): + now = datetime.now() + now = now.strftime("%m-%d_%H:%M:%S") + exp_name = args.exp_name + "_" + now + outpath = os.path.join(args.outpath, exp_name) + os.mkdir(outpath) + shutil.copy(args.my_config, os.path.join(outpath, "params.txt")) + + with open(os.path.join(outpath, "params_full.txt"), "w") as out_file: + param_list = [] + for key, value in vars(args).items(): + if type(value) == list: + value = [eval(f"{x}") for x in value] + elif type(value) != int and type(value) != float: + value = str(value) + value = f"'{value}'" + param_list.append("%s= %s" % (key, value)) + + out_file.write('\n'.join(param_list)) + return outpath + +def make_save_folder_final(args, optimizer, scheduler, radiance_field, occupancy_grid): + outpath = os.path.join(args.outpath, args.exp_name) + + if not os.path.isdir(outpath): + + os.mkdir(outpath) + shutil.copy(args.my_config, os.path.join(outpath, "params.txt")) + + + with open(os.path.join(outpath, "params_full.txt"), "w") as out_file: + param_list = [] + for key, value in vars(args).items(): + if type(value) != int and type(value) != float: + value = str(value) + value = f"'{value}'" + param_list.append("%s= %s" % (key, value)) + + out_file.write('\n'.join(param_list)) + step = 0 + writer = SummaryWriter(log_dir=outpath) + + else: + ckpt_path_var = os.path.join(outpath, 'variables.pth') + ckpt = torch.load(ckpt_path_var) + step = ckpt['step'] + + ckpt_path_rf = os.path.join(outpath, 'radiance_field_%04d.pth' % (step)) + ckpt_path_oc = os.path.join(outpath, 'occupancy_grid_%04d.pth' % (step)) + ckpt_path_opt = os.path.join(outpath, 'optimizer_%04d.pth' % (step)) + ckpt_path_sch = os.path.join(outpath, 'scheduler_%04d.pth' % (step)) + + ckpt = torch.load(ckpt_path_rf, map_location=args.device) + radiance_field.load_state_dict(ckpt) + radiance_field = radiance_field.to(args.device) + + ckpt = torch.load(ckpt_path_oc, map_location=args.device) + occupancy_grid.load_state_dict(ckpt) + occupancy_grid = occupancy_grid.to(args.device) + + ckpt = torch.load(ckpt_path_opt) + optimizer.load_state_dict(ckpt) + + ckpt = torch.load(ckpt_path_sch) + scheduler.load_state_dict(ckpt) + print(f"previous checkpoint loaded; current step: {step}") + writer = SummaryWriter(log_dir=outpath) + + return writer, step, outpath + +if __name__=="__main__": + pass diff --git a/codes/reconstruction/README.md b/codes/reconstruction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..862e53ce4f4b43dac77b4fc7854141b528b5aad7 --- /dev/null +++ b/codes/reconstruction/README.md @@ -0,0 +1,15 @@ +# STB 三方法最小项目:统一评价入口 + +本目录的 trnerf、FlyingWithPhotons、transientangelo 都保留各自训练模型代码;每份独立项目只有一个公开评价入口 `eval.py`,原来的两个 `shared_*` 目录已合并为 `evaluation/`。 + +三份 `eval.py` 与 evaluation 内的八个公共模块逐文件相同;`renderer.py` 和渲染参数解析仅适配各方法的模型与采样。没有旧 benchmark 评分开关,也不再使用 `evaluate_metrics_shared.py`、`eval_ours.py` 或 `launch.py --test`。 + +- `python eval.py render ...`:从实际 checkpoint 渲染并使用共同 V4 评分。 +- `python eval.py saved ...`:对未裁剪预测直方图复算,调用完全相同的评分器。 +- 各子项目 README 提供运行命令、训练归一化记录的要求,以及 Q6–Q8 的具体解释。 + +本次重构保持当前 V4 的计数域直方图 PSNR、共同 GT/掩码、固定场景峰值及图像指标定义。三种方法的原生采样逻辑保留;所有默认正式评价均为 30 次前向。历史论文结果尚未通过这次整理重算。 + +验证包括三项目导入/配置、单位与 gamma 回归、渲染平均一致性、统一 CLI、Lightning 测试回调,以及真实 film_box 单视角预测的重构前后逐项比较(直方图 PSNR 均为 40.35125958084842 dB)。不是三个不同模型得到了同一分数,而是同一预测经过三份共同评价实现得到相同结果。没有进行完整重训或九场景全量模型测试。 + +上一版代码与验证记录位于 `/work/runrong/project_all/stb_evaluation_merge_backup_20261017`,不放进可上传的代码包。数据、标定、权重与共同参考缓存仍在原外部位置;迁移时必须设置对应路径并使用同一个 `STB_METRICS_PYTHON` 环境。 diff --git a/codes/reconstruction/transientangelo/.gitignore b/codes/reconstruction/transientangelo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6107427c6ea2f841b6eb0ac6c8b4886c2ba04a85 --- /dev/null +++ b/codes/reconstruction/transientangelo/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.pyc +results/ +exp/ +runs/ +*.pth +*.ckpt diff --git a/codes/reconstruction/transientangelo/README.md b/codes/reconstruction/transientangelo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5d1a7d69bda3a81f07c359dd3e10b81d953dd93e --- /dev/null +++ b/codes/reconstruction/transientangelo/README.md @@ -0,0 +1,73 @@ +# transientangelo 最小复现版 + +保留原生训练、模型与采样代码;共同指标集中在 `evaluation/`,唯一评价入口为 `eval.py`。 + +在项目根目录执行;服务器模型解释器为 `/work/runrong/.conda/envs/transientangelo/bin/python`: + +```bash +export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python +python launch.py --config configs/captured.yaml --gpu 0 --train +python eval.py render --config configs/captured.yaml --gpu 0 \ + --resume /absolute/model.ckpt --output /absolute/new_result_directory +``` + +不再使用 `launch.py --test`。Lightning 的 test_step 只渲染直方图并交给共同评价器;单 GPU 训练结束后的测试也调用同一流程。正式评价使用一张 GPU 处理完整测试集合;多 GPU 训练结束后单独运行上述 eval.py 命令。 + +历史 checkpoint 没有训练尺度记录时,追加 `dataset.image_metric_training_scale=已核实的实际训练常数`。禁止填入测试最大值。 + +示例为 design_floor1 / 10 视角;参数模板来自原 designbuilding1 配置,不代表论文完整历史配置。更换场景或 3/5 视角时需修改相应训练参数与位姿路径。目录保持原 datasets/models/systems/utils 布局;模型、损失和原生测试采样规则保留。 + +## 共同评价协议(V4) + +`eval.py` 是唯一公开评价入口,`render` 和 `saved` 最终均调用 `evaluation/evaluator.py`。`evaluation/renderer.py` 仅适配本方法的模型和射线采样;直方图和图像指标实现与其他两个项目相同。原来的两个 `shared_*` 包、`evaluate_metrics_shared.py`、FWP 的 `eval_ours.py` 和独立旧评分分支已移除。 + +### 强度尺度与直方图 PSNR + +评分前逐 bin 恢复全曝光光子计数: + +``` +trnerf / transientangelo: prediction_counts = prediction_encoded * actual_training_scale +FlyingWithPhotons: prediction_counts = prediction_encoded ** training_gamma * dataset_scale +reference_counts: 共同参考缓存中的已标定、未独立归一化的光子计数 +MSE = mean((prediction_counts - reference_counts)^2) # 共同有效像素的全部 bins / channels +histogram_psnr = 20*log10(P_scene) - 10*log10(MSE) +``` + +`P_scene` 固定于同一场景的十视角训练候选池,在三种方法及 3/5/10 视角配置之间共用。预测峰值、测试最大值和每视角拟合系数都不用于确定它。预测直方图不做上限裁剪、显示 gamma 或曝光拟合;FWP 的逆训练 gamma 在积分前逐 bin 执行。缺失实际训练尺度时直接报错,禁止用测试集最大值代替。TN/FWP 新训练会记录 `image_metric_normalization.json`;TA 将训练尺度写入 checkpoint。历史权重须提供经过核实的训练常数,代码不能从测试集推断它。 + +共同参考由校准后全计数 GT 生成;掩码为硬件有效像素、GT 峰值 ≥100、正信号的交集,独立于预测。直方图峰值 `P_scene` 与积分图像尺度 `D_scene` 是两个不同的固定量。显示图像 PSNR、SSIM、LPIPS 沿用整理前 V4 所采用的显示变换,另报无显示 gamma 的 `linear_psnr`。这些图像分数不应标成直方图 PSNR。SSIM 使用完整有效 7×7 窗口;LPIPS 使用统一环境的 VGG v0.1 / FP32。 + +### 对 Q6–Q8 的代码说明 + +- **Q6:不是未经修改的发布版 eval.py。** 当前只提供统一 V4;取消旧 `scale_int` 和动态预测/GT 峰值评分。GT、掩码、固定场景尺度来自同一份 contract。原生测试均执行 30 次前向:TN 每次重新获取带抖动射线,TA 复用同一抖动批次,FWP 复用像素射线。因此不能把三者概括为“30 次独立像素抖动”。这些方法自身的采样逻辑保留。 +- **Q7:内部归一化不直接作为比较尺度。** TN/TA 预测乘回实际训练常数;FWP 逐 bin 逆训练 gamma 并乘回训练 dataset_scale;共同 GT 直接使用计数。测试加载器内部即使独立归一化,也不会把它的归一化 GT 或最大值用于评分。这解决当前流程中由训练/测试独立归一化引入的比较尺度不一致。 +- **Q8:三种视角设置均使用共同的 canonical test.json 帧及原始位姿。** 九场景合计 158 帧,逐场景 contract 强制核对完整唯一帧集合及位姿,拒绝只评部分帧或同名不同位姿。低视角下剩余训练候选帧不额外加入测试;十视角候选池仍用于冻结共同评价尺度,属于评价标定数据,不作为低视角方法的额外训练输入。 + +以上描述的是修订后的代码协议,不能用来证明历史论文分数已经重算。此次目录整理没有重新训练模型,也没有完成九场景全量模型评测。 + +### 输出、环境与迁移 + +输出为 `prediction_manifest.json` 和 `unified_metrics/` 下的协议记录、逐视角指标、完整集合汇总及浮点评分数组。记录含训练尺度、gamma、共同参考/掩码校验和、评分代码哈希和解释器路径。可加 `--save-predictions` 保存未裁剪编码直方图以便复算;不保存旧口径指标和旧图表。已有结果目录禁止覆盖。 + +三个项目必须使用同一个图像评价环境。服务器运行前设置: + +```bash +export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python +``` + +迁移机器后将它改为共同评价环境的 Python 绝对路径。数据、标定、权重、共同参考缓存不复制进代码包;README 中的示例配置仍指向服务器的实际路径,发布数据时需同时提供对应 contract/GT 缓存并改为新路径。每种方法使用同一场景的同一份 contract。保存目录名中的旧日期仅是外部参考数据的位置,不再是代码导入依赖。 + +评分已有预测统一使用 `python eval.py saved --help` 查看参数,例如: + +```bash +python eval.py saved --prediction-dir /absolute/predictions \ + --prediction-manifest /absolute/predictions/prediction_manifest.json \ + --prediction-scale ACTUAL_TRAINING_SCALE --prediction-gamma 1 \ + --prediction-bin-width-s 7.5e-10 \ + --shared-reference-contract /absolute/reference/contract.json \ + --output /absolute/new_scores --device cpu +``` + +FWP 编码输出填写真实训练 gamma;已经恢复完整计数的导出填写 scale=1、gamma=1。有单位记录的 manifest 与命令参数冲突时会报错。 + +`requirements.txt` 保留各模型依赖。先安装匹配 CUDA 11.8 的 PyTorch 2.5.1 / torchvision 0.20.1,再安装其余依赖和 CUDA 扩展;模型环境可以不同,图像评价子进程保持一致。训练日志中的训练集损失/PSNR 仅用于优化诊断,不是测试集 benchmark 分数。 diff --git a/codes/reconstruction/transientangelo/__pycache__/launch.cpython-312.pyc b/codes/reconstruction/transientangelo/__pycache__/launch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..302eaa668f3a5c7e5b4565aa6e2d015649430729 Binary files /dev/null and b/codes/reconstruction/transientangelo/__pycache__/launch.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/configs/captured.yaml b/codes/reconstruction/transientangelo/configs/captured.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2fc583bcf489b44aabc74e71e63097c83964580 --- /dev/null +++ b/codes/reconstruction/transientangelo/configs/captured.yaml @@ -0,0 +1,201 @@ +# Example adapted from the server designbuilding1 configuration; not verified Table 4 provenance. +name: stb-design_floor1_10views +tag: design_floor1_10views +seed: 42 +dataset: + name: captured_dataset_ours + scene: design_floor1 + root_dir: /work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views + num_views: '10' + gamma: false + intrinsics: /work/runrong/dataset/intrinsics.npy + measurement_root: /work/runrong/dataset/paper_data/design_floor1 + data_exts: .npz,.txt,.pt,.h5,.hdf5 + source_img_shape: null + n_bins: 672 + bin_width_s: 7.5e-10 + bin_width_s_loader: 7.5e-10 + exposure_time: 0.2248443435 + irf_path: /work/runrong/dataset/paper1_data/raw/new_IRF_global.csv + irf_column: irf + irf_half_window: 50 + no_irf_reverse: false + apply_shift: true + strict_n_bins: true + transforms_dir: null + rfilter_sigma: 0.15 + sample_as_per_distribution: false + meas_peak_min: 10.0 + invalid_mask_path: /work/runrong/dataset/paper1_data/offset.txt + invalid_mask_invalid_gt: 10.0 + img_wh: + - 256 + - 192 + img_downscale: 1 + near_plane: 0.1 + far_plane: 28.0 + train_split: train + val_split: test + test_split: test + test_no: 2 + var_increase: 1 + photon_level: 0 + use_bkgd_masking: false +model: + name: captured-neus + radius: 0.4 + scene_aabb: + - -30.723363 + - -32.531209 + - -1.819858 + - 30.377352 + - 12.024207 + - 9.260004 + num_samples_per_ray: 4096 + train_num_rays: 512 + max_train_num_rays: 8192 + grid_prune: true + grid_prune_occ_thre: 1.0e-07 + grid_prune_occ_thre_warmup: 0.0001 + grid_prune_occ_thre_warmup_steps: 2000 + multi_ray_shooting: false + dynamic_ray_sampling: false + batch_image_sampling: true + use_transient_depth: true + use_reg_nerf: false + use_regnerf_viz: true + train_patch_size: 8 + sparse_rays_size: 0 + bounding_form: sphere + sample_boundary: true + write_poses: false + randomized: true + ray_chunk: 1024 + cos_anneal_end: ${trainer.max_steps} + learned_background: false + background_color: black + variance: + init_val: 0.3 + modulate: false + geometry: + name: volume-sdf + radius: ${model.radius} + feature_dim: 16 + grad_type: finite_difference + finite_difference_eps: progressive + isosurface: + method: mc + resolution: 512 + chunk: 2097152 + threshold: 0.0 + xyz_encoding_config: + otype: ProgressiveBandHashGrid + n_levels: 16 + n_features_per_level: 2 + log2_hashmap_size: 19 + base_resolution: 32 + per_level_scale: 1.3195079107728942 + include_xyz: true + start_level: 4 + start_step: 0 + update_steps: 5000 + mlp_network_config: + otype: VanillaMLP + activation: ReLU + output_activation: none + n_neurons: 64 + n_hidden_layers: 1 + sphere_init: true + sphere_init_radius: 0.5 + weight_norm: true + texture: + name: volume-radiance + input_feature_dim: ${add:${model.geometry.feature_dim},3} + dir_encoding_config: + otype: SphericalHarmonics + degree: 4 + mlp_network_config: + otype: FullyFusedMLP + activation: ReLU + output_activation: none + n_neurons: 64 + n_hidden_layers: 2 + color_activation: softplus +system: + name: captured-neus-system + depth_from_transient_peak_for_losses: true + save_train_full_view_vis: false + train_full_view_vis_every_n_steps: 1000 + train_full_view_vis_view_index: 0 + loss: + lambda_rgb_l1: 1.0 + lambda_space_carving: 0.0 + lambda_integrated_l1: 0.007 + lambda_mask: 0.0 + lambda_eikonal: 1.0e-05 + lambda_eikonal_patch: 0.0 + lambda_curvature: 0.0 + lambda_surface: 0.0 + lambda_normal: 0.0 + lambda_distortion: 0.0 + lambda_opaque: 0.0 + lambda_depth_smoothness: 0.0 + lambda_transient_noise: 0.0 + lambda_argmax_consistency: 0.0 + lambda_regnerf_sparse_depth_variance: 0.0 + lambda_regnerf_depth_variance: 0.03 + lambda_depth_variance: 0.0 + lambda_sparsity: 0.0001 + sparsity_scale: 100.0 + optimizer: + name: AdamW + args: + lr: 0.001 + betas: + - 0.9 + - 0.99 + eps: 1.0e-15 + params: + geometry: + lr: 0.01 + texture: + lr: 0.01 + variance: + lr: 0.001 + warmup_steps: 5000 + scheduler: + name: SequentialLR + interval: step + milestones: + - ${system.warmup_steps} + schedulers: + - name: LinearLR + args: + start_factor: 0.01 + end_factor: 1.0 + total_iters: ${system.warmup_steps} + - name: ExponentialLR + args: + gamma: ${calc_exp_lr_decay_rate:0.1,${sub:${trainer.max_steps},${system.warmup_steps}}} + shared_reference_contract: /work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/contract.json +checkpoint: + save_top_k: -1 + every_n_train_steps: 10000 +export: + chunk_size: 2097152 + export_vertex_color: false +trainer: + max_steps: 150000 + log_every_n_steps: 100 + num_sanity_val_steps: 0 + val_check_interval: 50000000 + limit_train_batches: 1.0 + limit_val_batches: 3 + enable_progress_bar: true + precision: 16 +trial_name: train +exp_dir: ./exp/design_floor1_10views +save_dir: ./exp/design_floor1_10views/save +ckpt_dir: ./exp/design_floor1_10views/ckpt +code_dir: ./exp/design_floor1_10views/code +config_dir: ./exp/design_floor1_10views/config diff --git a/codes/reconstruction/transientangelo/datasets/__init__.py b/codes/reconstruction/transientangelo/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c77f971b0c4c21d4ea9dbdd4dcbe8037a26bed28 --- /dev/null +++ b/codes/reconstruction/transientangelo/datasets/__init__.py @@ -0,0 +1,18 @@ +datasets = {} + + +def register(name): + def decorator(cls): + datasets[name] = cls + return cls + return decorator + + +def make(name, config): + dataset = datasets[name](config) + return dataset + + + + +from . import captured_dataset_ours diff --git a/codes/reconstruction/transientangelo/datasets/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/transientangelo/datasets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4530ccf8f9827c369c64113a719ed55ad4b8fb6 Binary files /dev/null and b/codes/reconstruction/transientangelo/datasets/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/datasets/__pycache__/captured_dataset_ours.cpython-312.pyc b/codes/reconstruction/transientangelo/datasets/__pycache__/captured_dataset_ours.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..254c6dd26c40a1db89932690aafa9ce8136abf63 Binary files /dev/null and b/codes/reconstruction/transientangelo/datasets/__pycache__/captured_dataset_ours.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/datasets/captured_dataset_ours.py b/codes/reconstruction/transientangelo/datasets/captured_dataset_ours.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3cee56c5fd3a7b9006de717c2b356455535d47 --- /dev/null +++ b/codes/reconstruction/transientangelo/datasets/captured_dataset_ours.py @@ -0,0 +1,717 @@ +import json +import os +from typing import Sequence, Tuple + +import numpy as np +import pytorch_lightning as pl +import scipy.io as sio +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset, IterableDataset +from tqdm import tqdm + +import datasets as datasets +from models.ray_utils import find_mean_focus_point_regnerf +from models.utils import torch_laser_kernel +from utils.misc import get_rank + + +C = 299792458.0 + + +def _cfg_get(config, key, default=None): + if hasattr(config, key): + return getattr(config, key) + if isinstance(config, dict): + return config.get(key, default) + return default + + +def _as_bool(v, default=False): + if v is None: + return default + if isinstance(v, bool): + return v + if isinstance(v, str): + return v.lower() in ("1", "true", "yes", "y", "on") + return bool(v) + + +def _to_numpy(x): + if isinstance(x, np.ndarray): + return x + if isinstance(x, torch.Tensor): + return x.detach().cpu().numpy() + return np.asarray(x) + + +def _normalize_index(idx: torch.Tensor, size: int) -> torch.Tensor: + if size <= 1: + return torch.zeros_like(idx) + return 2.0 * idx / float(size - 1) - 1.0 + + +def _load_numpy_coo_npz(npz_path: str) -> np.ndarray: + pack = np.load(npz_path, allow_pickle=False) + try: + if "format" not in pack: + raise ValueError("missing 'format' key in npz") + fmt = str(np.asarray(pack["format"]).item()) + if fmt != "coo_numpy": + raise ValueError(f"unsupported npz format tag: {fmt}") + + shape = tuple(np.asarray(pack["shape"], dtype=np.int64).tolist()) + row = np.asarray(pack["row"], dtype=np.int64) + col = np.asarray(pack["col"], dtype=np.int64) + data = np.asarray(pack["data"]) + + dense = np.zeros(shape, dtype=data.dtype) + np.add.at(dense, (row, col), data) + return dense + finally: + pack.close() + + +def _load_histogram_2d(path: str, dtype=np.float32) -> np.ndarray: + ext = os.path.splitext(path)[1].lower() + if ext == ".txt": + arr = np.loadtxt(path, dtype=dtype) + elif ext == ".npz": + try: + from scipy import sparse # type: ignore + + arr = sparse.load_npz(path).toarray() + except Exception: + arr = _load_numpy_coo_npz(path) + if dtype is not None: + arr = np.asarray(arr, dtype=dtype) + else: + raise ValueError(f"unsupported histogram extension for 2D loader: {ext}") + + arr = np.asarray(arr, dtype=dtype) + if arr.ndim == 1: + arr = arr.reshape(1, -1) + return arr + + +def _reshape_histogram_to_hwt(arr: np.ndarray, hw: Tuple[int, int]) -> torch.Tensor: + h, w = int(hw[0]), int(hw[1]) + if arr.ndim == 3: + if arr.shape[0] == h and arr.shape[1] == w: + out = arr + elif arr.shape[0] == w and arr.shape[1] == h: + out = arr.transpose(1, 0, 2) + else: + raise ValueError(f"3D histogram shape {arr.shape} incompatible with target ({h}, {w}, T)") + return torch.from_numpy(np.asarray(out, dtype=np.float32)) + + if arr.ndim != 2: + raise ValueError(f"expected 2D/3D histogram array, got shape={arr.shape}") + + if arr.shape[0] == h * w: + out = arr.reshape(h, w, arr.shape[1]) + elif arr.shape[1] == h * w: + out = arr.T.reshape(h, w, arr.shape[0]) + else: + raise ValueError( + f"2D histogram shape {arr.shape} does not match H*W={h*w}; " + "expected [H*W, bins] or [bins, H*W]." + ) + return torch.from_numpy(np.asarray(out, dtype=np.float32)) + + +def _load_valid_mask_from_offset( + offset_path: str, + source_hw: Tuple[int, int], + target_hw: Tuple[int, int], + invalid_gt: float = 10.0, +) -> torch.Tensor: + ext = os.path.splitext(offset_path)[1].lower() + if ext == ".npy": + arr = np.load(offset_path).astype(np.float32) + else: + arr = np.loadtxt(offset_path, dtype=np.float32) + arr = np.asarray(arr, dtype=np.float32).squeeze() + + src_h, src_w = int(source_hw[0]), int(source_hw[1]) + if arr.ndim == 1: + if arr.size != src_h * src_w: + raise ValueError( + f"offset map length {arr.size} does not match source H*W={src_h*src_w}" + ) + arr = arr.reshape(src_h, src_w) + elif arr.ndim == 2: + if arr.shape == (src_h, src_w): + pass + elif arr.shape == (src_w, src_h): + arr = arr.T + elif arr.size == src_h * src_w: + arr = arr.reshape(src_h, src_w) + else: + raise ValueError( + f"offset map shape {arr.shape} incompatible with source shape ({src_h}, {src_w})" + ) + else: + raise ValueError(f"offset map must be 1D/2D, got shape={arr.shape}") + + valid = (arr <= float(invalid_gt)).astype(np.float32) + valid_t = torch.from_numpy(valid)[None, None, ...] + + dst_h, dst_w = int(target_hw[0]), int(target_hw[1]) + if (src_h, src_w) != (dst_h, dst_w): + valid_t = F.interpolate( + valid_t, + size=(dst_h, dst_w), + mode="nearest", + ) + return valid_t.squeeze(0).squeeze(0) > 0.5 + + +def _load_measurement_histogram(path: str, hw: Tuple[int, int]) -> torch.Tensor: + ext = os.path.splitext(path)[1].lower() + if ext in (".txt", ".npz"): + arr = _load_histogram_2d(path, dtype=np.float32) + hist = _reshape_histogram_to_hwt(arr, hw) + elif ext == ".pt": + raw = torch.load(path, map_location="cpu") + if not isinstance(raw, torch.Tensor): + raise ValueError(f".pt file must contain a tensor: {path}") + hist = raw.to_dense() if raw.is_sparse else raw + hist = hist.to(torch.float32).cpu() + if hist.ndim == 2: + hist = _reshape_histogram_to_hwt(hist.numpy(), hw) + elif hist.ndim == 3: + pass + else: + raise ValueError(f"unsupported tensor shape in {path}: {tuple(hist.shape)}") + elif ext in (".h5", ".hdf5"): + try: + import h5py # type: ignore + except Exception as ex: + raise ImportError(f"h5/hdf5 requires h5py: {path}") from ex + with h5py.File(path, "r") as f: + if "data" in f: + arr = np.asarray(f["data"]) + else: + dataset_keys = [k for k in f.keys() if hasattr(f[k], "shape")] + if not dataset_keys: + raise ValueError(f"h5 file has no dataset entries: {path}") + arr = np.asarray(f[dataset_keys[0]]) + hist = _reshape_histogram_to_hwt(arr, hw) + else: + raise ValueError(f"unsupported measurement extension: {ext}") + + if hist.ndim == 4 and hist.shape[-1] == 1: + hist = hist[..., 0] + if hist.ndim == 4 and hist.shape[-1] == 3: + hist = hist[..., 0] + if hist.ndim != 3: + raise ValueError(f"expected histogram shape [H,W,T], got {tuple(hist.shape)} from {path}") + return hist + + +def _parse_shift_for_grid(shift, hw: Tuple[int, int]): + h, w = int(hw[0]), int(hw[1]) + arr = np.asarray(shift, dtype=np.float32) + if arr.ndim == 0: + return float(arr.item()), None + + arr = arr.squeeze() + if arr.ndim == 0 or arr.size == 1: + return float(arr.reshape(-1)[0]), None + + if arr.ndim == 1 and arr.size == h * w: + return 0.0, torch.from_numpy(arr.reshape(h, w)) + + if arr.ndim == 2: + shift_map = torch.from_numpy(arr.astype(np.float32)) + if tuple(shift_map.shape) != (h, w): + shift_map = F.interpolate( + shift_map[None, None, ...], + size=(h, w), + mode="bilinear", + align_corners=True, + ).squeeze(0).squeeze(0) + return 0.0, shift_map + + return float(arr.reshape(-1)[0]), None + + +def _build_shift_grid( + hw: Tuple[int, int], + n_bins: int, + shift, + bin_width_s: float, + device: str = "cpu", +) -> torch.Tensor: + h, w = int(hw[0]), int(hw[1]) + exposure_time = C * float(bin_width_s) + shift_scalar, shift_map = _parse_shift_for_grid(shift, hw) + + z = torch.arange(n_bins, device=device, dtype=torch.float32)[:, None, None] + z = z * exposure_time / 2.0 + if shift_map is not None: + z = z - shift_map.to(device)[None, ...] + else: + z = z - float(shift_scalar) + z = z * 2.0 / exposure_time + z = _normalize_index(z, n_bins) + + x = _normalize_index(torch.arange(w, device=device, dtype=torch.float32), w) + y = _normalize_index(torch.arange(h, device=device, dtype=torch.float32), h) + + x = x[None, None, :].expand(n_bins, h, w) + y = y[None, :, None].expand(n_bins, h, w) + z = z.expand(n_bins, h, w) + + grid = torch.stack((x, y, z), dim=-1)[None, ...] + return grid + + +def _apply_shift(hist: torch.Tensor, shift, bin_width_s: float) -> torch.Tensor: + h, w, t = hist.shape + grid = _build_shift_grid((h, w), t, shift, bin_width_s, device=hist.device) + hist_dhw = hist.permute(2, 0, 1)[None, None, ...] + shifted = F.grid_sample(hist_dhw, grid, align_corners=True) + return shifted.squeeze(0).squeeze(0).permute(1, 2, 0) + + +def _resize_hist_spatial(hist: torch.Tensor, target_hw: Tuple[int, int]) -> torch.Tensor: + target_h, target_w = int(target_hw[0]), int(target_hw[1]) + h, w, _ = hist.shape + if (h, w) == (target_h, target_w): + return hist + hist_chw = hist.permute(2, 0, 1)[None, ...] + resized = F.interpolate(hist_chw, size=(target_h, target_w), mode="area") + return resized.squeeze(0).permute(1, 2, 0) + + +def _parse_data_exts(raw) -> Tuple[str, ...]: + if raw is None: + return (".npz", ".txt", ".pt", ".h5", ".hdf5") + if isinstance(raw, str): + return tuple(e.strip() for e in raw.split(",") if e.strip()) + return tuple(str(e).strip() for e in raw if str(e).strip()) + + +def _resolve_measurement_path( + data_dir: str, + split: str, + frame_file_path: str, + measurement_root: str = None, + data_exts: Sequence[str] = (".npz", ".txt", ".pt", ".h5", ".hdf5"), +) -> str: + raw = str(frame_file_path) + if os.path.isabs(raw) and os.path.isfile(raw): + return raw + + rel = raw.replace("\\", "/").lstrip("./") + base = os.path.basename(rel) + stem, ext = os.path.splitext(base) + rel_stem = os.path.splitext(rel)[0] + + roots = [] + if measurement_root: + roots.extend([measurement_root, os.path.join(measurement_root, split)]) + roots.extend([data_dir, os.path.join(data_dir, split)]) + + seen_roots = set() + unique_roots = [] + for r in roots: + rr = os.path.normpath(r) + if rr not in seen_roots: + unique_roots.append(rr) + seen_roots.add(rr) + + if ext: + for root in unique_roots: + for rel_name in (rel, base): + cand = os.path.normpath(os.path.join(root, rel_name)) + if os.path.isfile(cand): + return cand + + for root in unique_roots: + for data_ext in data_exts: + for rel_name in (rel_stem + data_ext, stem + data_ext): + cand = os.path.normpath(os.path.join(root, rel_name)) + if os.path.isfile(cand): + return cand + + raise FileNotFoundError( + f"Cannot resolve measurement file for frame '{frame_file_path}'. " + f"Searched roots={unique_roots}, exts={tuple(data_exts)}." + ) + + +def _load_irf_series(path: str, column: str = "irf") -> np.ndarray: + ext = os.path.splitext(path)[1].lower() + if ext == ".csv": + try: + import pandas as pd # type: ignore + + df = pd.read_csv(path, sep=",") + if column in df.columns: + arr = df[column].to_numpy(dtype=np.float64) + else: + numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)] + if not numeric_cols: + raise ValueError(f"No numeric columns found in IRF CSV: {path}") + arr = df[numeric_cols[0]].to_numpy(dtype=np.float64) + return arr.squeeze() + except Exception: + try: + arr = np.genfromtxt(path, delimiter=",", names=True, dtype=np.float64) + if arr.dtype.names and column in arr.dtype.names: + return np.asarray(arr[column], dtype=np.float64).squeeze() + except Exception: + pass + raw = np.loadtxt(path, delimiter=",", dtype=np.float64) + if raw.ndim == 1: + return raw.squeeze() + return raw[:, 0].squeeze() + if ext == ".npy": + return np.load(path).astype(np.float64).squeeze() + if ext == ".mat": + mat = sio.loadmat(path) + if "out" in mat: + return _to_numpy(mat["out"]).astype(np.float64).squeeze() + for value in mat.values(): + if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1: + return _to_numpy(value).astype(np.float64).squeeze() + raise ValueError(f"Cannot find valid IRF series in mat file: {path}") + if ext == ".pt": + return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze() + raise ValueError(f"Unsupported IRF extension: {ext}") + + +def _build_laser_from_config(config) -> torch.Tensor: + irf_path = _cfg_get(config, "irf_path", None) + if not irf_path: + irf_path = _cfg_get(config, "pulse_path", None) + if not irf_path: + raise ValueError("IRF path is empty. Set dataset.irf_path or dataset.pulse_path.") + + irf_column = str(_cfg_get(config, "irf_column", "irf")) + irf_half_window = int(_cfg_get(config, "irf_half_window", 50)) + no_irf_reverse = _as_bool(_cfg_get(config, "no_irf_reverse", False)) + + irf = _load_irf_series(irf_path, irf_column) + if irf.ndim != 1: + irf = irf.reshape(-1) + if irf.size == 0: + raise ValueError(f"Loaded empty IRF from: {irf_path}") + + peak_idx = int(np.argmax(irf)) + if irf_half_window > 0: + lo = max(0, peak_idx - irf_half_window) + hi = min(len(irf), peak_idx + irf_half_window + 1) + irf = irf[lo:hi] + + irf = irf / (irf.sum() + 1e-8) + if not no_irf_reverse: + irf = irf[::-1].copy() + return torch.tensor(irf, dtype=torch.float32) + + +def _resolve_transforms_path(root_dir: str, split: str, config) -> str: + transforms_dir = _cfg_get(config, "transforms_dir", None) + dirs = [transforms_dir] if transforms_dir else [] + dirs.append(root_dir) + + candidates = [] + for d in dirs: + candidates.append(os.path.join(d, f"transforms_{split}.json")) + + if split in ("train", "val"): + for d in dirs: + candidates.append(os.path.join(d, "transforms_train.json")) + + num_views = _cfg_get(config, "num_views", None) + if num_views: + candidates.append(os.path.join(root_dir, "final_cams", f"{num_views}_views", f"transforms_{split}.json")) + candidates.append(os.path.join(root_dir, "final_cams", f"{num_views}_views", "transforms_train.json")) + candidates.append(os.path.join(root_dir, "final_cams", "test_jsons", f"transforms_{split}.json")) + + seen = set() + for cand in candidates: + norm = os.path.normpath(cand) + if norm in seen: + continue + seen.add(norm) + if os.path.isfile(norm): + return norm + raise FileNotFoundError(f"Cannot find transforms json for split='{split}'. Tried: {candidates}") + + +class LearnRaysCustom(torch.nn.Module): + def __init__(self, rays, device="cuda:0", img_shape=(256, 256)): + super().__init__() + self.device = device + self.height = int(img_shape[0]) + self.width = int(img_shape[1]) + + rays = np.asarray(rays, dtype=np.float32) + if rays.ndim != 3 or rays.shape[-1] != 3: + raise ValueError(f"rays must be [H,W,3], got shape={rays.shape}") + + rays_t = torch.from_numpy(rays).to(self.device) + if tuple(rays_t.shape[:2]) != (self.height, self.width): + rays_t = F.interpolate( + rays_t.permute(2, 0, 1)[None, ...], + size=(self.height, self.width), + mode="bilinear", + align_corners=True, + ).squeeze(0).permute(1, 2, 0) + + rays_t = rays_t / torch.linalg.norm(rays_t, dim=-1, keepdims=True).clamp_min(1e-8) + self.rays = rays_t + + def forward(self, x0, y0): + rays = self.rays + x0 = x0.to(rays.device).float() + y0 = y0.to(rays.device).float() + + x1 = torch.floor(x0) + y1 = torch.floor(y0) + x2 = x1 + 1 + y2 = y1 + 1 + + x1 = torch.clip(x1, 0, self.width - 1) + y1 = torch.clip(y1, 0, self.height - 1) + x2 = torch.clip(x2, 0, self.width - 1) + y2 = torch.clip(y2, 0, self.height - 1) + + wx2 = ((x0 - x1) / (x2 - x1 + 1e-8))[:, None] + wx1 = 1.0 - wx2 + wy2 = ((y0 - y1) / (y2 - y1 + 1e-8))[:, None] + wy1 = 1.0 - wy2 + + x1 = x1.long() + y1 = y1.long() + x2 = x2.long() + y2 = y2.long() + + out = ( + wx1 * wy1 * rays[y1, x1] + + wx1 * wy2 * rays[y2, x1] + + wx2 * wy1 * rays[y1, x2] + + wx2 * wy2 * rays[y2, x2] + ) + out = out / torch.linalg.norm(out, dim=-1, keepdims=True).clamp_min(1e-8) + return out.float() + + +class CapturedDatasetOursBase: + def setup(self, config, split): + self.config = config + self.split = split + self.rank = get_rank() + self.device = f"cuda:{self.rank}" if torch.cuda.is_available() else "cpu" + self.OPENGL_CAMERA = True + self.apply_mask = False + self.has_mask = False + self.rep = 1 + self.rep_number = 30 + self.sample_as_per_distribution = _as_bool(_cfg_get(config, "sample_as_per_distribution", False)) + self.rfilter_sigma = float(_cfg_get(config, "rfilter_sigma", 0.1)) + + self.scene = str(_cfg_get(config, "scene", "custom")) + self.n_views = str(_cfg_get(config, "num_views", "custom")) + self.near = float(_cfg_get(config, "near_plane", 0.0)) + self.far = float(_cfg_get(config, "far_plane", 6.0)) + self.depth_path = os.path.join(_cfg_get(config, "root_dir", "."), "depth") + + self.n_bins = int(_cfg_get(config, "n_bins", 1500)) + bin_width_cfg = _cfg_get(config, "bin_width_s", None) + if bin_width_cfg is None: + bin_width_cfg = _cfg_get(config, "bin_width_s_loader", None) + exposure_cfg = _cfg_get(config, "exposure_time", None) + if bin_width_cfg is not None: + self.bin_width_s = float(bin_width_cfg) + elif exposure_cfg is not None: + self.bin_width_s = float(exposure_cfg) / C + else: + self.bin_width_s = 4e-12 + + if exposure_cfg is not None: + self.exposure_time = float(exposure_cfg) + else: + self.exposure_time = C * self.bin_width_s + self.transient_scale = 1.0 + self.div_vals = {self.scene: 1.0} + + params = np.load(self.config.intrinsics, allow_pickle=True)[()] + self.shift = _to_numpy(params["shift"]) + self.rays = _to_numpy(params["rays"]) + + laser = _build_laser_from_config(config).to(torch.float32).to(self.device) + self.laser = laser + self.laser_kernel = torch_laser_kernel(self.laser, device=self.device) + + transforms_path = _resolve_transforms_path(self.config.root_dir, split, config) + with open(transforms_path, "r", encoding="utf-8") as f: + meta = json.load(f) + self.meta = meta + + if "w" in meta and "h" in meta: + W, H = int(meta["w"]), int(meta["h"]) + else: + H, W = int(self.rays.shape[0]), int(self.rays.shape[1]) + + img_wh = _cfg_get(config, "img_wh", None) + img_downscale = _cfg_get(config, "img_downscale", None) + if img_wh is not None: + w, h = int(img_wh[0]), int(img_wh[1]) + elif img_downscale is not None: + w, h = W // int(img_downscale), H // int(img_downscale) + else: + w, h = W, H + self.w, self.h = w, h + self.img_wh = (self.w, self.h) + + source_img_shape = _cfg_get(config, "source_img_shape", None) + if source_img_shape is None: + source_hw = (int(self.rays.shape[0]), int(self.rays.shape[1])) + else: + source_hw = (int(source_img_shape[0]), int(source_img_shape[1])) + + invalid_mask_path = _cfg_get(config, "invalid_mask_path", None) + if invalid_mask_path is not None: + invalid_mask_path = str(invalid_mask_path).strip() + if invalid_mask_path.lower() in ("", "none", "null"): + invalid_mask_path = None + invalid_mask_invalid_gt = float(_cfg_get(config, "invalid_mask_invalid_gt", 10.0)) + if invalid_mask_path: + self.valid_mask = _load_valid_mask_from_offset( + invalid_mask_path, + source_hw=source_hw, + target_hw=(self.h, self.w), + invalid_gt=invalid_mask_invalid_gt, + ).to(torch.bool) + self.has_mask = not bool(torch.all(self.valid_mask)) + else: + self.valid_mask = torch.ones((self.h, self.w), dtype=torch.bool) + self.has_mask = False + + measurement_root = _cfg_get(config, "measurement_root", None) + measurement_root = str(measurement_root).strip() if measurement_root else None + data_exts = _parse_data_exts(_cfg_get(config, "data_exts", None)) + apply_shift = _as_bool(_cfg_get(config, "apply_shift", True), True) + strict_n_bins = _as_bool(_cfg_get(config, "strict_n_bins", True), True) + + images = [] + c2ws = [] + fg_masks = [] + for frame in tqdm(meta["frames"], desc=f"Processing {self.split} frames"): + file_key = frame.get("file_path", frame.get("filepath")) + if file_key is None: + raise KeyError("Each frame must contain 'file_path' or 'filepath'.") + + meas_path = _resolve_measurement_path( + data_dir=self.config.root_dir, + split=split, + frame_file_path=file_key, + measurement_root=measurement_root, + data_exts=data_exts, + ) + hist = _load_measurement_histogram(meas_path, source_hw).to(torch.float32).cpu() + hist = torch.clip(hist, min=0.0) + + if apply_shift: + hist = _apply_shift(hist, shift=self.shift, bin_width_s=self.bin_width_s) + + if hist.shape[-1] != self.n_bins: + if strict_n_bins: + raise ValueError( + f"Histogram bins mismatch for '{meas_path}': got {hist.shape[-1]}, expected {self.n_bins}." + ) + if hist.shape[-1] > self.n_bins: + hist = hist[..., : self.n_bins] + else: + pad = self.n_bins - int(hist.shape[-1]) + hist = F.pad(hist, (0, pad), mode="constant", value=0.0) + + hist = _resize_hist_spatial(hist, (self.h, self.w)) + images.append(hist[..., None].repeat(1, 1, 1, 3)) + c2ws.append(np.asarray(frame["transform_matrix"], dtype=np.float32)) + fg_masks.append(self.valid_mask.to(torch.float32)) + + self.all_images = torch.stack(images, dim=0).to(torch.float32) + self.all_c2w = torch.from_numpy(np.stack(c2ws, axis=0)).to(torch.float32) + self.all_fg_masks = torch.stack(fg_masks, dim=0).to(torch.float32) + + max_value = self.all_images.max().clamp_min(1e-8) + self.all_images = self.all_images / max_value + self.focal = max_value + + self.K = LearnRaysCustom(self.rays, device=self.device, img_shape=(self.h, self.w)).to(self.device) + known_rotation_matrices = self.all_c2w[:, :3, :3] + optical_axes = known_rotation_matrices[..., 2] + known_camera_locations = self.all_c2w[:, :3, -1] + self.mean_focus_point = find_mean_focus_point_regnerf(known_camera_locations, optical_axes) + + +class CapturedDatasetOurs(Dataset, CapturedDatasetOursBase): + def __init__(self, config, split): + self.setup(config, split) + + def __len__(self): + return len(self.all_c2w) + + def __getitem__(self, index): + return {"index": index} + + +class CapturedIterableDatasetOurs(IterableDataset, CapturedDatasetOursBase): + def __init__(self, config, split): + self.setup(config, split) + + def __iter__(self): + while True: + yield {} + + +@datasets.register("captured_dataset_ours") +class CapturedDataOursModule(pl.LightningDataModule): + def __init__(self, config): + super().__init__() + self.config = config + + def setup(self, stage=None): + if stage in [None, "fit"]: + self.train_dataset = CapturedIterableDatasetOurs(self.config, self.config.train_split) + if stage in [None, "fit", "validate"]: + self.val_dataset = CapturedDatasetOurs(self.config, self.config.val_split) + if stage in [None, "test"]: + self.test_dataset = CapturedDatasetOurs(self.config, self.config.test_split) + if stage in [None, "predict"]: + self.predict_dataset = CapturedDatasetOurs(self.config, self.config.train_split) + + def prepare_data(self): + pass + + def general_loader(self, dataset, batch_size): + sampler = None + num_workers = int(_cfg_get(self.config, "num_workers", 0)) + pin_memory = _as_bool(_cfg_get(self.config, "pin_memory", True), True) + persistent_workers = num_workers > 0 + return DataLoader( + dataset, + num_workers=num_workers, + batch_size=batch_size, + pin_memory=pin_memory, + persistent_workers=persistent_workers, + sampler=sampler, + ) + + def train_dataloader(self): + return self.general_loader(self.train_dataset, batch_size=1) + + def val_dataloader(self): + return self.general_loader(self.val_dataset, batch_size=1) + + def test_dataloader(self): + return self.general_loader(self.test_dataset, batch_size=1) + + def predict_dataloader(self): + return self.general_loader(self.predict_dataset, batch_size=1) diff --git a/codes/reconstruction/transientangelo/eval.py b/codes/reconstruction/transientangelo/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..156428c137ff4a40e071acd2dbb76990a15b8cca --- /dev/null +++ b/codes/reconstruction/transientangelo/eval.py @@ -0,0 +1,5 @@ +"""The only public evaluation entry: render predictions or score saved histograms.""" +from evaluation.cli import main + +if __name__ == "__main__": + main() diff --git a/codes/reconstruction/transientangelo/evaluation/__init__.py b/codes/reconstruction/transientangelo/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4587915b0d7bc01640496b06530c1fa02f2321b0 --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/__init__.py @@ -0,0 +1,4 @@ +"""Common count-domain transient evaluation, independent of model training units.""" +PROTOCOL = 'shared_transient_counts_v4_20261016' +TRANSIENT_KEYS = ('histogram_psnr', 'histogram_mse_counts', 'histogram_mae_counts', + 'depth_l1_m', 'transient_iou') diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8475e7931580d6987b510770572c5efe51e497a2 Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/cli.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba6587cd5fccd8500ed0a0cd2cdeb7f289a2bbde Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/cli.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/core.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9797fc086cea44548c9eb46386b28a9349d04a9c Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/core.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/evaluator.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..468d3ff553d15ffaf83a49109489a93389906878 Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/evaluator.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/image_metrics.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/image_metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2a305e365da8d7555a387147ebe780e02aa77e Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/image_metrics.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/io.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..505c8f63d3f559517522ba5bb234d49d13d34c0e Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/io.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/renderer.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/renderer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a6931007f7ad29661a6731f5a91d286818fce9d Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/renderer.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/units.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/units.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e133b948aad715b95586b68c8671d47ea5fccc4c Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/units.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/__pycache__/worker.cpython-312.pyc b/codes/reconstruction/transientangelo/evaluation/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b25369a5d457a5a06861fd9e1e641a5ebd7cd7de Binary files /dev/null and b/codes/reconstruction/transientangelo/evaluation/__pycache__/worker.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/evaluation/cli.py b/codes/reconstruction/transientangelo/evaluation/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..75f1ced0c673a449a2511fb744c102c7384cdaab --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/cli.py @@ -0,0 +1,54 @@ +"""One entry point and one protocol, for all three methods.""" +import argparse +import json +import sys +from pathlib import Path + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', choices=('render', 'saved'), + help='render a checkpoint, or score unmodified saved histograms') + if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'): + parser.print_help() + return + mode = parser.parse_args(sys.argv[1:2]).source + sys.argv = [sys.argv[0]] + sys.argv[2:] + from . import renderer + if mode == 'render': + return renderer.main() + from .evaluator import EvaluationRun + from .io import load_histogram, write_json, sha256 + p = argparse.ArgumentParser(description='Score saved histograms with the same V4 evaluator as render.') + p.add_argument('--prediction-dir', required=True) + p.add_argument('--prediction-pattern', default='{view}_transient_array.npy') + p.add_argument('--prediction-scale', type=float, required=True, + help='ACTUAL TRAINING normalization; 1 only for full-count exports') + p.add_argument('--prediction-gamma', type=float, default=1.) + p.add_argument('--prediction-bin-width-s', type=float, required=True) + p.add_argument('--prediction-manifest', required=True, + help='Actual rendered frames and poses, in prediction-file order') + p.add_argument('--shared-reference-contract', required=True) + p.add_argument('--output', required=True) + p.add_argument('--device', default='cpu') + a = p.parse_args() + a.bin_width_s_loader = a.prediction_bin_width_s + a.n_bins = json.loads(Path(a.shared_reference_contract).read_text())['n_bins'] + manifest = json.loads(Path(a.prediction_manifest).read_text()) + if (Path(a.output)/'prediction_manifest.json').resolve() == Path(a.prediction_manifest).resolve(): + raise ValueError('Use a separate output directory to preserve the source manifest') + # Generated manifests are binding; do not silently override their physical units. + for key, actual in [('prediction_scale', a.prediction_scale), + ('prediction_gamma', a.prediction_gamma), + ('bin_width_s', a.prediction_bin_width_s)]: + if key in manifest and float(manifest[key]) != actual: + raise ValueError('Prediction manifest disagrees with '+key) + frames = manifest['frames'] + run = EvaluationRun(renderer.PROJECT, a, a.output, frames, a.prediction_scale, + a.prediction_gamma, rendering=manifest.get('rendering')) + run.evaluator.metadata.update(prediction_manifest=str(Path(a.prediction_manifest).resolve()), + prediction_manifest_sha256=sha256(a.prediction_manifest)) + write_json(run.evaluator.output/'evaluation_protocol.json', run.evaluator.metadata) + for i, frame in enumerate(frames): + path = Path(a.prediction_dir)/a.prediction_pattern.format(view=i, stem=Path(frame['file_path']).stem) + run.score(load_histogram(path), i) + print(run.finish()) diff --git a/codes/reconstruction/transientangelo/evaluation/core.py b/codes/reconstruction/transientangelo/evaluation/core.py new file mode 100644 index 0000000000000000000000000000000000000000..27d91f197d2e6648591d1ad87e1ff28c6d8e4b8e --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/core.py @@ -0,0 +1,81 @@ +"""Pure NumPy scoring. No data-dependent exposure fitting or upper clipping.""" +import numpy as np + +C = 299792458.0 + +def positive(x, name): + x = float(x) + if not np.isfinite(x) or x <= 0: + raise ValueError(name + ' must be finite and positive') + return x + +def histogram(x): + if hasattr(x, 'detach'): + x = x.detach().cpu().numpy() + x = np.asarray(x) + if x.ndim == 3: + x = x[..., None] + if x.ndim != 4 or x.shape[-1] not in (1, 3) or min(x.shape) <= 0: + raise ValueError('Expected H x W x T x (1 or 3) histogram') + return x + +def decode(x, scale, gamma=1.0): + """Inverse training encoding, applied per bin before any summation.""" + scale, gamma = positive(scale, 'training scale'), positive(gamma, 'gamma') + x = np.asarray(x, dtype=np.float64) + if not np.isfinite(x).all() or np.any(x < 0): + raise ValueError('Histogram must be finite and nonnegative, even outside the mask') + y = np.power(x, gamma) * scale if gamma != 1.0 else x * scale + if not np.isfinite(y).all(): + raise ValueError('Count decoding overflow') + return y + +def score_histograms(prediction, reference, mask, *, prediction_scale, + reference_scale, histogram_peak, bin_width_s, + prediction_gamma=1.0, row_chunk=4): + """MSE over all bins/channels of GT-valid pixels, using a frozen train peak. + + A one-channel capture is broadcast to RGB when necessary. All RGB channels + enter MSE; peak depth uses their arithmetic mean. Chunking bounds RAM use. + """ + pred, ref = histogram(prediction), histogram(reference) + if pred.shape[:3] != ref.shape[:3]: + raise ValueError('Prediction/reference pixel grid or temporal window differs') + mask = np.asarray(mask) + if mask.shape != pred.shape[:2] or not np.isin(mask, [0, 1]).all(): + raise ValueError('Expected binary HW reference-only mask') + mask = mask.astype(bool) + if not mask.any(): + raise ValueError('No valid reference pixels') + peak = positive(histogram_peak, 'fixed histogram peak') + dt = positive(bin_width_s, 'physical bin width') + if int(row_chunk) != row_chunk or row_chunk < 1: + raise ValueError('row_chunk must be a positive integer') + h, w, t = pred.shape[:3] + channels = max(pred.shape[-1], ref.shape[-1]) + ip, ig = np.zeros((h,w,3)), np.zeros((h,w,3)) + dp, dg = np.zeros((h,w)), np.zeros((h,w)) + squared = absolute = intersection = union = 0.0 + for start in range(0,h,int(row_chunk)): + sl = slice(start,min(h,start+int(row_chunk))) + p = decode(pred[sl], prediction_scale, prediction_gamma) + g = decode(ref[sl], reference_scale) + ip[sl] = np.broadcast_to(p.sum(axis=-2), (len(p),w,3)) + ig[sl] = np.broadcast_to(g.sum(axis=-2), (len(g),w,3)) + dp[sl] = p.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0 + dg[sl] = g.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0 + a,b = np.broadcast_arrays(p[mask[sl]], g[mask[sl]]) + error = a-b + squared += np.square(error).sum(dtype=np.float64) + absolute += np.abs(error).sum(dtype=np.float64) + intersection += np.minimum(a,b).sum(dtype=np.float64) + union += np.maximum(a,b).sum(dtype=np.float64) + count = int(mask.sum()) * t * channels + mse = squared/count + psnr = float(20*np.log10(peak)-10*np.log10(mse)) if mse>0 else float('inf') + scores = dict(histogram_psnr=psnr, histogram_mse_counts=float(mse), + histogram_mae_counts=float(absolute/count), + depth_l1_m=float(np.abs(dp[mask]-dg[mask]).mean()), + transient_iou=float(intersection/union) if union>0 else 1.0) + return scores, dict(prediction=ip, reference=ig, mask=mask, + prediction_depth=dp, reference_depth=dg) diff --git a/codes/reconstruction/transientangelo/evaluation/evaluator.py b/codes/reconstruction/transientangelo/evaluation/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..ed102f188ebd8079a33eeca554a87db7a6ce9278 --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/evaluator.py @@ -0,0 +1,161 @@ +"""Frame-bound common scoring adapter for all three native and saved entrances.""" +import json +import operator +import os +from pathlib import Path +import subprocess +import sys +import numpy as np +from . import PROTOCOL +from .core import C,positive,score_histograms +from .io import sha256,verified,load_histogram,write_json + +BASE=Path(__file__).resolve().parent.parent +PYTHON=os.environ.get('STB_METRICS_PYTHON') or '/work/runrong/.conda/envs/transientangelo/bin/python' + +def resolve_contract(args): + explicit=getattr(args,'shared_reference_contract',None) or os.environ.get('SHARED_REFERENCE_CONTRACT') + if explicit:return Path(explicit).resolve() + measurement=getattr(args,'measurement_root',None) + matches=[] + for p in Path(os.environ.get('STB_REFERENCE_ROOT', str(BASE/'references'))).glob('*/contract.json'): + d=json.loads(p.read_text()) + if measurement and Path(d['measurement_root']).resolve()==Path(measurement).resolve():matches.append(p) + if len(matches)!=1: + raise ValueError('A prepared V4 canonical reference is required. Pass --shared-reference-contract ' + 'with the matching contract.json; no legacy/test-scale fallback.') + return matches[0] + +class UnifiedEvaluator: + def __init__(self,project,args,output_dir,frames): + if project not in ('trnerf','transientangelo','FlyingWithPhotons'):raise ValueError('Unknown project') + if not Path(PYTHON).is_file():raise FileNotFoundError('Set STB_METRICS_PYTHON to the common evaluation Python: '+str(PYTHON)) + self.project=project;self.path=resolve_contract(args);self.digest=sha256(self.path) + self.contract=c=json.loads(self.path.read_text()) + if c.get('protocol')!=PROTOCOL: + raise ValueError('V4 needs a histogram reference contract, not an intensity-only V2/V3 contract') + self.peak=positive(c['histogram_peak'],'fixed training histogram peak') + self.display_scale=positive(c['display_scale'],'fixed training display scale') + dt=positive(c['bin_width_s'],'reference bin width') + if not c.get('training_frames') or not c.get('scale_policy') or c.get('time_start')!=0: + raise ValueError('Missing frozen training-scale provenance or invalid time origin') + for k in ('height','width','n_bins'): + if type(c[k]) is not int or c[k]<=0:raise ValueError('Invalid '+k) + measurement=getattr(args,'measurement_root',None) + if measurement and Path(measurement).resolve()!=Path(c['measurement_root']).resolve(): + raise ValueError('Measurement scene does not match reference') + intrinsics=getattr(args,'intrinsics',None) or getattr(args,'intrinsics_path',None) + if intrinsics and sha256(intrinsics)!=c['intrinsics_sha256']:raise ValueError('Calibration mismatch') + actual=getattr(args,'bin_width_s_loader',None) + if actual is None:actual=getattr(args,'bin_width_s',None) + if actual is None and hasattr(args,'exposure_time'): + actual=float(args.exposure_time)/(C/2 if project=='FlyingWithPhotons' else C) + if actual is None or not np.isclose(float(actual),dt,rtol=1e-6,atol=0):raise ValueError('Physical bin width mismatch/missing') + # FWP uses one-way range/bin; verify it even when a loader override exists. + if project=='FlyingWithPhotons' and hasattr(args,'exposure_time'): + if not np.isclose(float(args.exposure_time)/(C/2),dt,rtol=1e-6,atol=0):raise ValueError('FWP exposure_time mismatch') + for name,want in [('n_bins',c['n_bins']),('t_min_test',0),('t_max_test',c['n_bins']), + ('img_height_test',c['height']),('img_width_test',c['width'])]: + actual=getattr(args,name,None) + if actual is not None and int(actual)!=want:raise ValueError('Common window/grid mismatch: '+name) + frames=list(frames);records={Path(f['file_path']).stem:f for f in c['frames']} + ids=[Path(f['file_path']).stem for f in frames] + if (not frames or len(records)!=len(c['frames']) or len(set(ids))!=len(ids) + or set(ids)!=set(records)): + raise ValueError('Evaluation must declare the complete, unique canonical test frame set') + self.frames=[] + for f,key in zip(frames,ids): + r=records[key];pose=np.asarray(f['transform_matrix']);rp=np.asarray(r['transform_matrix']) + 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): + raise ValueError('Test frame pose differs from canonical reference: '+key) + self.frames.append(r) + self.output=Path(output_dir)/'unified_metrics' + if (self.output/'evaluation_protocol.json').exists(): + raise FileExistsError('Use a fresh V4 output directory; existing scores are not overwritten') + self.output.mkdir(parents=True,exist_ok=True);self.rows=[] + self.device=os.environ.get('STB_METRICS_DEVICE') or str(getattr(args,'device','cpu')) + self.metadata=dict(protocol=PROTOCOL,project=project,reference_contract=str(self.path), + reference_sha256=self.digest,scene_id=c['scene_id'],histogram_peak=self.peak, + display_scale=self.display_scale,mask_policy=c['mask_policy'],n_bins=c['n_bins'],bin_width_s=dt, + frames=[f['file_path'] for f in self.frames], + histogram_psnr='20log10(frozen train peak)-10log10(mean squared count error); all valid bins/channels; no upper clipping/gamma', + depth='argmax of channel-mean full-count histogram; bin_index*c*dt/2, metres; canonical GT mask', + aggregation='arithmetic mean of per-view metrics, only complete frame sets receive an aggregate', + training_scale_policy='explicit actual training scale; never test maximum', + 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')}, + image_code_sha256=sha256(Path(__file__).with_name('image_metrics.py'))) + from .image_metrics import PROTOCOL_INFO + self.metadata['image_metric_definition']=dict(PROTOCOL_INFO,scale=self.display_scale) + self.metadata['checkpoint_dir']=getattr(args,'checkpoint_dir',None) + self.metadata['checkpoint_step']=getattr(args,'step',None) + 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.' + write_json(self.output/'evaluation_protocol.json',self.metadata) + + def score(self,prediction_histogram,frame_index,prediction_scale,prediction_gamma=1.0): + if isinstance(frame_index,(bool,np.bool_)):raise IndexError('Boolean frame index') + i=operator.index(frame_index) + if i<0 or i>=len(self.frames):raise IndexError(i) + if sha256(self.path)!=self.digest:raise ValueError('Reference contract changed during evaluation') + f=self.frames[i];c=self.contract + hp=verified(self.path.parent/f['histogram_path'],f['histogram_sha256']) + mp=verified(self.path.parent/f['mask_path'],f['mask_sha256']) + reference=load_histogram(hp);mask=np.load(mp,allow_pickle=False) + if reference.shape[:3]!=(c['height'],c['width'],c['n_bins']):raise ValueError('Reference shape differs from contract') + scores,arrays=score_histograms(prediction_histogram,reference,mask, + prediction_scale=prediction_scale,reference_scale=f['reference_scale'], + histogram_peak=self.peak,bin_width_s=c['bin_width_s'],prediction_gamma=prediction_gamma) + 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' + np.savez_compressed(inp,**arrays) + env=dict(os.environ);env['PYTHONPATH']=str(BASE)+os.pathsep+env.get('PYTHONPATH','') + if self.device=='cpu':env['CUDA_VISIBLE_DEVICES']='' + proc=subprocess.run([PYTHON,'-m','evaluation.worker', + '--input',str(inp),'--output',str(result),'--display',str(display), + '--scale',str(self.display_scale),'--device',self.device],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True) + if proc.returncode:raise RuntimeError('Common image scorer failed: '+proc.stdout[-5000:]) + scores.update(json.loads(result.read_text())) + row=dict(view=i,frame=f['file_path'],prediction_scale=float(prediction_scale), + prediction_gamma=float(prediction_gamma),valid_pixels=int(mask.sum()),**scores) + self.rows=[r for r in self.rows if r['view']!=i]+[row];self.rows.sort(key=lambda r:r['view']) + write_json(self.output/'metrics_per_view.json',self.rows) + complete=len(self.rows)==len(self.frames) + write_json(self.output/'progress.json',dict(completed_views=len(self.rows),expected_views=len(self.frames),complete=complete)) + if complete: + write_json(self.output/'metrics_aggregate.json',{k:float(np.mean([r[k] for r in self.rows])) for k in scores}) + with np.load(display) as d:p,g=d['prediction'],d['reference'] + return dict(scores,psnr=scores['image_psnr'],prediction_display=p,reference_display=g, + reference_histogram=reference,reference_scale=f['reference_scale'], + prediction_intensity_counts=arrays['prediction'],reference_intensity_counts=arrays['reference'], + mask=arrays['mask'],prediction_depth=arrays['prediction_depth'],reference_depth=arrays['reference_depth'],protocol=PROTOCOL) + +class EvaluationRun: + """The same scoring/output path for native rendering and saved predictions.""" + def __init__(self, project, args, output_dir, frames, scale, gamma=1.0, + rendering=None, save_predictions=False): + self.scale = positive(scale, 'actual training scale') + self.gamma = positive(gamma, 'actual training gamma') + self.evaluator = UnifiedEvaluator(project, args, output_dir, frames) + self.output = Path(output_dir) + self.save_predictions = save_predictions + manifest = dict(frames=frames, prediction_scale=self.scale, + prediction_gamma=self.gamma, + bin_width_s=self.evaluator.contract['bin_width_s'], + rendering=rendering or {'source': 'saved histograms; see source manifest'}) + write_json(self.output/'prediction_manifest.json', manifest) + self.evaluator.metadata.update(prediction_scale=self.scale, prediction_gamma=self.gamma, + rendering=manifest['rendering']) + write_json(self.evaluator.output/'evaluation_protocol.json', self.evaluator.metadata) + + def score(self, prediction, index): + if self.save_predictions: + if hasattr(prediction, 'detach'): + prediction = prediction.detach().cpu().numpy() + np.save(self.output/f'{index}_transient_array.npy', prediction) + scores = self.evaluator.score(prediction, index, self.scale, self.gamma) + print(self.evaluator.project, index, {k: scores[k] for k in + ('histogram_psnr', 'image_psnr', 'ssim', 'lpips', 'depth_l1_m')}, flush=True) + return scores + + def finish(self): + if len(self.evaluator.rows) != len(self.evaluator.frames): + raise ValueError('Incomplete canonical test set: no complete evaluation result') + return self.evaluator.output/'metrics_aggregate.json' diff --git a/codes/reconstruction/transientangelo/evaluation/image_metrics.py b/codes/reconstruction/transientangelo/evaluation/image_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..21f88ff92b2aefd2895c10990710d0d069d76b61 --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/image_metrics.py @@ -0,0 +1,114 @@ +"""Shared TA-style display metrics, with uncensored linear-count diagnostics. + +Not an exact upstream reproduction: all projects use one reference-only mask, +explicit SSIM settings, a frozen training scale, and FP32 LPIPS. +""" +import numpy as np +import torch +import lpips +from contextlib import contextmanager +from scipy.ndimage import minimum_filter +from skimage.metrics import structural_similarity + +PROTOCOL = 'shared_ta_display_psnr_ssim_lpips_v3_20260929' +PRIMARY_KEYS = ('psnr', 'ssim', 'lpips') +AUXILIARY_KEYS = ('linear_psnr', 'prediction_above_scale_percent', + 'reference_above_scale_percent', 'max_prediction_over_scale', + 'max_reference_over_scale') +SCORE_KEYS = PRIMARY_KEYS + AUXILIARY_KEYS +PROTOCOL_INFO = dict( + protocol=PROTOCOL, + scale_policy="explicit frozen per-scene record; no numeric scene fallback", + metric_labels=dict(psnr='PSNR-display', ssim='SSIM-display', lpips='LPIPS-display', + linear_psnr='PSNR-linear (auxiliary)'), + prediction_display='clip(I/D,0,1) ** (1/2.2)', + reference_display='(I/D) ** (1/2.2), no upper clipping', + psnr='-10log10 valid-reference-pixel/RGB display MSE; fixed peak 1', + ssim='RGB, data_range=1, uniform 7x7, sample covariance, complete reference-valid windows', + lpips='same display RGB, common invalid region black, [-1,1] transform, VGG0.1 FP32', + linear_psnr='-10log10 mean(((prediction-reference)/D)^2); no upper clipping or gamma', + above_scale_percent='percentage of reference-valid pixels with ANY RGB channel > D', + aggregation='arithmetic mean of per-view metrics; saturation percentages are mean per-view percentages', + prediction_upper_clip=True, reference_upper_clip=False, + count_domain_upper_clip=False, fitted_test_exposure=False, + preview_png='clip display arrays only for uint8 export; floating scoring arrays are retained', + upstream_exact=False, +) + +@contextmanager +def scoring_precision(): + previous = (torch.get_float32_matmul_precision(), + torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32) + try: + torch.set_float32_matmul_precision('highest') + torch.backends.cuda.matmul.allow_tf32=False + torch.backends.cudnn.allow_tf32=False + yield + finally: + torch.set_float32_matmul_precision(previous[0]) + torch.backends.cuda.matmul.allow_tf32=previous[1] + torch.backends.cudnn.allow_tf32=previous[2] + +def tone_map(image, scale, *, prediction): + """Role is explicit: upstream prediction and reference transforms differ.""" + x=np.asarray(image,dtype=np.float64) + if not np.isfinite(scale) or scale <= 0: + raise ValueError('positive fixed scale required') + if not np.isfinite(x).all() or np.any(x<0): + raise ValueError('Expected finite nonnegative counts; no silent masking/clipping of invalid inputs') + x=x/scale + if prediction: + x=np.clip(x,0.,1.) + return x**(1/2.2) + +def display_pair(prediction, reference, scale, mask=None): + p=tone_map(prediction,scale,prediction=True) + g=tone_map(reference,scale,prediction=False) + if mask is not None: + mask=np.asarray(mask,bool) + p[~mask]=0;g[~mask]=0 + return p,g + +def preview_uint8(display_image): + """PNG encoding only. Never pass this output back to a metric.""" + return np.rint(np.clip(display_image,0.,1.)*255.).astype(np.uint8) + +def _psnr(mse): + return float(-10*np.log10(mse)) if mse>0 else float('inf') + +class ImageMetrics: + def __init__(self, scale, device='cuda'): + if not np.isfinite(scale) or scale<=0: + raise ValueError('positive fixed scale required') + self.scale=float(scale);self.device=str(device) + self.net=lpips.LPIPS(net='vgg',version='0.1').float().to(device).eval() + + def __call__(self, prediction, reference, mask): + pred=np.asarray(prediction,np.float64);ref=np.asarray(reference,np.float64) + mask=np.asarray(mask,dtype=bool) + if pred.shape!=ref.shape or pred.ndim!=3 or pred.shape[-1]!=3 or mask.shape!=pred.shape[:2]: + raise ValueError('Expected matching HWC3 images and HW reference mask') + if not mask.any(): + raise ValueError('No reference-valid pixels') + x,y=display_pair(pred,ref,self.scale) + psnr=_psnr(np.mean((x[mask]-y[mask])**2,dtype=np.float64)) + linear_psnr=_psnr(np.mean(((pred[mask]-ref[mask])/self.scale)**2,dtype=np.float64)) + windows=minimum_filter(mask.astype(np.uint8),size=7,mode='constant',cval=0).astype(bool) + if not windows.any(): + raise ValueError('No complete 7x7 reference-valid SSIM windows') + _,ssim_map=structural_similarity(y,x,data_range=1.,channel_axis=-1, + win_size=7,gaussian_weights=False,use_sample_covariance=True,full=True) + ssim=float(ssim_map[windows].mean()) + x[~mask]=0;y[~mask]=0 + tensor=lambda z: torch.from_numpy(z.astype(np.float32)).permute(2,0,1)[None].to(self.device)*2-1 + with scoring_precision(),torch.no_grad(),torch.autocast(device_type=self.device.split(':')[0],enabled=False): + score=self.net(tensor(x),tensor(y)) + return dict(psnr=psnr,ssim=ssim,lpips=float(score.item()),linear_psnr=linear_psnr, + prediction_above_scale_percent=float(np.any(pred[mask]>self.scale,axis=-1).mean()*100), + reference_above_scale_percent=float(np.any(ref[mask]>self.scale,axis=-1).mean()*100), + max_prediction_over_scale=float(pred[mask].max()/self.scale), + max_reference_over_scale=float(ref[mask].max()/self.scale)) + +def aggregate(rows): + if not rows:raise ValueError('Cannot aggregate empty results') + return {k:float(np.mean([r[k] for r in rows],dtype=np.float64)) for k in SCORE_KEYS} diff --git a/codes/reconstruction/transientangelo/evaluation/io.py b/codes/reconstruction/transientangelo/evaluation/io.py new file mode 100644 index 0000000000000000000000000000000000000000..7e60dcd7d8efcae23e61ced00e87642448edd9f3 --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/io.py @@ -0,0 +1,30 @@ +import hashlib +import json +import os +from pathlib import Path +import numpy as np + +def sha256(path): + h=hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block) + return h.hexdigest() + +def write_json(path, data): + path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) + tmp=path.with_name(path.name+'.%d.tmp'%os.getpid()) + tmp.write_text(json.dumps(data,indent=2,allow_nan=True));tmp.replace(path) + +def verified(path, digest): + path=Path(path) + if not path.is_file() or sha256(path)!=digest: + raise ValueError('Frozen input missing or changed: '+str(path)) + return path + +def load_histogram(path): + path=Path(path) + if path.suffix=='.npy':return np.load(path,mmap_mode='r',allow_pickle=False) + if path.suffix in ('.h5','.hdf5'): + import h5py + with h5py.File(path,'r') as f:return np.asarray(f['data']) + raise ValueError('Use unclipped .npy or .h5 histogram exports: '+str(path)) diff --git a/codes/reconstruction/transientangelo/evaluation/renderer.py b/codes/reconstruction/transientangelo/evaluation/renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..73cb8bea9f1c4a3833c0f8c4e33d6532d2522c9c --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/renderer.py @@ -0,0 +1,102 @@ +"""Lightning model rendering adapter; every score is computed by EvaluationRun.""" +import argparse +import os +from pathlib import Path +from types import SimpleNamespace +import numpy as np + +PROJECT = 'transientangelo' + +def start_test(system): + from .evaluator import EvaluationRun + from .units import resolve_prediction_scale + from .core import C + options = getattr(system, '_evaluation_options', None) + if options is None: + raise RuntimeError('Use eval.py render to attach the common evaluation pipeline') + if system.trainer.world_size != 1: + raise ValueError('Use one GPU for the complete canonical test set') + dataset = system.trainer.datamodule.test_dataloader().dataset + system.dataset = dataset + system.model.n_bins = int(dataset.n_bins) + system.model.exposure_time = float(dataset.exposure_time) + system.model.near_plane = float(dataset.near) + system.model.far_plane = float(dataset.far) + cfg = system.config.dataset + if float(cfg.get('photon_level',0)) != 0: + raise ValueError('Full-count evaluation requires recorded full-exposure training units') + args = SimpleNamespace(shared_reference_contract=system.config.system.get('shared_reference_contract') + or cfg.get('shared_reference_contract'), + measurement_root=cfg.get('measurement_root'), intrinsics=cfg.get('intrinsics'), + n_bins=dataset.n_bins, bin_width_s=dataset.bin_width_s, + img_height_test=dataset.h, img_width_test=dataset.w, device=str(system.device)) + if not np.isclose(float(system.model.exposure_time)/C, args.bin_width_s, rtol=1e-6, atol=0): + raise ValueError('Model and reference physical bin widths differ') + scale, source = resolve_prediction_scale(system) + system._evaluation_run = EvaluationRun(PROJECT, args, options['output'], dataset.meta['frames'], scale, + rendering=dict(forward_repeats=30, sampling='native one jittered batch reused across forward repeats', + training_scale_source=source, ray_chunk_size=int(system.model.config.ray_chunk), + radiance_network_precision=system.config.model.texture.get('network_precision', 'native')), + save_predictions=options['save_predictions']) + +def render_histogram(system, batch): + """Retain the original float64 accumulation and batch reuse across 30 passes.""" + w, h = system.dataset.img_wh + rgb = np.zeros((h,w,system.dataset.n_bins,3)) + weights_sum = 0 + for _ in range(30): + sample_weights = batch['weights'].detach().cpu().numpy() + out = system(batch) + rgb += (out['rgb'].detach().cpu().numpy() * sample_weights[:, None, None]).reshape(h, w, system.dataset.n_bins, 3) + weights_sum += sample_weights + return rgb/weights_sum.reshape(h,w,1,1) + +def evaluate_trained(trainer, system, datamodule): + if trainer.world_size != 1: + if trainer.is_global_zero: + print('Training finished. Run eval.py render with one GPU to evaluate the complete test set.') + return + system._evaluation_options = dict(output=system.get_save_path(f'it{system.global_step}-evaluation'), + save_predictions=False) + return trainer.test(system, datamodule=datamodule) + +def main(): + p = argparse.ArgumentParser(description='Render a captured-NeuS checkpoint into the common evaluator') + p.add_argument('--config', required=True) + p.add_argument('--resume', required=True, help='Actual model checkpoint') + p.add_argument('--gpu', default='0', help='One GPU index') + p.add_argument('--output', required=True) + p.add_argument('--shared-reference-contract') + p.add_argument('--save-predictions', action='store_true') + p.add_argument('--ray-chunk', type=int, default=256, + help='Maximum rays per native test chunk; does not change training batches') + a, extras = p.parse_known_args() + if ',' in a.gpu: + p.error('Use one GPU for evaluation') + if a.ray_chunk <= 0: + p.error('--ray-chunk must be positive') + os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' + os.environ['CUDA_VISIBLE_DEVICES'] = a.gpu + import torch + import pytorch_lightning as pl + import datasets + import systems + from utils.misc import load_config + torch.set_float32_matmul_precision('medium') + config = load_config(a.config, cli_args=[x[2:] if x.startswith('--') else x for x in extras]) + config.cmd_args = vars(a) + config.save_dir = str(Path(a.output).resolve()) + config.model.ray_chunk = min(int(config.model.ray_chunk), a.ray_chunk) + if a.shared_reference_contract: + config.system.shared_reference_contract = a.shared_reference_contract + # Match launch.py's configured seed; record a fixed default when none was supplied. + pl.seed_everything(int(config.get('seed',42))) + dm = datasets.make(config.dataset.name, config.dataset) + system = systems.make(config.system.name, config, load_from_checkpoint=None) + system._evaluation_options = dict(output=a.output, save_predictions=a.save_predictions) + kwargs = dict(config.trainer) + kwargs.pop('progress_refresh_rate',None) + # A benchmark result must contain every canonical test frame, once. + kwargs['limit_test_batches'] = 1.0 + trainer = pl.Trainer(devices=1, accelerator='gpu', logger=False, strategy='auto', **kwargs) + trainer.test(system, datamodule=dm, ckpt_path=a.resume) diff --git a/codes/reconstruction/transientangelo/evaluation/units.py b/codes/reconstruction/transientangelo/evaluation/units.py new file mode 100644 index 0000000000000000000000000000000000000000..00b727d7a5b2f38cb6231a55ea00deb768afdee8 --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/units.py @@ -0,0 +1,84 @@ +import math +"""Actual training units; a test-split maximum is never a fallback.""" +import ast +import json +from pathlib import Path +from types import SimpleNamespace +from .core import positive +from .io import write_json,sha256 + +def record_training_units(directory,scale,gamma,train_poses,project,measurement_root=None,intrinsics=None): + path=Path(directory)/'image_metric_normalization.json' + data=dict(training_scale=positive(scale,'training scale'),training_gamma=positive(gamma,'training gamma'), + project=project,train_poses=str(Path(train_poses).resolve()),train_poses_sha256=sha256(train_poses), + measurement_root=measurement_root,intrinsics=intrinsics, + intrinsics_sha256=sha256(intrinsics) if intrinsics else None, + source='actual training loader/configuration; never computed from test data') + if path.exists(): + old=json.loads(path.read_text()) + if (float(old['training_scale'])!=data['training_scale'] or + float(old.get('training_gamma',1.0))!=data['training_gamma']): + raise ValueError('Checkpoint directory already records different training units') + for key in ('train_poses_sha256','intrinsics_sha256','measurement_root'): + if key in old and old[key]!=data[key]: + raise ValueError('Checkpoint training provenance differs: '+key) + return + write_json(path,data) + +def fwp_training_units(args): + root=Path(args.checkpoint_dir);metadata=root/'image_metric_normalization.json' + if metadata.exists(): + record=json.loads(metadata.read_text()) + scale,gamma=record['training_scale'],record['training_gamma'] + else: + params=root/'params_full.txt' + if not params.is_file():raise ValueError('FWP requires saved training params_full.txt or normalization metadata') + values={} + for line in params.read_text().splitlines(): + if '=' not in line or line.lstrip().startswith('#'):continue + k,v=line.split('=',1) + if k.strip() in ('dataset_scale','gamma'):values[k.strip()]=ast.literal_eval(v.strip()) + scale,gamma=values['dataset_scale'],values['gamma'] + scale,gamma=positive(scale,'training dataset_scale'),positive(gamma,'training gamma') + if float(args.dataset_scale)!=scale or float(args.gamma)!=gamma: + raise ValueError('Evaluation dataset_scale/gamma differs from saved FWP training units') + return scale,gamma + +def scalar(value): + if hasattr(value, 'detach'): + value = value.detach().cpu().item() + value = float(value) + if not math.isfinite(value) or value <= 0: + raise ValueError('A finite positive count scale is required') + return value + +def resolve_prediction_scale(system): + value = system.config.dataset.get('image_metric_training_scale', None) + if hasattr(system, '_image_metric_training_scale'): + if value is not None and scalar(value) != scalar(system._image_metric_training_scale): + raise ValueError('Explicit training scale conflicts with checkpoint metadata') + return scalar(system._image_metric_training_scale), 'training/checkpoint metadata' + if value is not None: + return scalar(value), 'explicit dataset.image_metric_training_scale' + raise ValueError('Missing actual training scale; use checkpoint metadata or set dataset.image_metric_training_scale. Never substitute the test maximum.') + +def tn_training_scale(args): + """Restore model output units; the independently normalized test split is not valid here.""" + explicit = getattr(args, "shared_prediction_scale", None) + path = Path(args.checkpoint_dir) / "image_metric_normalization.json" + recorded = None + if path.is_file(): + recorded = json.loads(path.read_text()).get("training_scale") + if explicit is None and recorded is None: + raise ValueError( + "Shared metrics require the TRAINING histogram normalization. " + "Supply --shared-prediction-scale from the training loader, or create " + + str(path) + " with training_scale and its training-data provenance. " + "The test split maximum must never be substituted." + ) + if explicit is not None and recorded is not None and float(explicit) != float(recorded): + raise ValueError("Explicit prediction scale conflicts with checkpoint normalization metadata") + value = float(recorded if explicit is None else explicit) + if not math.isfinite(value) or value <= 0: + raise ValueError("Training histogram normalization must be finite and positive") + return value diff --git a/codes/reconstruction/transientangelo/evaluation/worker.py b/codes/reconstruction/transientangelo/evaluation/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..2e99015d8a945dbd42af07654af354978dffcb1f --- /dev/null +++ b/codes/reconstruction/transientangelo/evaluation/worker.py @@ -0,0 +1,21 @@ +"""Run image scoring in the same installed environment for all three methods.""" +import argparse +from pathlib import Path +import numpy as np +from .io import write_json + +def main(): + p=argparse.ArgumentParser() + for k in ('input','output','display'):p.add_argument('--'+k,required=True) + p.add_argument('--scale',required=True,type=float);p.add_argument('--device',default='cpu') + a=p.parse_args() + from .image_metrics import ImageMetrics,display_pair + with np.load(a.input) as d: + pred,ref,mask=d['prediction'],d['reference'],d['mask'].astype(bool) + scores=ImageMetrics(a.scale,a.device)(pred,ref,mask) + scores['image_psnr']=scores.pop('psnr') + x,y=display_pair(pred,ref,a.scale,mask) + np.savez_compressed(a.display,prediction=x,reference=y) + write_json(a.output,scores) + +if __name__=='__main__':main() diff --git a/codes/reconstruction/transientangelo/launch.py b/codes/reconstruction/transientangelo/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..697c7c77e785acc80f8143a4a340f58080e5cb89 --- /dev/null +++ b/codes/reconstruction/transientangelo/launch.py @@ -0,0 +1,180 @@ +import sys +import argparse +import os +import time +import logging +from datetime import datetime +from pathlib import Path +from pytorch_lightning.strategies import DDPStrategy +from pytorch_lightning.profilers import PyTorchProfiler + + +PROJECT_PARENT = Path(__file__).resolve().parent +if str(PROJECT_PARENT) not in sys.path: + sys.path.insert(0, str(PROJECT_PARENT)) + + +def main(): + os.environ.setdefault("CXX", "g++") + os.environ.setdefault("CC", "gcc") + parser = argparse.ArgumentParser() + parser.add_argument('--config', required=True, help='path to config file') + parser.add_argument('--gpu', default='0', help='GPU(s) to be used') + parser.add_argument('--resume', default=None, help='path to the weights to be resumed') + parser.add_argument( + '--resume_weights_only', + action='store_true', + help='specify this argument to restore only the weights (w/o training states), e.g. --resume path/to/resume --resume_weights_only' + ) + + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('--train', action='store_true') + group.add_argument('--validate', action='store_true') + group.add_argument('--predict', action='store_true') + # group.add_argument('--export', action='store_true') # TODO: a separate export action + + parser.add_argument('--exp_dir', default='./exp') + parser.add_argument('--runs_dir', default='./runs') + parser.add_argument('--verbose', action='store_true', help='if true, set logging level to DEBUG') + parser.add_argument('--no_loggers', action='store_true', help='disable TensorBoard/CSV loggers for debugging hangs') + + args, extras = parser.parse_known_args() + extras = [arg[2:] if arg.startswith("--") else arg for arg in extras] + + # set CUDA_VISIBLE_DEVICES then import pytorch-lightning + os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' + os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu + n_gpus = len(args.gpu.split(',')) + + import datasets as datasets + import systems as systems + import pytorch_lightning as pl + from pytorch_lightning import Trainer + from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor + from pytorch_lightning.loggers import TensorBoardLogger, CSVLogger + from utils.callbacks import CodeSnapshotCallback, ConfigSnapshotCallback, CustomProgressBar + from utils.misc import load_config + import torch + + torch.set_float32_matmul_precision("medium") + + # parse YAML config to OmegaConf + config = load_config(args.config, cli_args=extras) + config.cmd_args = vars(args) + + #you can adjust stuff here to get the exp names that u want + config.trial_name = config.get('trial_name') or (config.tag + datetime.now().strftime('@%Y%m%d-%H%M%S')) + config.exp_dir = config.get('exp_dir') or os.path.join(args.exp_dir, config.name) + config.save_dir = config.get('save_dir') or os.path.join(config.exp_dir, config.trial_name, 'save') + config.ckpt_dir = config.get('ckpt_dir') or os.path.join(config.exp_dir, config.trial_name, 'ckpt') + config.code_dir = config.get('code_dir') or os.path.join(config.exp_dir, config.trial_name, 'code') + config.config_dir = config.get('config_dir') or os.path.join(config.exp_dir, config.trial_name, 'config') + + + + logger = logging.getLogger('pytorch_lightning') + if args.verbose: + logger.setLevel(logging.DEBUG) + + if 'seed' not in config: + config.seed = int(time.time() * 1000) % 1000 + pl.seed_everything(config.seed) + + + print(f"Experiment: {config.tag} 🧪") + + if "baseline" in config.name: + print(f"Reproducing baseline: {config.name.split('-')[0]} 👮") + + for val in config["system"]["loss"]: + if config["system"]["loss"][val] > 0: + print(f"Using {val}, with weight {config['system']['loss'][val]}") + + + + dm = datasets.make(config.dataset.name, config.dataset) + system = systems.make(config.system.name, config, load_from_checkpoint=None if not args.resume_weights_only else args.resume) + + callbacks = [] + if args.train: + enable_progress_bar = bool(config.trainer.get("enable_progress_bar", True)) + progress_refresh_rate = int(config.trainer.get("progress_refresh_rate", 5000)) + callbacks += [ + ModelCheckpoint( + dirpath=config.ckpt_dir, + **config.checkpoint + ), + # CodeSnapshotCallback( + # config.code_dir, use_version=False + # ), + ConfigSnapshotCallback( + config, config.config_dir, use_version=False + ), + ] + if enable_progress_bar: + callbacks.append(CustomProgressBar(refresh_rate=progress_refresh_rate)) + if not args.no_loggers: + callbacks.append(LearningRateMonitor(logging_interval='step')) + + loggers = [] + if args.train and not args.no_loggers: + loggers += [ + TensorBoardLogger(args.runs_dir, name=config.name, version=config.trial_name), + CSVLogger(config.exp_dir, name=config.trial_name, version='csv_logs') + ] + if args.no_loggers: + loggers = False + + if sys.platform == "win32": + # does not support multi-gpu on windows + strategy = "dp" + assert n_gpus == 1 + elif n_gpus == 1: + strategy = "auto" + else: + strategy = "ddp_find_unused_parameters_false" + + # if n_gpus == 1: + # strategy = "auto" + # profiler = PyTorchProfiler( + # "output_directory", # Directory where the trace file will be saved + # schedule=torch.profiler.schedule(wait=2, warmup=2, active=6, repeat=1), + # on_trace_ready=torch.profiler.tensorboard_trace_handler("output_directory"), + # record_shapes=True, + # profile_memory=True, # Set this to True if you're also interested in memory profiling + # with_stack=True # Captures the stack frames (source of the call) + # ) + + + trainer_kwargs = dict(config.trainer) + trainer_kwargs.pop('progress_refresh_rate', None) + + trainer = Trainer( + devices=n_gpus, + accelerator='gpu', + callbacks=callbacks, + logger=loggers, + strategy=strategy, + # profiler = "advanced", + **trainer_kwargs + ) + + + #NOTE: the checkpoints are actually loaded down here + if args.train: + if args.resume and not args.resume_weights_only: + # FIXME: different behavior in pytorch-lighting>1.9 ? + trainer.fit(system, datamodule=dm, ckpt_path=args.resume) + else: + trainer.fit(system, datamodule=dm) + if config.system.get('evaluate_after_fit', True): + from evaluation.renderer import evaluate_trained + evaluate_trained(trainer, system, dm) + elif args.validate: + trainer.validate(system, datamodule=dm, ckpt_path=args.resume) + elif args.predict: + trainer.predict(system, datamodule=dm, ckpt_path=args.resume) + + +if __name__ == '__main__': + main() diff --git a/codes/reconstruction/transientangelo/models/__init__.py b/codes/reconstruction/transientangelo/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a8024770669ea5004ae0d9d8a329936c448e7bb --- /dev/null +++ b/codes/reconstruction/transientangelo/models/__init__.py @@ -0,0 +1,18 @@ +models = {} + + +def register(name): + def decorator(cls): + models[name] = cls + return cls + return decorator + + +def make(name, config): + model = models[name](config) + return model + + + + +from . import captured_neus, geometry, texture diff --git a/codes/reconstruction/transientangelo/models/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e10ca4422e22163a45afd585f68e11e9005d72bb Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/base.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aabd240457e5af48dc209833b8174c84cd487e40 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/base.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/captured_neus.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/captured_neus.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ef6e261fd3eeab81c1da07d7c24b4dcd8c2f689 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/captured_neus.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/geometry.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/geometry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6ce1d4c33cc5e3bc8d072073b4fc6ca1a2b87f2 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/geometry.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/mesh_utils.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/mesh_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38fb419cddcc4112c6ba65c3bb1eba1c49481ca1 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/mesh_utils.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/nerfacc_compat.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/nerfacc_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75ba58c52e7a2448d0fa2e80385e44df06eb2eed Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/nerfacc_compat.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/network_utils.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/network_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..026a542f3ba2d85237127b87fb9f1373b321b340 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/network_utils.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/ray_utils.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/ray_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c1e2441d24f01ff659250beb075516ff63bd48d Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/ray_utils.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/texture.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/texture.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd26d22f123b9efa3b5d624ba79a7689381da4c6 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/texture.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/__pycache__/utils.cpython-312.pyc b/codes/reconstruction/transientangelo/models/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec7d48b99eb9f6cb54c86e9f886d819d9e36ec30 Binary files /dev/null and b/codes/reconstruction/transientangelo/models/__pycache__/utils.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/models/base.py b/codes/reconstruction/transientangelo/models/base.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a11207fb6659ab050eb49041a33504556df1f9 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/base.py @@ -0,0 +1,41 @@ +import torch +import torch.nn as nn + +from utils.misc import get_rank + +class BaseModel(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.rank = get_rank() + self.setup() + if self.config.get('weights', None): + self.load_state_dict(torch.load(self.config.weights)) + # self.attach_gradient_hooks() + + # def attach_gradient_hooks(self): + # # Attach hooks to all applicable layers + # for name, module in self.named_modules(): + # module.register_backward_hook(self.print_gradients) + + # def print_gradients(self, module, grad_input, grad_output): + # print(f"Gradients on {module.__class__.__name__}: {grad_output[0]}") + + def setup(self): + raise NotImplementedError + + def update_step(self, epoch, global_step): + pass + + def train(self, mode=True): + return super().train(mode=mode) + + def eval(self): + return super().eval() + + def regularizations(self, out): + return {} + + @torch.no_grad() + def export(self, export_config): + return {} diff --git a/codes/reconstruction/transientangelo/models/captured_neus.py b/codes/reconstruction/transientangelo/models/captured_neus.py new file mode 100644 index 0000000000000000000000000000000000000000..af62be4c36b01dbf96f04e00757e389184ce97aa --- /dev/null +++ b/codes/reconstruction/transientangelo/models/captured_neus.py @@ -0,0 +1,497 @@ +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch_scatter import scatter_max + +import models as models +from models.base import BaseModel +from models.utils import chunk_batch, mapping_dist_to_bin_mitsuba, mapping_dist_to_bin, torch_laser_kernel, convolve_colour +from models.nerfacc_compat import ContractionType, accumulate_along_rays, get_ray_marching_grid, make_occupancy_grid +from models.nerfacc_compat import ray_marching, render_weight_from_alpha, render_weight_from_density +from systems.utils import update_module_step + +import numpy as np +import scipy.io as sio + +class VarianceNetwork(nn.Module): + def __init__(self, config): + super(VarianceNetwork, self).__init__() + self.config = config + self.init_val = self.config.init_val + self.register_parameter('variance', nn.Parameter(torch.tensor(self.config.init_val))) + self.modulate = self.config.get('modulate', False) + if self.modulate: + self.mod_start_steps = self.config.mod_start_steps + self.reach_max_steps = self.config.reach_max_steps + self.max_inv_s = self.config.max_inv_s + + @property + def inv_s(self): + val = torch.exp(self.variance * 10.0) + if self.modulate and self.do_mod: + val = val.clamp_max(self.mod_val) + return val + + def forward(self, x): + return torch.ones([len(x), 1], device=self.variance.device) * self.inv_s + + def update_step(self, epoch, global_step): + if self.modulate: + self.do_mod = global_step > self.mod_start_steps + if not self.do_mod: + self.prev_inv_s = self.inv_s.item() + else: + self.mod_val = min((global_step / self.reach_max_steps) * (self.max_inv_s - self.prev_inv_s) + self.prev_inv_s, self.max_inv_s) + + +@models.register('captured-neus') +class CapturedNeuSModel(BaseModel): + def setup(self): + self.geometry = models.make(self.config.geometry.name, self.config.geometry) + self.texture = models.make(self.config.texture.name, self.config.texture) + if self.config.get("scene_aabb", None) is not None: + scene_aabb = torch.as_tensor(self.config.scene_aabb, dtype=torch.float32) + if scene_aabb.numel() != 6: + raise ValueError(f"model.scene_aabb must have 6 elements, got {scene_aabb.numel()}") + else: + scene_aabb = torch.as_tensor( + [-self.config.radius, -self.config.radius, -self.config.radius, self.config.radius, self.config.radius, self.config.radius], + dtype=torch.float32, + ) + self.register_buffer('scene_aabb', scene_aabb) + self.register_buffer("cos_anneal_ratio",torch.tensor(1.0).to(self.scene_aabb)) + + self.geometry.contraction_type = ContractionType.AABB + self.geometry.scene_aabb = self.scene_aabb + + if self.config.learned_background: + self.geometry_bg = models.make(self.config.geometry_bg.name, self.config.geometry_bg) + self.texture_bg = models.make(self.config.texture_bg.name, self.config.texture_bg) + self.geometry_bg.contraction_type = ContractionType.UN_BOUNDED_SPHERE + self.near_plane_bg, self.far_plane_bg = 0.1, 1e3 + self.cone_angle_bg = 10**(math.log10(self.far_plane_bg) / self.config.num_samples_per_ray) - 1. # approximate + self.render_step_size_bg = 0.01 # render_step_size = max(distance_to_camera * self.cone_angle, self.render_step_size) + + self.variance = VarianceNetwork(self.config.variance) + if self.config.grid_prune: + self.occupancy_grid = make_occupancy_grid( + roi_aabb=self.scene_aabb, + resolution=128, + contraction_type=ContractionType.AABB, + ) + if self.config.learned_background: + self.occupancy_grid_bg = make_occupancy_grid( + roi_aabb=self.scene_aabb, + resolution=256, + contraction_type=ContractionType.UN_BOUNDED_SPHERE, + ) + self.randomized = self.config.randomized + self.background_color = "black" + self.near_plane, self.far_plane = None, None + scene_extent = (self.scene_aabb[3:] - self.scene_aabb[:3]).max() + self.render_step_size = (scene_extent * math.sqrt(3) / self.config.num_samples_per_ray).item() + self.n_bins = 1500 + self.exposure_time = 0.002398339664 + + def update_step(self, epoch, global_step): + update_module_step(self.geometry, epoch, global_step) + update_module_step(self.texture, epoch, global_step) + if self.config.learned_background: + update_module_step(self.geometry_bg, epoch, global_step) + update_module_step(self.texture_bg, epoch, global_step) + update_module_step(self.variance, epoch, global_step) + + cos_anneal_end = self.config.get('cos_anneal_end', 0) + self.cos_anneal_ratio = torch.tensor(1.0) if cos_anneal_end == 0 else torch.tensor( min(1.0, global_step / cos_anneal_end)).to(self.scene_aabb) + + def occ_eval_fn(x): + sdf = self.geometry(x, with_grad=False, with_feature=False) + inv_s = self.variance(torch.zeros([1, 3]))[:, :1].clip(1e-6, 1e6) + inv_s = inv_s.expand(sdf.shape[0], 1) + estimated_next_sdf = sdf[...,None] - self.render_step_size * 0.5 + estimated_prev_sdf = sdf[...,None] + self.render_step_size * 0.5 + prev_cdf = torch.sigmoid(estimated_prev_sdf * inv_s) + next_cdf = torch.sigmoid(estimated_next_sdf * inv_s) + p = prev_cdf - next_cdf + c = prev_cdf + alpha = ((p + 1e-5) / (c + 1e-5)).view(-1, 1).clip(0.0, 1.0) + return alpha + + def occ_eval_fn_bg(x): + density, _ = self.geometry_bg(x) + # approximate for 1 - torch.exp(-density[...,None] * self.render_step_size_bg) based on taylor series + return density[...,None] * self.render_step_size_bg + + if self.training and self.config.grid_prune: + occ_thre_base = float(self.config.get("grid_prune_occ_thre", 1e-3)) + occ_warmup_steps = int(self.config.get("grid_prune_occ_thre_warmup_steps", 10000)) + occ_thre_warmup = self.config.get("grid_prune_occ_thre_warmup", None) + if occ_thre_warmup is None: + occ_thre_warmup = occ_thre_base + occ_thre = float(occ_thre_warmup) if global_step < occ_warmup_steps else occ_thre_base + + self.occupancy_grid.every_n_step(step=global_step, ema_decay= 0.95, occ_eval_fn=occ_eval_fn, occ_thre=occ_thre) + if self.config.learned_background: + self.occupancy_grid_bg.every_n_step(step=global_step, ema_decay=0.95, occ_eval_fn=occ_eval_fn_bg, occ_thre=occ_thre) + + def isosurface(self): + mesh = self.geometry.isosurface() + return mesh + + def get_alpha(self, sdf, normal, dirs, intervals): + inv_s = self.variance(torch.zeros([1, 3]))[:, :1].clip(1e-6, 1e6) # Single parameter + inv_s = inv_s.expand(sdf.shape[0], 1) + + true_cos = (dirs * normal).sum(-1, keepdim=True) + + # "cos_anneal_ratio" grows from 0 to 1 in the beginning training iterations. The anneal strategy below makes + # the cos value "not dead" at the beginning training iterations, for better convergence. + iter_cos = -(F.relu(-true_cos * 0.5 + 0.5) * (1.0 - self.cos_anneal_ratio) + + F.relu(-true_cos) * self.cos_anneal_ratio) # always non-positive + + # Estimate signed distances at section points + estimated_next_sdf = sdf[...,None] + iter_cos * intervals.reshape(-1, 1) * 0.5 + estimated_prev_sdf = sdf[...,None] - iter_cos * intervals.reshape(-1, 1) * 0.5 + + prev_cdf = torch.sigmoid(estimated_prev_sdf * inv_s) + next_cdf = torch.sigmoid(estimated_next_sdf * inv_s) + + p = prev_cdf - next_cdf + c = prev_cdf + + alpha = ((p + 1e-5) / (c + 1e-5)).view(-1).clip(0.0, 1.0) + return alpha + + + def forward_regnerf(self, unseen_rays, regnerf_laser_kernel): + n_rays = unseen_rays.shape[0] + assert n_rays == self.config.train_patch_size ** 2 + rays_o, rays_d = unseen_rays[:, 0:3], unseen_rays[:, 3:6] # both (N_rays, 3) + + def alpha_fn(t_starts, t_ends, ray_indices): + ray_indices = ray_indices.long() + t_origins = rays_o[ray_indices] + t_dirs = rays_d[ray_indices] + positions = t_origins + t_dirs * (t_starts + t_ends) / 2. + sdf, sdf_grad, feature = self.geometry(positions, with_grad=True, with_feature=True) + normal = F.normalize(sdf_grad, p=2, dim=-1) + alpha = self.get_alpha(sdf, normal, t_dirs, t_ends - t_starts) + return alpha[...,None] + + with torch.no_grad(): + ray_indices, t_starts, t_ends = ray_marching( + rays_o, rays_d, + scene_aabb=self.scene_aabb, + grid=get_ray_marching_grid(self.occupancy_grid), + alpha_fn=None, + near_plane=self.near_plane, far_plane=self.far_plane, + render_step_size=self.render_step_size, + stratified=self.randomized, + cone_angle=0.0, + alpha_thre=0.0 + ) + ray_indices = ray_indices.long() + t_origins = rays_o[ray_indices] + t_dirs = rays_d[ray_indices] + midpoints = (t_starts + t_ends) / 2. + positions = t_origins + t_dirs * midpoints + intervals = t_ends - t_starts + distances_from_origin = midpoints.squeeze(-1) + + if self.config.geometry.grad_type == 'finite_difference': + sdf, sdf_grad, feature, sdf_laplace = self.geometry(positions, with_grad=True, with_feature=True, with_laplace=True) + else: + sdf, sdf_grad, feature = self.geometry(positions, with_grad=True, with_feature=True) + + normal = F.normalize(sdf_grad, p=2, dim=-1) + # Detach inv_s so that regnerf gradients only regularize the SDF + # geometry, NOT the variance (sharpness) parameter. Allowing + # regnerf to push inv_s creates a positive-feedback loop that + # leads to NaN / collapse in large-scale scenes. + with torch.no_grad(): + inv_s_detached = self.variance(torch.zeros([1, 3]))[:, :1].clip(1e-6, 1e6) + inv_s_detached = inv_s_detached.expand(sdf.shape[0], 1).detach() + true_cos = (t_dirs * normal).sum(-1, keepdim=True) + iter_cos = -(F.relu(-true_cos * 0.5 + 0.5) * (1.0 - self.cos_anneal_ratio) + + F.relu(-true_cos) * self.cos_anneal_ratio) + estimated_next_sdf = sdf[..., None] + iter_cos * intervals.reshape(-1, 1) * 0.5 + estimated_prev_sdf = sdf[..., None] - iter_cos * intervals.reshape(-1, 1) * 0.5 + prev_cdf = torch.sigmoid(estimated_prev_sdf * inv_s_detached) + next_cdf = torch.sigmoid(estimated_next_sdf * inv_s_detached) + p = prev_cdf - next_cdf + c = prev_cdf + alpha = ((p + 1e-5) / (c + 1e-5)).view(-1).clip(0.0, 1.0)[..., None] + + rgb = self.texture(feature, t_dirs, normal) + # rgb = torch.exp(rgb) - 1 #taking exp again as double exp enforces non-negativity and helps with HDR + weights_non_squared = render_weight_from_alpha(alpha, ray_indices=ray_indices, n_rays=n_rays) + actual_colors = accumulate_along_rays(weights_non_squared, ray_indices, values=rgb, n_rays=n_rays) + only_weights = weights_non_squared + + #NOTE: if only one sample is found, right pad with zeros + if self.config.use_transient_depth: + if t_starts.shape[0] == 1: + depths = (t_starts+t_ends)/2 + left_padding = 0 + right_padding = self.config.train_patch_size ** 2 - 1 + depths = F.pad(depths, (left_padding, right_padding), "constant", 0).view(self.config.train_patch_size**2, -1) + else: + #Reason we adjust this is because some rays don't have samples so the argmax at those rays is the last index + out, argmax = scatter_max(torch.squeeze(only_weights), ray_indices, out=torch.zeros(n_rays, device=ray_indices.device)) #both are (n_rays, ) + argmax[argmax==only_weights.shape[0]] = only_weights.shape[0]-1 #shifting the index to the last index + if t_starts.shape[0] > 0: + depths = (t_starts+t_ends)[argmax]/2 #(self.config.train_patch_size ** 2, 1) + else: + depths = out[:, None] + else: + depths = accumulate_along_rays(only_weights, ray_indices, midpoints, n_rays) + + depth_variance = ((t_ends - depths[ray_indices]) ** 2 + (t_ends - depths[ray_indices])*(t_starts - depths[ray_indices]) + (t_starts - depths[ray_indices]) ** 2)/3 + weight_variance = accumulate_along_rays(weights_non_squared, ray_indices, depth_variance, n_rays) + + weights = (only_weights ** 2 / (alpha + 1e-9)) + src = weights * rgb #Alpha compose + times = distances_from_origin + try: + src = src/(times[:, None].detach()**2 + 1e-10) #square falloff of light + except: + print("here") + + + #Mapping the predicted colors to bins + tfilter_sigma = 3 + bin_mapping, dist_weights = mapping_dist_to_bin_mitsuba(distances_from_origin, self.n_bins, self.exposure_time, c=1, sigma=tfilter_sigma) #(n_samples, 24) + src = (dist_weights[..., None] * src[:, None, :]).flatten(0, 1) + colors = torch.zeros((n_rays * self.n_bins, 3), device=weights.device) + #Creates a bunch of indices for the scatter add + #NOTE: those indices are not unique. Basically, for each channel, say, index = [1805, 1806, 1807, ...], then colors[1805] sums over all elements in src that are assigned the 1805 index + index = ((torch.repeat_interleave(ray_indices, 8*tfilter_sigma) * self.n_bins) + bin_mapping.flatten().long())[:, None].expand(-1, 3).long() # (n_samples * 24, 3) + #Add all colors to the respective bins + colors.scatter_add_(0, index, src) + colors = colors.view(n_rays, self.n_bins, 3) + colors = convolve_colour(colors, regnerf_laser_kernel, n_bins=self.n_bins) + + bin_numbers_floor, bin_numbers_ceil, alpha = mapping_dist_to_bin(distances_from_origin, self.n_bins, self.exposure_time) + index_f = ((ray_indices * self.n_bins) + bin_numbers_floor.long())[:, None].expand(-1, 3).long() + index = index_f + + opacity = accumulate_along_rays(only_weights, values=None, ray_indices=ray_indices, n_rays=n_rays) + patch_size = int(math.sqrt(actual_colors.shape[0])) + out = { + "color_patch": actual_colors.view(patch_size, patch_size, 3), + "depth_patch": depths.view(patch_size, patch_size), + "opacity_patch": opacity.view(patch_size, patch_size), + "transient_patch": colors.view(-1, self.n_bins, 3), + "depth_variance_patch": weight_variance.view(patch_size, patch_size), + "sdf_grad_samples_patch": sdf_grad, + "num_samples_regnerf": len(ray_indices) + } + + return out + + + + def forward_(self, rays, laser_kernel): + + n_rays = rays.shape[0] + rays_o, rays_d = rays[:, 0:3], rays[:, 3:6] # both (N_rays, 3) + + with torch.no_grad(): + ray_indices, t_starts, t_ends = ray_marching( + rays_o, rays_d, + scene_aabb=self.scene_aabb, + grid=get_ray_marching_grid(self.occupancy_grid), + alpha_fn=None, + near_plane=self.near_plane, far_plane=self.far_plane, + render_step_size=self.render_step_size, + stratified=self.randomized, + cone_angle=0.0, + alpha_thre=0.0 + ) + + ray_indices = ray_indices.long() + t_origins = rays_o[ray_indices] + t_dirs = rays_d[ray_indices] + midpoints = (t_starts + t_ends) / 2. + positions = t_origins + t_dirs * midpoints + intervals = t_ends - t_starts + distances_from_origin = midpoints.squeeze(-1) + + if self.config.geometry.grad_type == 'finite_difference': + sdf, sdf_grad, feature, sdf_laplace = self.geometry(positions, with_grad=True, with_feature=True, with_laplace=True) + else: + sdf, sdf_grad, feature = self.geometry(positions, with_grad=True, with_feature=True) + + normal = F.normalize(sdf_grad, p=2, dim=-1) + alpha = self.get_alpha(sdf, normal, t_dirs, intervals)[...,None] #NOTE: be careful here, think adjacent sample + rgb = self.texture(feature, t_dirs, normal) + # rgb = torch.exp(rgb) - 1 #taking exp again as double exp enforces non-negativity and helps with HDR + weights_non_squared = render_weight_from_alpha(alpha, ray_indices=ray_indices, n_rays=n_rays) + only_weights = weights_non_squared + + ''' + Transient NeRF territory below + ''' + + weights = (only_weights ** 2 / (alpha+ 1e-9)) + src = weights * rgb #Alpha compose + times = 2*distances_from_origin + + src = src/(times[:, None].detach()**2 + 1e-10) #square falloff of light + + + bin_numbers_floor, bin_numbers_ceil, _ = mapping_dist_to_bin(distances_from_origin, self.n_bins, self.exposure_time) + colors = torch.zeros((n_rays * self.n_bins, 3), device=weights.device) + index = ((ray_indices * self.n_bins) + bin_numbers_floor.long())[:, None].expand(-1, 3).long() + + + colors.scatter_add_(0, index, src) + colors = colors.view(n_rays, self.n_bins, 3) + + + # do the same for the sigmas + comp_weights = torch.zeros((n_rays * self.n_bins, 1), device=weights.device) + comp_weights.scatter_add_(0, index[:, [0]], only_weights) + comp_weights = comp_weights.reshape(n_rays, self.n_bins) + + + colors = convolve_colour(colors, laser_kernel, n_bins=self.n_bins) + + opacity = accumulate_along_rays( + only_weights, ray_indices=ray_indices, values=None, n_rays=n_rays + ) + comp_normal = accumulate_along_rays(only_weights, ray_indices, values=normal, n_rays=n_rays) + comp_normal = F.normalize(comp_normal, p=2, dim=-1) + + if t_starts.shape[0] == 1: + depths = (t_starts+t_ends)/2 + left_padding = 0 + right_padding = self.config.ray_chunk - 1 + depths = F.pad(depths, (left_padding, right_padding), "constant", 0).view(self.config.ray_chunk, -1) + else: + #Reason we adjust this is because some rays don't have samples so the argmax at those rays is the last index + out, argmax = scatter_max(torch.squeeze(only_weights), ray_indices, out=torch.zeros(n_rays, device=ray_indices.device)) #both are (n_rays, ) + argmax[argmax==only_weights.shape[0]] = only_weights.shape[0]-1 #shifting the index to the last index + if t_starts.shape[0] > 0: + depths = (t_starts+t_ends)[argmax]/2 + else: + depths = out[:, None] + + to_accum_var = ((t_starts + t_ends)[..., None] - depths[ray_indices][...,None])**2 + depths_variance = accumulate_along_rays( + weights = only_weights, + ray_indices= ray_indices, + values=to_accum_var.view(to_accum_var.shape[0], 1), + n_rays=n_rays, + ) + depth_variance = ((t_ends - depths[ray_indices]) ** 2 + (t_ends - depths[ray_indices])*(t_starts - depths[ray_indices]) + (t_starts - depths[ray_indices]) ** 2)/3 + weight_variance = accumulate_along_rays(weights_non_squared, ray_indices, depth_variance, n_rays) + + out = { + 'opacity': opacity, + 'depth': torch.squeeze(depths), + 'rays_valid': opacity > 0, + 'num_samples': torch.as_tensor([len(t_starts)], dtype=torch.int32, device=rays.device), + 'rgb': colors, #the predicted transients + 'weights': only_weights.view(-1), + 'distances_from_origin': distances_from_origin, + 't_starts': t_starts, + 't_ends': t_ends, + 'ray_indices': ray_indices + } + + if self.training: + out.update({ + 'sdf_samples': sdf, + 'sdf_grad_samples': sdf_grad, + 'comp_weights': comp_weights, + 'weights': weights.view(-1), + 'points': midpoints.view(-1), + 'intervals': intervals.view(-1), + 'ray_indices': ray_indices.view(-1), + 'weight_variance': weight_variance, + }) + if self.config.geometry.grad_type == 'finite_difference': + out.update({ + 'sdf_laplace_samples': sdf_laplace + }) + + if self.config.learned_background: + out_bg = self.forward_bg_(rays) + else: + out_bg = { + # 'actual_colors': self.background_color[None,:].expand(*actual_colors.shape), + 'num_samples': torch.zeros_like(out['num_samples']), + 'rays_valid': torch.zeros_like(out['rays_valid']) + } + out_full = { + # 'actual_colors': out['actual_colors'] + out_bg['actual_colors'] * (1.0 - out['opacity']), + 'num_samples': out['num_samples'] + out_bg['num_samples'], + 'rays_valid': out['rays_valid'] | out_bg['rays_valid'] + } + + return { + **out, + **{k + '_bg': v for k, v in out_bg.items()}, + **{k + '_full': v for k, v in out_full.items()} + } + + + + + def forward(self, rays_dict, laser_kernel): + ''' + Performs forward pass from rays dict from the system to the model + the rays_dict contains the rays and the corresponding metadata + in the form of {something_rays: {"rays": rays, "metadata": metadata}} + ''' + training_rays = rays_dict["training_rays"]["rays"] + stage = rays_dict["stage"] + use_regnerf = bool(rays_dict.get("use_regnerf", self.config.use_reg_nerf)) + if self.training: + out = {} + if use_regnerf and "regnerf_patch" in rays_dict: + regnerf_patch = rays_dict["regnerf_patch"]["rays"] + regnerf_out = self.forward_regnerf(regnerf_patch, laser_kernel) + out.update(regnerf_out) + + out.update(self.forward_(training_rays, laser_kernel)) + if stage == "validation": + if use_regnerf and "regnerf_patch" in rays_dict: + regnerf_patch = rays_dict["regnerf_patch"]["rays"] + out = chunk_batch(self.forward_, self.config.ray_chunk, True, regnerf_patch, laser_kernel) + else: + out = chunk_batch(self.forward_, self.config.ray_chunk, True, training_rays, laser_kernel) + elif stage =="test": + out = chunk_batch(self.forward_, self.config.ray_chunk, True, training_rays, laser_kernel) + return { + **out, + 'inv_s': self.variance.inv_s + } + + def train(self, mode=True): + self.randomized = mode and self.config.randomized + return super().train(mode=mode) + + def eval(self): + self.randomized = False + return super().eval() + + def regularizations(self, out): + losses = {} + losses.update(self.geometry.regularizations(out)) + losses.update(self.texture.regularizations(out)) + return losses + + @torch.no_grad() + def export(self, export_config): + mesh = self.isosurface() + if export_config.export_vertex_color: + _, sdf_grad, feature = chunk_batch(self.geometry, export_config.chunk_size, False, mesh['v_pos'].to(self.rank), with_grad=True, with_feature=True) + normal = F.normalize(sdf_grad, p=2, dim=-1) + rgb = self.texture(feature, -normal, normal) # set the viewing directions to the normal to get "albedo" + rgb = torch.sigmoid(torch.log(rgb)) #Remap to 0-1 in order to get the right colors + mesh['v_rgb'] = rgb.cpu() + return mesh diff --git a/codes/reconstruction/transientangelo/models/geometry.py b/codes/reconstruction/transientangelo/models/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..c91d8d76bf205eef536ff74e19c27f66ad8e39e3 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/geometry.py @@ -0,0 +1,322 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import pdb +from pytorch_lightning.utilities.rank_zero import rank_zero_info +import models as models +from models.base import BaseModel +from models.utils import scale_anything, get_activation, cleanup, chunk_batch +from models.network_utils import get_encoding, get_mlp, get_encoding_with_network +from models.nerfacc_compat import ContractionType +from utils.misc import get_rank +from systems.utils import update_module_step + + +def _get_aabb_bounds(radius, scene_aabb, ref_tensor): + if scene_aabb is None: + bmin = torch.as_tensor( + [-radius, -radius, -radius], + dtype=ref_tensor.dtype, + device=ref_tensor.device, + ) + bmax = torch.as_tensor( + [radius, radius, radius], + dtype=ref_tensor.dtype, + device=ref_tensor.device, + ) + else: + aabb = torch.as_tensor(scene_aabb, dtype=ref_tensor.dtype, device=ref_tensor.device).reshape(-1) + if aabb.numel() != 6: + raise ValueError(f"scene_aabb must have 6 elements, got {aabb.numel()}") + bmin, bmax = aabb[:3], aabb[3:] + return bmin, bmax + + +def contract_to_unisphere(x, radius, contraction_type, scene_aabb=None): + if contraction_type == ContractionType.AABB: + bmin, bmax = _get_aabb_bounds(radius, scene_aabb, x) + x = scale_anything(x, (bmin, bmax), (0, 1)) + elif contraction_type == ContractionType.UN_BOUNDED_SPHERE: + x = scale_anything(x, (-radius, radius), (0, 1)) + x = x * 2 - 1 # aabb is at [-1, 1] + mag = x.norm(dim=-1, keepdim=True) + mask = mag.squeeze(-1) > 1 + x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask]) + x = x / 4 + 0.5 # [-inf, inf] is at [0, 1] + else: + raise NotImplementedError + return x + + +class MarchingCubeHelper(nn.Module): + def __init__(self, resolution, use_torch=True): + super().__init__() + self.resolution = resolution + self.use_torch = use_torch + self.points_range = (0, 1) + + import mcubes + self.mc_func = mcubes.marching_cubes + self.verts = None + + def grid_vertices(self): + if self.verts is None: + #The resolution controlls the number of vertices sampled + x, y, z = torch.linspace(*self.points_range, self.resolution), torch.linspace(*self.points_range, self.resolution), torch.linspace(*self.points_range, self.resolution) + x, y, z = torch.meshgrid(x, y, z, indexing='ij') + verts = torch.cat([x.reshape(-1, 1), y.reshape(-1, 1), z.reshape(-1, 1)], dim=-1).reshape(-1, 3) + self.verts = verts + return self.verts + + def forward(self, level, threshold=0.): + level = level.float().view(self.resolution, self.resolution, self.resolution) + if self.use_torch: + verts, faces = self.mc_func(level.to(get_rank()), threshold) + verts, faces = verts.cpu(), faces.cpu().long() + else: + verts, faces = self.mc_func(-level.numpy(), threshold) # transform to numpy + verts, faces = torch.from_numpy(verts.astype(np.float32)), torch.from_numpy(faces.astype(np.int64)) # transform back to pytorch + verts = verts / (self.resolution - 1.) + return { + 'v_pos': verts, + 't_pos_idx': faces + } + + +class BaseImplicitGeometry(BaseModel): + def __init__(self, config): + super().__init__(config) + if self.config.isosurface is not None: + assert self.config.isosurface.method in ['mc', 'mc-torch'] + if self.config.isosurface.method == 'mc-torch': + raise NotImplementedError("Please do not use mc-torch. It currently has some scaling issues I haven't fixed yet.") + self.helper = MarchingCubeHelper(self.config.isosurface.resolution, use_torch=self.config.isosurface.method=='mc-torch') + self.radius = self.config.radius + self.contraction_type = None # assigned in system + self.scene_aabb = None + + def forward_level(self, points): + raise NotImplementedError + + def isosurface_(self, vmin, vmax): + def batch_func(x): + x = torch.stack([ + scale_anything(x[...,0], (0, 1), (vmin[0], vmax[0])), + scale_anything(x[...,1], (0, 1), (vmin[1], vmax[1])), + scale_anything(x[...,2], (0, 1), (vmin[2], vmax[2])), + ], dim=-1).to(self.rank) + rv = self.forward_level(x).cpu() #calls forward_level of volume density class + cleanup() + return rv + + #NOTE: Need to ensure that self.config.isosurface.chunk is a divisor of self.helper.grid_vertices().shape[0] + #NOTE: self.helper.grid_vertices() depend on resolution + + level = chunk_batch(batch_func, self.config.isosurface.chunk, True, self.helper.grid_vertices()) #same shape as grid_vertices + + mesh = self.helper(level, threshold=self.config.isosurface.threshold) + if torch.isnan(mesh['v_pos']).any(): + print("Warning: NaNs found in the mesh. Removing them and reshifting the faces.") + #Find any NaNs in the mesh and remove them and the corresponding faces + vertices_to_remove = torch.isnan(mesh["v_pos"]).any(dim=1) + filtered_vertices = mesh["v_pos"][~vertices_to_remove] #vertices with no NaNs + + index_mapping = torch.full((mesh["v_pos"].size(0),), -1, dtype=torch.long) #creates a tensor of -1 with the same size as old vertices + index_mapping[~vertices_to_remove] = torch.arange(filtered_vertices.size(0)) #creates a mapping from old vertices to new vertices + + valid_faces_mask = ~vertices_to_remove[mesh["t_pos_idx"]].any(dim=1) #Checks if any of the vertices in the faces are NaN (shape (n_faces,) + filtered_faces = mesh["t_pos_idx"][valid_faces_mask] #faces with no NaNs + updated_faces = index_mapping[filtered_faces] + + mesh["v_pos"] = filtered_vertices + mesh["t_pos_idx"] = updated_faces + + mesh['v_pos'] = torch.stack([ + scale_anything(mesh['v_pos'][...,0], (0, 1), (vmin[0], vmax[0])), + scale_anything(mesh['v_pos'][...,1], (0, 1), (vmin[1], vmax[1])), + scale_anything(mesh['v_pos'][...,2], (0, 1), (vmin[2], vmax[2])) + ], dim=-1) + return mesh + + @torch.no_grad() + def isosurface(self): + if self.config.isosurface is None: + raise NotImplementedError + if getattr(self, "scene_aabb", None) is not None: + scene_aabb = torch.as_tensor(self.scene_aabb, dtype=torch.float32).reshape(-1) + if scene_aabb.numel() != 6: + raise ValueError(f"scene_aabb must have 6 elements, got {scene_aabb.numel()}") + bounds_min = scene_aabb[:3] + bounds_max = scene_aabb[3:] + else: + bounds_min = torch.as_tensor( + [-self.radius, -self.radius, -self.radius], dtype=torch.float32 + ) + bounds_max = torch.as_tensor( + [self.radius, self.radius, self.radius], dtype=torch.float32 + ) + + mesh_coarse = self.isosurface_(bounds_min, bounds_max) + vmin, vmax = mesh_coarse['v_pos'].amin(dim=0), mesh_coarse['v_pos'].amax(dim=0) + vmin_ = torch.maximum(vmin - (vmax - vmin) * 0.1, bounds_min) + vmax_ = torch.minimum(vmax + (vmax - vmin) * 0.1, bounds_max) + mesh_fine = self.isosurface_(vmin_, vmax_) + return mesh_fine + + +@models.register('volume-density') +class VolumeDensity(BaseImplicitGeometry): + def setup(self): + self.n_input_dims = self.config.get('n_input_dims', 3) + self.n_output_dims = self.config.feature_dim + self.encoding_with_network = get_encoding_with_network(self.n_input_dims, self.n_output_dims, self.config.xyz_encoding_config, self.config.mlp_network_config) + + def forward(self, points): + #Verified to be the same as transient NeRF + points = contract_to_unisphere( + points, self.radius, self.contraction_type, getattr(self, "scene_aabb", None) + ) #the same as transient nerf + out = self.encoding_with_network(points.view(-1, self.n_input_dims)).view(*points.shape[:-1], self.n_output_dims).float() + density, feature = out[...,0], out + selector = ((points > 0.0) & (points < 1.0)).all(dim=-1) + if 'density_activation' in self.config: + density = get_activation(self.config.density_activation)(density + float(self.config.density_bias)) + if 'feature_activation' in self.config: + feature = get_activation(self.config.feature_activation)(feature) + density = density * selector #zero out densities that fall out of selector + return density, feature + + def forward_level(self, points): + points = contract_to_unisphere( + points, self.radius, self.contraction_type, getattr(self, "scene_aabb", None) + ) + density = self.encoding_with_network(points.reshape(-1, self.n_input_dims)).reshape(*points.shape[:-1], self.n_output_dims)[...,0] + if 'density_activation' in self.config: + density = get_activation(self.config.density_activation)(density + float(self.config.density_bias)) + return -density + + def update_step(self, epoch, global_step): + update_module_step(self.encoding_with_network, epoch, global_step) + + +@models.register('volume-sdf') +class VolumeSDF(BaseImplicitGeometry): + def setup(self): + self.n_output_dims = self.config.feature_dim + encoding = get_encoding(3, self.config.xyz_encoding_config) + network = get_mlp(encoding.n_output_dims, self.n_output_dims, self.config.mlp_network_config) + self.encoding, self.network = encoding, network + self.grad_type = self.config.grad_type + self.finite_difference_eps = self.config.get('finite_difference_eps', 1e-3) + self.register_buffer('_finite_difference_eps', torch.zeros(1, dtype=torch.float32)) + + # the actual value used in training + # will update at certain steps if finite_difference_eps="progressive" + if self.grad_type == 'finite_difference' and isinstance(self.finite_difference_eps, float): + rank_zero_info(f"Using constant finite difference to compute gradients with eps={self.finite_difference_eps}") + + def forward(self, points, with_grad=True, with_feature=True, with_laplace=False): + with torch.inference_mode(torch.is_inference_mode_enabled() and not (with_grad and self.grad_type == 'analytic')): + with torch.set_grad_enabled(self.training or (with_grad and self.grad_type == 'analytic')): + if with_grad and self.grad_type == 'analytic': + if not self.training: + points = points.clone() # points may be in inference mode, get a copy to enable grad + points.requires_grad_(True) + + points_ = points # points in the original scale + points = contract_to_unisphere( + points, self.radius, self.contraction_type, getattr(self, "scene_aabb", None) + ) # points normalized to (0, 1) + out = self.network(self.encoding(points.view(-1, 3))).view(*points.shape[:-1], self.n_output_dims).float() + + sdf, feature = out[...,0], out + if 'sdf_activation' in self.config: + sdf = get_activation(self.config.sdf_activation)(sdf + float(self.config.sdf_bias)) + if 'feature_activation' in self.config: + feature = get_activation(self.config.feature_activation)(feature) + if with_grad: + if self.grad_type == 'analytic': + grad = torch.autograd.grad( + sdf, points_, grad_outputs=torch.ones_like(sdf), + create_graph=True, retain_graph=True, only_inputs=True + )[0] + elif self.grad_type == 'finite_difference': + eps = self._finite_difference_eps.item() + offsets = torch.as_tensor( + [ + [eps, 0.0, 0.0], + [-eps, 0.0, 0.0], + [0.0, eps, 0.0], + [0.0, -eps, 0.0], + [0.0, 0.0, eps], + [0.0, 0.0, -eps], + ] + ).to(points_) + bounds_min, bounds_max = _get_aabb_bounds( + self.radius, getattr(self, "scene_aabb", None), points_ + ) + points_d_ = torch.minimum( + torch.maximum(points_[..., None, :] + offsets, bounds_min), + bounds_max, + ) + points_d = scale_anything(points_d_, (bounds_min, bounds_max), (0, 1)) + points_d_sdf = self.network(self.encoding(points_d.view(-1, 3)))[...,0].view(*points.shape[:-1], 6).float() + grad = 0.5 * (points_d_sdf[..., 0::2] - points_d_sdf[..., 1::2]) / eps + + if with_laplace: + laplace = (points_d_sdf[..., 0::2] + points_d_sdf[..., 1::2] - 2 * sdf[..., None]).sum(-1) / (eps ** 2) + + rv = [sdf] + if with_grad: + rv.append(grad) + if with_feature: + rv.append(feature) + if with_laplace: + assert self.config.grad_type == 'finite_difference', "Laplace computation is only supported with grad_type='finite_difference'" + rv.append(laplace) + rv = [v if self.training else v.detach() for v in rv] + return rv[0] if len(rv) == 1 else rv + + def forward_level(self, points): + points = contract_to_unisphere( + points, self.radius, self.contraction_type, getattr(self, "scene_aabb", None) + ) # points normalized to (0, 1) + sdf = self.network(self.encoding(points.view(-1, 3))).view(*points.shape[:-1], self.n_output_dims)[...,0] + if 'sdf_activation' in self.config: + sdf = get_activation(self.config.sdf_activation)(sdf + float(self.config.sdf_bias)) + return sdf + + def update_step(self, epoch, global_step): + update_module_step(self.encoding, epoch, global_step) + update_module_step(self.network, epoch, global_step) + if self.grad_type == 'finite_difference': + + #Logic: if self.finite_difference_eps is a float, use constant finite_diff_eps. Else, update it based on neuralangelo's update equation + if isinstance(self.finite_difference_eps, float): + self._finite_difference_eps.fill_(self.finite_difference_eps) + + + elif self.finite_difference_eps == 'progressive': + #NOTE: progressive finite_difference_eps + hg_conf = self.config.xyz_encoding_config + assert hg_conf.otype == "ProgressiveBandHashGrid", "finite_difference_eps='progressive' only works with ProgressiveBandHashGrid" + current_level = min( + hg_conf.start_level + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps, + hg_conf.n_levels + ) + grid_res = hg_conf.base_resolution * hg_conf.per_level_scale**(current_level - 1) + #NOTE: captured dataset actually has a much smaller grid size, so the finite difference epsilon starts out much smaller + if getattr(self, "scene_aabb", None) is not None: + scene_aabb = torch.as_tensor(self.scene_aabb, dtype=torch.float32).reshape(-1) + if scene_aabb.numel() != 6: + raise ValueError(f"scene_aabb must have 6 elements, got {scene_aabb.numel()}") + scene_extent = float((scene_aabb[3:] - scene_aabb[:3]).max().item()) + else: + scene_extent = 2 * float(self.config.radius) + grid_size = scene_extent / grid_res + if grid_size != self._finite_difference_eps: + rank_zero_info(f"\n Update finite_difference_eps to {grid_size} 🧞") + self._finite_difference_eps.fill_(grid_size) + else: + raise ValueError(f"Unknown finite_difference_eps={self.finite_difference_eps}") diff --git a/codes/reconstruction/transientangelo/models/mesh_utils.py b/codes/reconstruction/transientangelo/models/mesh_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2f885e05f02f6249fe2736348b41f4acba960108 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/mesh_utils.py @@ -0,0 +1,45 @@ +import argparse + +import torch +import numpy as np + +# pip install trimesh[all] +import trimesh +#Code from https://github.com/NVlabs/nvdiffrec/issues/71 + +# https://github.com/otaheri/chamfer_distance + + +def as_mesh(scene_or_mesh): + if isinstance(scene_or_mesh, trimesh.Scene): + assert len(scene_or_mesh.geometry) > 0 + mesh = trimesh.util.concatenate( + tuple(trimesh.Trimesh(vertices=g.vertices, faces=g.faces) + for g in scene_or_mesh.geometry.values())) + else: + assert isinstance(scene_or_mesh, trimesh.Trimesh) + mesh = scene_or_mesh + return mesh + +def sample_mesh(m, n): + vpos, _ = trimesh.sample.sample_surface(m, n) + return torch.tensor(vpos, dtype=torch.float32, device="cuda") + + +def calculate_chamfer_distance(mesh_path, ref_mesh_path, n): + ''' + Given two meshes, sample n points from each mesh and calculate the chamfer distance between the two sets of points. + ''' + from chamfer_distance import ChamferDistance + chamfer_dist = ChamferDistance() + mesh = as_mesh(trimesh.load_mesh(mesh_path)) + ref = as_mesh(trimesh.load_mesh(ref_mesh_path)) + # Make sure l=1.0 maps to 1/10th of the AABB. https://arxiv.org/pdf/1612.00603.pdf + scale = 10.0 / np.amax(np.amax(ref.vertices, axis=0) - np.amin(ref.vertices, axis=0)) + mesh.vertices = mesh.vertices * scale + ref.vertices = ref.vertices * scale + vpos_mesh = sample_mesh(mesh, n) #(n, 3) + vpos_ref = sample_mesh(ref, n) #(n, 3) + dist1, dist2,_,_ = chamfer_dist(vpos_mesh[None, ...], vpos_ref[None, ...]) + loss = (torch.mean(dist1) + torch.mean(dist2)).item() + return loss \ No newline at end of file diff --git a/codes/reconstruction/transientangelo/models/nerfacc_compat.py b/codes/reconstruction/transientangelo/models/nerfacc_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..f47165f2e7830eb7ad9441a34945b1a0dc660753 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/nerfacc_compat.py @@ -0,0 +1,212 @@ +import inspect +import importlib +import warnings +from enum import Enum + +import torch + +_NerfAccOccupancyGrid = None +_OccGridEstimator = None +_OCC_IMPL = None + +try: + from nerfacc import OccupancyGrid as _NerfAccOccupancyGrid + + _OCC_IMPL = "occupancy_grid" +except ImportError: + try: + from nerfacc.grid import OccupancyGrid as _NerfAccOccupancyGrid + + _OCC_IMPL = "occupancy_grid" + except ImportError: + try: + from nerfacc.estimators.occ_grid import OccGridEstimator as _OccGridEstimator + + _OCC_IMPL = "occ_grid_estimator" + except ImportError as ex: + raise ImportError( + "Cannot import nerfacc OccupancyGrid/OccGridEstimator. " + "Please install a compatible nerfacc version (e.g. 0.3.3)." + ) from ex + +try: + from nerfacc import ContractionType as _NerfAccContractionType + + ContractionType = _NerfAccContractionType +except ImportError: + # nerfacc>=0.5 removed this enum from public API. + class ContractionType(Enum): + AABB = "AABB" + UN_BOUNDED_SPHERE = "UN_BOUNDED_SPHERE" + + +if _OCC_IMPL == "occupancy_grid": + _OCC_SIG = inspect.signature(_NerfAccOccupancyGrid.__init__) + _OCC_PARAMS = _OCC_SIG.parameters + _OCC_HAS_CONTRACTION = "contraction_type" in _OCC_PARAMS + _OCC_HAS_ROI_AABB = "roi_aabb" in _OCC_PARAMS + _OCC_HAS_AABB = "aabb" in _OCC_PARAMS +else: + _OCC_HAS_CONTRACTION = False + _OCC_HAS_ROI_AABB = False + _OCC_HAS_AABB = False +_WARNED_CONTRACTION_DROP = False +_WARNED_ESTIMATOR_FALLBACK = False + + +try: + from nerfacc.intersection import ray_aabb_intersect as _nerfacc_ray_aabb_intersect +except ImportError: + try: + from nerfacc.grid import ray_aabb_intersect as _nerfacc_ray_aabb_intersect + except ImportError: + _nerfacc_ray_aabb_intersect = None + + +def _import_api(candidates, api_name: str): + for mod_name, attr_name in candidates: + try: + mod = importlib.import_module(mod_name) + except ImportError: + continue + if hasattr(mod, attr_name): + return getattr(mod, attr_name) + raise ImportError( + f"Cannot find nerfacc API '{api_name}'. " + "Please install a compatible nerfacc version (recommended: 0.3.3), " + "or extend models/nerfacc_compat.py for your installed version." + ) + + +ray_marching = _import_api( + [ + ("nerfacc", "ray_marching"), + ("nerfacc.ray_marching", "ray_marching"), + ("nerfacc.grid", "ray_marching"), + ], + "ray_marching", +) + +render_weight_from_density = _import_api( + [ + ("nerfacc", "render_weight_from_density"), + ("nerfacc.volrend", "render_weight_from_density"), + ], + "render_weight_from_density", +) + +render_weight_from_alpha = _import_api( + [ + ("nerfacc", "render_weight_from_alpha"), + ("nerfacc.volrend", "render_weight_from_alpha"), + ], + "render_weight_from_alpha", +) + +accumulate_along_rays = _import_api( + [ + ("nerfacc", "accumulate_along_rays"), + ("nerfacc.volrend", "accumulate_along_rays"), + ], + "accumulate_along_rays", +) + + +def make_occupancy_grid(roi_aabb, resolution, contraction_type=None): + global _WARNED_CONTRACTION_DROP, _WARNED_ESTIMATOR_FALLBACK + + if _OCC_IMPL == "occ_grid_estimator": + # nerfacc newer API fallback. + kwargs = { + "roi_aabb": roi_aabb, + "resolution": resolution, + } + try: + estimator = _OccGridEstimator(levels=1, **kwargs) + except TypeError: + estimator = _OccGridEstimator(**kwargs) + + if contraction_type not in (None, ContractionType.AABB) and not _WARNED_ESTIMATOR_FALLBACK: + warnings.warn( + "Using OccGridEstimator fallback (no contraction_type support). " + "Results may differ from legacy OccupancyGrid behavior.", + RuntimeWarning, + ) + _WARNED_ESTIMATOR_FALLBACK = True + + class _EstimatorAdapter: + def __init__(self, est): + self._est = est + + def every_n_step(self, step, occ_eval_fn, occ_thre=0.01, ema_decay=0.95): + try: + self._est.update_every_n_steps( + step=step, + occ_eval_fn=occ_eval_fn, + occ_thre=occ_thre, + ema_decay=ema_decay, + ) + except TypeError: + self._est.update_every_n_steps(step=step, occ_eval_fn=occ_eval_fn, occ_thre=occ_thre) + + def sampling(self, *args, **kwargs): + return self._est.sampling(*args, **kwargs) + + def __getattr__(self, name): + return getattr(self._est, name) + + return _EstimatorAdapter(estimator) + + kwargs = {} + if _OCC_HAS_ROI_AABB: + kwargs["roi_aabb"] = roi_aabb + elif _OCC_HAS_AABB: + kwargs["aabb"] = roi_aabb + else: + # Extremely old/new API fallback: use positional for bbox-like arg. + return _NerfAccOccupancyGrid(roi_aabb, resolution) + + kwargs["resolution"] = resolution + + if _OCC_HAS_CONTRACTION: + if contraction_type is not None: + kwargs["contraction_type"] = contraction_type + else: + if contraction_type not in (None, ContractionType.AABB) and not _WARNED_CONTRACTION_DROP: + warnings.warn( + "Installed nerfacc does not support OccupancyGrid.contraction_type; " + "falling back to default grid behavior.", + RuntimeWarning, + ) + _WARNED_CONTRACTION_DROP = True + + return _NerfAccOccupancyGrid(**kwargs) + + +def ray_aabb_intersect(rays_o, rays_d, aabb): + if _nerfacc_ray_aabb_intersect is not None: + return _nerfacc_ray_aabb_intersect(rays_o, rays_d, aabb) + + # Fallback intersection if nerfacc API path changed. + aabb = aabb.to(rays_o.device, dtype=rays_o.dtype) + aabb_min = aabb[:3] + aabb_max = aabb[3:] + inv_d = 1.0 / torch.where(torch.abs(rays_d) < 1e-12, torch.full_like(rays_d, 1e-12), rays_d) + + t0 = (aabb_min - rays_o) * inv_d + t1 = (aabb_max - rays_o) * inv_d + + t_near = torch.minimum(t0, t1).amax(dim=-1, keepdim=True) + t_far = torch.maximum(t0, t1).amin(dim=-1, keepdim=True) + + miss = t_far < t_near + t_near = torch.where(miss, torch.full_like(t_near, float("inf")), t_near) + t_far = torch.where(miss, torch.zeros_like(t_far), t_far) + return t_near, t_far + + +def get_ray_marching_grid(grid_obj): + # OccGridEstimator fallback should not be passed as `grid=...` to legacy ray_marching API. + if _OCC_IMPL == "occ_grid_estimator": + return None + return grid_obj diff --git a/codes/reconstruction/transientangelo/models/network_utils.py b/codes/reconstruction/transientangelo/models/network_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5221cb57bd3c0d1f8761e97dbfbc62df6e85899f --- /dev/null +++ b/codes/reconstruction/transientangelo/models/network_utils.py @@ -0,0 +1,219 @@ +import math +import numpy as np + +import torch +import torch.nn as nn +import tinycudann as tcnn + +from pytorch_lightning.utilities.rank_zero import rank_zero_debug, rank_zero_info + +from utils.misc import config_to_primitive, get_rank +from models.utils import get_activation +from systems.utils import update_module_step + +class VanillaFrequency(nn.Module): + def __init__(self, in_channels, config): + super().__init__() + self.N_freqs = config['n_frequencies'] + self.in_channels, self.n_input_dims = in_channels, in_channels + self.funcs = [torch.sin, torch.cos] + self.freq_bands = 2**torch.linspace(0, self.N_freqs-1, self.N_freqs) + self.n_output_dims = self.in_channels * (len(self.funcs) * self.N_freqs) + self.n_masking_step = config.get('n_masking_step', 0) + self.update_step(None, None) # mask should be updated at the beginning each step + + def forward(self, x): + out = [] + for freq, mask in zip(self.freq_bands, self.mask): + for func in self.funcs: + out += [func(freq*x) * mask] + return torch.cat(out, -1) + + def update_step(self, epoch, global_step): + if self.n_masking_step <= 0 or global_step is None: + self.mask = torch.ones(self.N_freqs, dtype=torch.float32) + else: + self.mask = (1. - torch.cos(math.pi * (global_step / self.n_masking_step * self.N_freqs - torch.arange(0, self.N_freqs)).clamp(0, 1))) / 2. + rank_zero_debug(f'Update mask: {global_step}/{self.n_masking_step} {self.mask}') + + +class ProgressiveBandHashGrid(nn.Module): + def __init__(self, in_channels, config): + super().__init__() + self.n_input_dims = in_channels + encoding_config = config.copy() + encoding_config['otype'] = 'HashGrid' + with torch.cuda.device(get_rank()): + self.encoding = tcnn.Encoding(in_channels, encoding_config) + self.n_output_dims = self.encoding.n_output_dims + self.n_level = config['n_levels'] + self.n_features_per_level = config['n_features_per_level'] + self.start_level, self.start_step, self.update_steps = config['start_level'], config['start_step'], config['update_steps'] + self.register_buffer('current_level', torch.tensor([self.start_level], dtype=torch.long)) + rank_zero_info(f"Grid level is starting at {self.current_level.item()}") + self.register_buffer("mask", torch.zeros(self.n_level * self.n_features_per_level, dtype=torch.float32, device=get_rank())) + + def forward(self, x): + enc = self.encoding(x) #(n_samples, n_output_dims) + enc = enc * self.mask + return enc + + def update_step(self, epoch, global_step): + current_level = min(self.start_level + max(global_step - self.start_step, 0) // self.update_steps, self.n_level) + if current_level > self.current_level.item(): + rank_zero_info(f' Update grid level to {current_level} 🍩') + self.current_level.fill_(current_level) + + #Every time the grid level upgrades, you unlock self.n_features_per_level from the encoder + self.mask[:self.current_level.item() * self.n_features_per_level] = 1. + + +class CompositeEncoding(nn.Module): + def __init__(self, encoding, include_xyz=False, xyz_scale=1., xyz_offset=0.): + super(CompositeEncoding, self).__init__() + self.encoding = encoding + self.include_xyz, self.xyz_scale, self.xyz_offset = include_xyz, xyz_scale, xyz_offset + self.n_output_dims = int(self.include_xyz) * self.encoding.n_input_dims + self.encoding.n_output_dims + + def forward(self, x, *args): + return self.encoding(x, *args) if not self.include_xyz else torch.cat([x * self.xyz_scale + self.xyz_offset, self.encoding(x, *args)], dim=-1) + + def update_step(self, epoch, global_step): + update_module_step(self.encoding, epoch, global_step) + + +def get_encoding(n_input_dims, config): + # input suppose to be range [0, 1] + if config.otype == 'VanillaFrequency': + encoding = VanillaFrequency(n_input_dims, config_to_primitive(config)) + elif config.otype == 'ProgressiveBandHashGrid': + encoding = ProgressiveBandHashGrid(n_input_dims, config_to_primitive(config)) + else: + with torch.cuda.device(get_rank()): + encoding = tcnn.Encoding(n_input_dims, config_to_primitive(config)) + encoding = CompositeEncoding(encoding, include_xyz=config.get('include_xyz', False), xyz_scale=2., xyz_offset=-1.) + return encoding + + +class VanillaMLP(nn.Module): + def __init__(self, dim_in, dim_out, config): + super().__init__() + self.n_neurons, self.n_hidden_layers = config['n_neurons'], config['n_hidden_layers'] + self.sphere_init, self.weight_norm = config.get('sphere_init', False), config.get('weight_norm', False) + self.sphere_init_radius = config.get('sphere_init_radius', 0.5) + self.layers = [self.make_linear(dim_in, self.n_neurons, is_first=True, is_last=False), self.make_activation()] + for i in range(self.n_hidden_layers - 1): + self.layers += [self.make_linear(self.n_neurons, self.n_neurons, is_first=False, is_last=False), self.make_activation()] + self.layers += [self.make_linear(self.n_neurons, dim_out, is_first=False, is_last=True)] + self.layers = nn.Sequential(*self.layers) + self.output_activation = get_activation(config['output_activation']) + + @torch.cuda.amp.autocast(False) + def forward(self, x): + x = self.layers(x.float()) + x = self.output_activation(x) + return x + + def make_linear(self, dim_in, dim_out, is_first, is_last): + layer = nn.Linear(dim_in, dim_out, bias=True) # network without bias will degrade quality + if self.sphere_init: + if is_last: + torch.nn.init.constant_(layer.bias, -self.sphere_init_radius) + torch.nn.init.normal_(layer.weight, mean=math.sqrt(math.pi) / math.sqrt(dim_in), std=0.0001) + elif is_first: + torch.nn.init.constant_(layer.bias, 0.0) + torch.nn.init.constant_(layer.weight[:, 3:], 0.0) + torch.nn.init.normal_(layer.weight[:, :3], 0.0, math.sqrt(2) / math.sqrt(dim_out)) + else: + torch.nn.init.constant_(layer.bias, 0.0) + torch.nn.init.normal_(layer.weight, 0.0, math.sqrt(2) / math.sqrt(dim_out)) + else: + torch.nn.init.constant_(layer.bias, 0.0) + torch.nn.init.kaiming_uniform_(layer.weight, nonlinearity='relu') + + if self.weight_norm: + layer = nn.utils.weight_norm(layer) + return layer + + def make_activation(self): + if self.sphere_init: + return nn.Softplus(beta=100) + else: + return nn.ReLU(inplace=True) + + +def sphere_init_tcnn_network(n_input_dims, n_output_dims, config, network): + rank_zero_debug('Initialize tcnn MLP to approximately represent a sphere.') + """ + from https://github.com/NVlabs/tiny-cuda-nn/issues/96 + It's the weight matrices of each layer laid out in row-major order and then concatenated. + Notably: inputs and output dimensions are padded to multiples of 8 (CutlassMLP) or 16 (FullyFusedMLP). + The padded input dimensions get a constant value of 1.0, + whereas the padded output dimensions are simply ignored, + so the weights pertaining to those can have any value. + """ + padto = 16 if config.otype == 'FullyFusedMLP' else 8 + n_input_dims = n_input_dims + (padto - n_input_dims % padto) % padto + n_output_dims = n_output_dims + (padto - n_output_dims % padto) % padto + data = list(network.parameters())[0].data + assert data.shape[0] == (n_input_dims + n_output_dims) * config.n_neurons + (config.n_hidden_layers - 1) * config.n_neurons**2 + new_data = [] + # first layer + weight = torch.zeros((config.n_neurons, n_input_dims)).to(data) + torch.nn.init.constant_(weight[:, 3:], 0.0) + torch.nn.init.normal_(weight[:, :3], 0.0, math.sqrt(2) / math.sqrt(config.n_neurons)) + new_data.append(weight.flatten()) + # hidden layers + for i in range(config.n_hidden_layers - 1): + weight = torch.zeros((config.n_neurons, config.n_neurons)).to(data) + torch.nn.init.normal_(weight, 0.0, math.sqrt(2) / math.sqrt(config.n_neurons)) + new_data.append(weight.flatten()) + # last layer + weight = torch.zeros((n_output_dims, config.n_neurons)).to(data) + torch.nn.init.normal_(weight, mean=math.sqrt(math.pi) / math.sqrt(config.n_neurons), std=0.0001) + new_data.append(weight.flatten()) + new_data = torch.cat(new_data) + data.copy_(new_data) + + +def get_mlp(n_input_dims, n_output_dims, config): + if config.otype == 'VanillaMLP': + network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config)) + else: + with torch.cuda.device(get_rank()): + #NOTE: use network.params to inspect the weights of the network + network = tcnn.Network(n_input_dims, n_output_dims, config_to_primitive(config)) + if config.get('sphere_init', False): + sphere_init_tcnn_network(n_input_dims, n_output_dims, config, network) + return network + + +class EncodingWithNetwork(nn.Module): + def __init__(self, encoding, network): + super().__init__() + self.encoding, self.network = encoding, network + + def forward(self, x): + return self.network(self.encoding(x)) + + def update_step(self, epoch, global_step): + update_module_step(self.encoding, epoch, global_step) + update_module_step(self.network, epoch, global_step) + + +def get_encoding_with_network(n_input_dims, n_output_dims, encoding_config, network_config): + # input suppose to be range [0, 1] + if encoding_config.otype in ['VanillaFrequency', 'ProgressiveBandHashGrid'] \ + or network_config.otype in ['VanillaMLP']: + encoding = get_encoding(n_input_dims, encoding_config) + network = get_mlp(encoding.n_output_dims, n_output_dims, network_config) + encoding_with_network = EncodingWithNetwork(encoding, network) + else: + with torch.cuda.device(get_rank()): + encoding_with_network = tcnn.NetworkWithInputEncoding( + n_input_dims=n_input_dims, + n_output_dims=n_output_dims, + encoding_config=config_to_primitive(encoding_config), + network_config=config_to_primitive(network_config) + ) + return encoding_with_network diff --git a/codes/reconstruction/transientangelo/models/ray_utils.py b/codes/reconstruction/transientangelo/models/ray_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8b09aad08f6f69b4f848785e83178014e63a3356 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/ray_utils.py @@ -0,0 +1,618 @@ +import torch +import numpy as np +import scipy +import json +import torch.nn.functional as F +from scipy.optimize import minimize +import cv2 + + +def cast_rays(ori, dir, z_vals): + return ori[..., None, :] + z_vals[..., None] * dir[..., None, :] + + +def get_ray_directions(W, H, fx, fy, cx, cy, use_pixel_centers=True): + pixel_center = 0.5 if use_pixel_centers else 0 + i, j = np.meshgrid( + np.arange(W, dtype=np.float32) + pixel_center, + np.arange(H, dtype=np.float32) + pixel_center, + indexing='xy' + ) + i, j = torch.from_numpy(i), torch.from_numpy(j) + + directions = torch.stack([(i - cx) / fx, -(j - cy) / fy, -torch.ones_like(i)], -1) # (H, W, 3) + + return directions + + +def get_rays(directions, c2w, keepdim=False): + # Rotate ray directions from camera coordinate to the world coordinate + # rays_d = directions @ c2w[:, :3].T # (H, W, 3) # slow? + assert directions.shape[-1] == 3 + + if directions.ndim == 2: # (N_rays, 3) + assert c2w.ndim == 3 # (N_rays, 4, 4) / (1, 4, 4) + rays_d = (directions[:,None,:] * c2w[:,:3,:3]).sum(-1) # (N_rays, 3) + rays_o = c2w[:,:,3].expand(rays_d.shape) + elif directions.ndim == 3: # (H, W, 3) + if c2w.ndim == 2: # (4, 4) + rays_d = (directions[:,:,None,:] * c2w[None,None,:3,:3]).sum(-1) # (H, W, 3) + rays_o = c2w[None,None,:,3].expand(rays_d.shape) + elif c2w.ndim == 3: # (B, 4, 4) + rays_d = (directions[None,:,:,None,:] * c2w[:,None,None,:3,:3]).sum(-1) # (B, H, W, 3) + rays_o = c2w[:,None,None,:,3].expand(rays_d.shape) + + if not keepdim: + rays_o, rays_d = rays_o.reshape(-1, 3), rays_d.reshape(-1, 3) + + return rays_o, rays_d + + +def spatial_filter(x, y, sigma, rep, prob_dithering=False, normalize=True): + """ + Use of a truncated Gaussian to model the spatial footprint of the laser spot and SPAD sensor projected onto the scene + Rays are sampled at 4 standard deviations from the ray center weighting their contribution to the rendered transient by the corresponding Gaussian probability density function value. + + Args: + x (numpy.ndarray): The x pixel coordinates (n_rays) containing elements in the range (0, WIDTH) + y (numpy.ndarray): The y pixel coordinates (n_rays) containing elements in the range (0, HEIGHT) + sigma (float): The standard deviation of the Gaussian distribution. (0.15) + rep (int): The number of repetitions. + prob_dithering (bool, optional): Whether to use probabilistic dithering. Defaults to True. + normalize (bool, optional): Whether to normalize the weights. Defaults to True. + + + """ + + pdf_fn = lambda x: np.exp(-x/(2*sigma**2)) - np.exp(-16) + if prob_dithering: + #the bounds are determined by 4 standard deviations from ray center. + bounds_max = [4*sigma]*x.shape[0] + loc = 0 + # Generate s_x, s_y based on a truncated normal distribution with bounds as the first two arguments + s_x = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma) + s_y = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma) + weights = np.ones_like(s_x)*1/rep + + else: + s_x = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep)) #(self.rep, num_rays) + s_y = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep)) #(self.rep, num_rays) + dists = (s_x**2 + s_y**2) #Look at how far they are from the origin + weights = pdf_fn(dists) + if normalize: + weights = weights/weights.sum(0)[None, :] #if self.rep = 1, then the weights are all the same + s_x = s_x.flatten() + s_y = s_y.flatten() + weights = weights.flatten() + + #weights tell you the contribution of each of the repeated rays for a given pixel. For instance, if weights is of shape + #(3,16), this means that in your batch of 16 rays, you are additionally sampling two other rays. weights[:, i] tells you the + #contribution of each of the three rays for the ith ray, contribution sums up to 1 + return s_x, s_y, weights #(all are self.rep * num_rays) + +def normalize(v, eps=1e-8): + v = np.asarray(v, dtype=np.float32) + norm = np.linalg.norm(v) + if not np.isfinite(norm) or norm < eps: + raise ValueError(f"Cannot normalize vector with norm={norm}") + return v / norm + +def look_at(pf, pu, t, captured=False, eps=1e-6): + ''' + pf is the 3D that you're looking at + pu is the up vector + + Logic: since pf is not a direction vector, we calculate the forward vector by subtracting it with the camera origin (think -t + pf is the vector from origin to pf) + ''' + pf = np.asarray(pf, dtype=np.float32) + pu = np.asarray(pu, dtype=np.float32) + t = np.asarray(t, dtype=np.float32) + + f = normalize(pf - t, eps) #calculate the foward vector by normalizing the difference between the point of interest and the camera origin + pu = normalize(pu, eps) + r = np.cross(f, pu) #calculate the right vector by taking the cross product of the forward vector and the up vector + if not np.isfinite(r).all() or np.linalg.norm(r) < eps: + # RegNeRF occasionally samples unseen poses whose forward direction is almost parallel + # to the averaged up vector; fall back to a canonical axis to avoid NaN rotations. + fallback_axes = [ + np.array([1.0, 0.0, 0.0], dtype=np.float32), + np.array([0.0, 0.0, 1.0], dtype=np.float32), + np.array([0.0, 1.0, 0.0], dtype=np.float32), + ] + pu = min(fallback_axes, key=lambda axis: abs(float(np.dot(f, axis)))) + r = np.cross(f, pu) + r = normalize(r, eps) #normalize the right vector + u = normalize(np.cross(r, f), eps) #calculate the up vector by taking the cross product of the right vector and the forward vector + if not captured: + R = np.stack([r, u, -f], axis=1) + else: + R = np.stack([r, u, f], axis=1) + return R.astype(np.float32) + + + +def sample_point_interpolated(known_camera_locations, jitter_scale=0.05): + ''' + Sample an unseen camera location by interpolating between two random + training camera locations with small perturbation. This ensures the + unseen camera stays in a geometrically plausible region for captured scenes, + unlike sphere/box sampling which can place cameras in empty space. + ''' + n_cams = known_camera_locations.shape[0] + idx = torch.randperm(n_cams)[:min(2, n_cams)] + if n_cams >= 2: + alpha = torch.rand(1).item() + new_pos = (1 - alpha) * known_camera_locations[idx[0]] + alpha * known_camera_locations[idx[1]] + else: + new_pos = known_camera_locations[idx[0]].clone() + # Add small jitter proportional to the camera distribution extent + extent = (known_camera_locations.max(dim=0).values - known_camera_locations.min(dim=0).values).norm().item() + extent = max(extent, 1e-6) + new_pos = new_pos.float() + torch.randn(3) * jitter_scale * extent + return new_pos[0:1], new_pos[1:2], new_pos[2:3] + + +def sample_point_in_box(x_bounds, y_bounds, z_bounds, sample_boundary=True): + ''' + Sample a point on the boundary defined by x_bounds, y_bounds, z_bounds + ''' + + if sample_boundary: + boundary_choice = torch.randint(0, 3, (1,)).item() # 0 for x, 1 for y, 2 for z + + if boundary_choice == 0: # Fix x + x = x_bounds[torch.randint(0, 2, (1,)).item()].unsqueeze(0) + y = torch.rand(1) * (y_bounds[1] - y_bounds[0]) + y_bounds[0] + z = torch.rand(1) * (z_bounds[1] - z_bounds[0]) + z_bounds[0] + elif boundary_choice == 1: # Fix y + y = y_bounds[torch.randint(0, 2, (1,)).item()].unsqueeze(0) + x = torch.rand(1) * (x_bounds[1] - x_bounds[0]) + x_bounds[0] + z = torch.rand(1) * (z_bounds[1] - z_bounds[0]) + z_bounds[0] + else: # Fix z + z = z_bounds[torch.randint(0, 2, (1,)).item()].unsqueeze(0) + x = torch.rand(1) * (x_bounds[1] - x_bounds[0]) + x_bounds[0] + y = torch.rand(1) * (y_bounds[1] - y_bounds[0]) + y_bounds[0] + + #Verify the new camera location is within the box + assert x >= x_bounds[0].item() and x <= x_bounds[1].item() + assert y >= y_bounds[0].item() and y <= y_bounds[1].item() + assert z >= z_bounds[0].item() and z <= z_bounds[1].item() + + else: + x = torch.rand(1) * (x_bounds[1] - x_bounds[0]) + x_bounds[0] + y = torch.rand(1) * (y_bounds[1] - y_bounds[0]) + y_bounds[0] + z = torch.rand(1) * (z_bounds[1] - z_bounds[0]) + z_bounds[0] + assert x >= x_bounds[0].item() and x <= x_bounds[1].item() + assert y >= y_bounds[0].item() and y <= y_bounds[1].item() + assert z >= z_bounds[0].item() and z <= z_bounds[1].item() + return x, y, z + +def sample_point_in_sphere(mean_focus_point, known_camera_locations, sample_boundary=True): + ''' + Sample an unknown camera location on the sphere boundary using spherical coordinates defined as + x = radius*sin(\phi)cos(\theta) + center[0] + y = radius*sing(\phi)sin(\theta) + center[1] + z = radius*cos(\phi) + center[2] + Idea: + 1. randomly sample an azimuth angle from 0 to 2pi + 2. sample the cosine of the zenith angle from -1 to 1 + 3. apply arccos to the zenith angle + 4. plug in the values to the spherical coordinates + ''' + center = mean_focus_point + max_radius = torch.sum((known_camera_locations - center)**2, dim=1).mean().sqrt() + theta = torch.rand(1) * 2 * np.pi #sample an azimuth angle from 0 to 2pi + cos_zenith = torch.rand(1) * 2 - 1 #sample the cosine of the zenith angle from -1 to 1 + zenith = torch.acos(cos_zenith) #apply arccos to the zenith angle + + if sample_boundary: + x = max_radius*torch.sin(zenith)*torch.cos(theta) + center[0] + y = max_radius*torch.sin(zenith)*torch.sin(theta) + center[1] + z = max_radius*torch.cos(zenith) + center[2] + squared_distance = (x - center[0])**2 + (y - center[1])**2 + (z - center[2])**2 + assert torch.abs(squared_distance - max_radius**2) < 1e-4 + + else: + r = (torch.rand(1) ** (1/3)) * max_radius #volume scales with r^3 + x = r*torch.sin(zenith)*torch.cos(theta) + center[0] + y = r*torch.sin(zenith)*torch.sin(theta) + center[1] + z = r*torch.cos(zenith) + center[2] + squared_distance = (x - center[0])**2 + (y - center[1])**2 + (z - center[2])**2 + assert squared_distance < max_radius**2 + #Verify the new camera location is on the surface of the sphere + return x, y, z + + +def vectorized_distance_point_from_line(point, origins, directions): + """ + Vectorized computation of the smallest distance from a single point to multiple lines defined by origins + t*directions. + """ + point = np.array(point) + # Ensure the point is broadcastable over the origins and directions + point = point.reshape(1, -1) + # Compute projection factors + projection_factors = np.sum((point - origins) * directions, axis=1) / np.sum(directions * directions, axis=1) #(n_cameras,) + # Compute projections + projections = origins + (projection_factors[:, np.newaxis] * directions) #(n_cameras, 3) + # Calculate distances + distances = np.linalg.norm(projections - point, axis=1)**2 #adding squared to help with convergence + return distances + + +def find_mean_focus_point_regnerf(known_camera_locations, optical_axes): + origins, directions = known_camera_locations[...,None], optical_axes[...,None] + eye = torch.eye(3) + m = eye - directions * directions.permute(0, 2, 1) + mt_m = m.permute(0, 2, 1) @ m + mt_m_mean = mt_m.mean(dim=0) + origins_mean = (mt_m @ origins).mean(dim=0) + + # Solve for the focus point + focus_pt = torch.linalg.solve(mt_m_mean, origins_mean).squeeze(-1) + + return focus_pt + +def generate_unseen_poses(patch_size, img_wh, c2w, n_sparse_rays, bounding_form, mean_focus_point, write_poses=False, captured=False, sample_boundary=True, constrain_hemisphere=None): + ''' + Generate a random pose following https://arxiv.org/pdf/2112.00724v1.pdf RegNerf from known poses c2w. + Args: + patch_size: int, length the patch + img_wh: (h,w), image shape + c2w: (n_images, 4, 4), c2w matrix + n_sparse_rays: number of sparse rays that we are shooting + bounding_form: str, sampling from a box or a sphere + mean_focus_point: (3, ), the mean focus point of the existing cameras + use_sparse: bool, whether to generate sparse rays using the unseen_poses. + write_poses: bool, whether to write the poses to a json file for viz + captured: bool, if set to true, the generated look-at matrix will have forward axis inverted + sample_boundary: bool, if set to true, the unseen poses will only be sampled from the boundary + Output: + x_indices xx: (patch_size**2) + y_indices yy: (patch_size**2) + new_rotation_matrix: (3, 3) + new_translation_vector: (3, 1) + ''' + image_width, image_height = img_wh + + known_rotation_matrices = c2w[:, :3, :3].cpu() # (n_images, 3, 3) + + #1. First generate a random patch of size patch_size x patch_size + #Randomly generating indices and forming a patch + start_y = torch.randint(0, image_height - patch_size + 1, (1,)).item() + start_x = torch.randint(0, image_width - patch_size + 1, (1,)).item() + + # Generate the coordinates of the patch + rows = torch.arange(start_y, start_y + patch_size) + cols = torch.arange(start_x, start_x + patch_size) + + # Use meshgrid to create a grid of coordinates + xx, yy = torch.meshgrid(rows, cols, indexing='xy') + xx = xx.flatten() + yy = yy.flatten() + + # 2. Generate sparse image coordinates of shape (n_sparse_rays,1) + if n_sparse_rays > 0: + x_sparse = torch.randint(0, image_height, size=(n_sparse_rays,)) #(n_sparse_rays, ) + y_sparse = torch.randint(0, image_width, size=(n_sparse_rays,)) #(n_sparse_rays, ) + + #Combine both rays + xx, yy = torch.cat([xx, x_sparse]), torch.cat([yy, y_sparse]) #(patch_size**2 + n_sparse_rays, ) + + # 3. Compute pu + #Computes the average of the up vectors (second column) of the known rotation matrices + local_up = torch.tensor([0., 1., 0.]) + global_up = known_rotation_matrices.float() @ local_up #batch matrix multiplication (n_images, 3) transform in the global coordinate system, basically just taking the second column of the known camera pose + averaged_up = torch.mean(global_up, dim=0) #Average them across the n_images dimension + p_u = averaged_up/torch.linalg.norm(averaged_up) #Normalize the vector + + # 4. Compute pf + # Computes the point of smallest average distance to the optical axes of the known rotation matrices + optical_axes = known_rotation_matrices[..., 2] #each of the rows is normalized + known_camera_locations = c2w[:, :3, -1] # (n_images, 3) + + + p_f = mean_focus_point + torch.normal(0, 0.125, size=(mean_focus_point.shape[0],)) #adding random jitter to the focal point + + # 5. Compute the new camera origin + x_bounds = torch.min(known_camera_locations[:, 0]), torch.max(known_camera_locations[:, 0]) + y_bounds = torch.min(known_camera_locations[:, 1]), torch.max(known_camera_locations[:, 1]) + z_bounds = torch.min(known_camera_locations[:, 2]), torch.max(known_camera_locations[:, 2]) + + # Hemisphere constraint: for captured scenes, only sample unseen cameras on the same + # side of the scene as the existing cameras, avoiding positions behind/above the scene. + if constrain_hemisphere is None: + constrain_hemisphere = captured # enable by default for captured datasets + if constrain_hemisphere: + mean_cam_dir = (known_camera_locations - mean_focus_point).float().mean(dim=0) + mean_cam_dir = mean_cam_dir / (mean_cam_dir.norm() + 1e-8) + + unseen_rotation_matrix = None + unseen_camera_origin = None + max_pose_attempts = 64 # increased to account for hemisphere rejection + for _ in range(max_pose_attempts): + if bounding_form == "box": + new_location_x, new_location_y, new_location_z = sample_point_in_box(x_bounds, y_bounds, z_bounds, sample_boundary) + elif bounding_form == "sphere": + new_location_x, new_location_y, new_location_z = sample_point_in_sphere(mean_focus_point, known_camera_locations, sample_boundary) + elif bounding_form == "interpolation": + new_location_x, new_location_y, new_location_z = sample_point_interpolated(known_camera_locations) + else: + raise ValueError("Bounding form not recognized") + + candidate_origin = torch.cat((new_location_x, new_location_y, new_location_z), dim=0) + + # Reject candidates in the opposite hemisphere (back-side of scene) + if constrain_hemisphere: + cand_dir = (candidate_origin - mean_focus_point).float() + cand_dir = cand_dir / (cand_dir.norm() + 1e-8) + if torch.dot(cand_dir, mean_cam_dir) <= 0.0: + continue + + try: + candidate_rotation = look_at(p_f, p_u, candidate_origin, captured) + except ValueError: + continue + if np.isfinite(candidate_rotation).all(): + unseen_camera_origin = candidate_origin + unseen_rotation_matrix = candidate_rotation + break + + if unseen_rotation_matrix is None or unseen_camera_origin is None: + raise RuntimeError("Failed to sample a finite RegNeRF unseen pose after multiple attempts") + + #Concatenate the rotation matrix and the translation vector + # Uncomment the following lines to visualize the camera locations + if write_poses: + #NOTE: make sure to change the paths and the frame + unseen_c2w = np.concatenate((unseen_rotation_matrix, unseen_camera_origin[:, None]), axis=1) + unseen_c2w = np.concatenate((unseen_c2w, torch.tensor([0., 0., 0., 1.]).reshape(1, 4)), axis=0) + unseen_c2w = unseen_c2w.tolist() + #Open + json_file_path = '/scratch/ondemand28/weihanluo/multiview_transient_project/instant-nsr-pl/load/transient_nerf_synthetic/lego/lego_jsons/two_views/unseen_train.json' + with open(json_file_path, 'r') as file: + data = json.load(file) + new_frame = { + "file_path": "./train/r_new", + "rotation": data["frames"][0]["rotation"], + "transform_matrix": unseen_c2w + } + data["frames"].append(new_frame) + with open(json_file_path, 'w') as file: + json.dump(data, file, indent=4) + + + return xx, yy, unseen_rotation_matrix, unseen_camera_origin + + + +class LearnRays(torch.nn.Module): + ''' + This is used to generate rays direction for the captured dataset + ''' + def __init__(self, rays, device ="cuda:0", img_shape = (256, 256)): + """ + :param num_cams: + :param learn_R: True/False + :param learn_t: True/False + :param init_c2w: (N, 4, 4) torch tensor + """ + super(LearnRays, self).__init__() + self.device = device + self.init_c2w = None + self.height = int(img_shape[1]) if len(img_shape) > 1 else int(img_shape[0]) + self.width = int(img_shape[0]) + self.img_shape = (self.width, self.height) + + rays = np.asarray(rays, dtype=np.float32) + if rays.ndim != 3 or rays.shape[-1] != 3: + raise ValueError(f"rays must be [H,W,3], got shape={rays.shape}") + + rays_t = torch.from_numpy(rays).to(self.device) + src_h, src_w = int(rays_t.shape[0]), int(rays_t.shape[1]) + if (src_h, src_w) != (self.height, self.width): + rays_t = F.interpolate( + rays_t.permute(2, 0, 1)[None, ...], + size=(self.height, self.width), + mode="bilinear", + align_corners=True, + ).squeeze(0).permute(1, 2, 0) + + rays_t = rays_t / torch.linalg.norm(rays_t, dim=-1, keepdims=True).clamp_min(1e-8) + self.rays = rays_t + + def forward(self, x0, y0): + """input coord = (n, 2) + rays = (512, 512, 3) + """ + rays = self.rays + x1, y1 = torch.floor(x0.float()), torch.floor(y0.float()) + x2, y2 = x1+1, y1+1 + """ + Perform bilinear interpolation to estimate the value of the function f(x, y) + at the continuous point (x0, y0), given that f is known at integer values of x, y. + """ + # if (y1>self.img_shape[0]-1).any() or (x1>self.img_shape[0]-1).any(): + # print("hello") + x1 = torch.clip(x1, 0, self.width - 1) + y1 = torch.clip(y1, 0, self.height - 1) + + # x2, y2 = torch.clip(x2, 0, self.img_shape[0]-1), torch.clip(y2, 0, self.img_shape[0]-1) + + # Compute the weights for the interpolation + wx1 = ((x2 - x0) / (x2 - x1 + 1e-8))[:, None] + wx2 = ((x0 - x1) / (x2 - x1 + 1e-8))[:, None] + wy1 = ((y2 - y0) / (y2 - y1 + 1e-8))[:, None] + wy2 = ((y0 - y1) / (y2 - y1 + 1e-8))[:, None] + + x1, y1, x2, y2 = x1.long(), y1.long(), x2.long(), y2.long() + x2 = torch.clip(x2, 0, self.width - 1) + y2 = torch.clip(y2, 0, self.height - 1) + + # Compute the interpolated value of f(x, y) at (x0, y0) + f_interp = wx1 * wy1 * rays[y1, x1] + \ + wx1 * wy2 * rays[y2, x1] + \ + wx2 * wy1 * rays[y1, x2] + \ + wx2 * wy2 * rays[y2, x2] + + f_interp = f_interp/torch.linalg.norm(f_interp, dim=-1, keepdims=True) + return f_interp.float() + + +def find_surface_points(ray_origins, ray_dirs, opacities, depths, geometry_net, use_opacities=False, validation=False): + # considered_indices = torch.where(opacities>0.5)[0] + + considered_indices = torch.arange(depths.shape[0]) + surface_points = ray_origins[considered_indices] + depths[considered_indices]*ray_dirs[considered_indices] #(n_rays, 3), + #o + t_sd, where t_s is the depth + surface_points = torch.clip(surface_points, -1.49, 1.49) #keep the range between -1.49, 1.49 + sdf_surface, sdf_grad = geometry_net(surface_points, with_grad=True, with_feature=False, with_laplace=False) + + # Analytical gradients seem to have good visuals + normals = F.normalize(sdf_grad, p=2, dim=-1) + normals = normals.view(-1, 3) + normals_len = torch.linalg.norm(normals, dim=-1, keepdims=True)[..., 0] #computes the l2 norm of normals + + # surface_points = surface_points[normals_len>1e-9] + # considered_indices = considered_indices[normals_len>1e-9] + # normals = normals[normals_len>1e-9] + + normals[normals_len<1e-9] = -ray_dirs[normals_len<1e-9] + + # depths = depths[considered_indices] + + # normals = normals/(torch.max(normals, dim=1, keepdim=True)[0]+1e-10) + # normals = normals / (torch.linalg.norm(normals, dim=-1, keepdims=True)+1e-10) + if torch.isnan(normals).any(): + print("stop") + + + # if use_opacities: + # considered_indices_surface = torch.where(opacities>0.5)[0] + # return surface_points, depths[considered_indices], considered_indices, normals, considered_indices_surface + + return surface_points, sdf_surface, depths[considered_indices], considered_indices, normals + +# def compute_normals(depth_map, intrinsic): +# '''Compute the normals from the depth map using camera intrinsics.''' +# n, h, w = depth_map.shape +# u, v = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij") + +# fx, fy = intrinsic[0, 0], intrinsic[1, 1] +# cx, cy = intrinsic[0, 2], intrinsic[1, 2] + +# z = torch.from_numpy(depth_map) +# x = (u - cx) * z / fx +# y = (v - cy) * z / fy + +# points = torch.stack([x, y, z], dim=-1) +# padded = torch.nn.functional.pad(points, (0, 0, 1, 1, 1, 1), mode='replicate') +# g_x = (padded[:, 2:, 1:-1] - padded[:, :-2, 1:-1]) / 2 +# g_y = (padded[:, 1:-1, 2:] - padded[:, 1:-1, :-2]) / 2 +# N = torch.cross(g_x, g_y, dim=-1) +# N_norm = torch.linalg.norm(N, dim=-1, keepdim=True) +# N_normalized = N / torch.where(N_norm == 0, torch.ones_like(N_norm), N_norm) + + return N_normalized + + +def get_rays_from_images(K, c2w): + ''' + K is a 3x3 intrinsic matrix + c2w is a (n,4x4) extrinsic matrix for each of the n images + ''' + + x, y = torch.meshgrid( + torch.arange(512), + torch.arange(512), + indexing="xy", + ) + + x = x.flatten() + y = y.flatten() + + dirs = F.pad( + torch.stack( + [ + (x - K[0, 2] + 0.5) / K[0, 0], + (y - K[1, 2] + 0.5) / K[1, 1] * -1.0, + ], dim=-1), (0, 1), value=-1.0) + + #Dimension for camera_dirs[:x.shape[0], None, None, :] + #Dimension for c2w[:, :3, :3] + directions = (dirs[:,None, None, :] * c2w[:, :3, :3]).sum(dim=-1) + directions = directions.permute(1,0,2) + origins = torch.broadcast_to(c2w[:, None, :3, -1], directions.shape) + viewdirs = directions / torch.linalg.norm( + directions, dim=-1, keepdims=True + ) + + origins = torch.reshape(origins, (c2w.shape[0], 512, 512, 3)) + viewdirs = torch.reshape(viewdirs, (c2w.shape[0], 512, 512, 3)) + + return origins, viewdirs + + + +def get_rays_captured_from_images(K, c2w): + + x, y = torch.meshgrid( + torch.arange(512), + torch.arange(512), + indexing="xy", + ) + + x = x.flatten() + y = y.flatten() + x = x.to(K.rays) + y = y.to(K.rays) + dirs = K(x, y) + + directions = (dirs[:,None, None, :] * c2w[:, :3, :3].to(dirs)).sum(dim=-1) + directions = directions.permute(1,0,2) + origins = torch.broadcast_to(c2w[:, None, :3, -1], directions.shape) + viewdirs = directions / torch.linalg.norm( + directions, dim=-1, keepdims=True + ) + + origins = torch.reshape(origins, (c2w.shape[0], 512, 512, 3)) + viewdirs = torch.reshape(viewdirs, (c2w.shape[0], 512, 512, 3)) + return origins, viewdirs + +def compute_normals(depth_map, K, c2w): + '''Compute the normals from the depth map using camera intrinsics.''' + n, h, w = depth_map.shape + # Compute ray origins and directions + origins, viewdirs = get_rays_from_images(K, c2w) + # Reshape depth_map for broadcasting + depth_map = torch.from_numpy(depth_map).reshape(n, h, w, 1) + + # Compute 3D points + points = (depth_map * viewdirs + origins).reshape(n, h, w, 3) + padded = torch.nn.functional.pad(points, (0, 0, 1, 1, 1, 1), mode='replicate') + g_x = (padded[:, 2:, 1:-1] - padded[:, :-2, 1:-1]) / 2 #each of these terms is of shape (n, 512,512,3) + g_y = (padded[:, 1:-1, 2:] - padded[:, 1:-1, :-2]) / 2 + N = torch.cross(g_x, g_y, dim=-1) + N_norm = torch.linalg.norm(N, dim=-1, keepdim=True) + N_normalized = N / torch.where(N_norm == 0, torch.ones_like(N_norm), N_norm) + + return N_normalized + + + +def compute_normals_from_transient_captured(depth_map, K, c2w): + '''Compute the normals from the depth map for the captured dataset''' + n, h, w = depth_map.shape + origins, viewdirs = get_rays_captured_from_images(K, c2w) + + depth_map = torch.from_numpy(depth_map).reshape(n, h, w, 1) + + # Compute 3D points + points = (depth_map * viewdirs.to(origins) + origins).reshape(n, h, w, 3) + padded = torch.nn.functional.pad(points, (0, 0, 1, 1, 1, 1), mode='replicate') + g_x = (padded[:, 2:, 1:-1] - padded[:, :-2, 1:-1]) / 2 #each of these terms is of shape (n, 512,512,3) + g_y = (padded[:, 1:-1, 2:] - padded[:, 1:-1, :-2]) / 2 + N = torch.cross(g_x, g_y, dim=-1) + N_norm = torch.linalg.norm(N, dim=-1, keepdim=True) + N_normalized = N / torch.where(N_norm == 0, torch.ones_like(N_norm), N_norm) + + return -N_normalized #in captured dataset, the normals are inverted diff --git a/codes/reconstruction/transientangelo/models/texture.py b/codes/reconstruction/transientangelo/models/texture.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2eac48d167da336ba75c6ae96e910d320a6dc7 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/texture.py @@ -0,0 +1,93 @@ +import torch +import torch.nn as nn +import torch.nn.functional as functional + +import models as models +from models.utils import get_activation +from models.network_utils import get_encoding, get_mlp +from systems.utils import update_module_step + + +@models.register('volume-radiance') +class VolumeRadiance(nn.Module): + def __init__(self, config): + super(VolumeRadiance, self).__init__() + self.config = config + self.n_dir_dims = self.config.get('n_dir_dims', 3) + self.n_output_dims = 3 + encoding = get_encoding(self.n_dir_dims, self.config.dir_encoding_config) + self.n_input_dims = self.config.input_feature_dim + encoding.n_output_dims + network = get_mlp(self.n_input_dims, self.n_output_dims, self.config.mlp_network_config) + self.encoding = encoding + self.network = network + self.network_precision = config.get('network_precision', 'native') + if self.network_precision not in ('native', 'float32'): + raise ValueError(f'Unsupported radiance network precision: {self.network_precision}') + if self.network_precision == 'float32': + network_config = config.mlp_network_config + if (network_config.otype != 'FullyFusedMLP' or network_config.activation != 'ReLU' + or str(network_config.output_activation).lower() != 'none'): + raise ValueError('Float32 radiance execution requires a FullyFusedMLP with ReLU and no output activation') + + def _network_forward_float32(self, inputs): + network_config = self.config.mlp_network_config + width = int(network_config.n_neurons) + hidden_layers = int(network_config.n_hidden_layers) + input_width = (self.n_input_dims + 15) // 16 * 16 + output_width = (self.n_output_dims + 15) // 16 * 16 + dimensions = [input_width] + [width] * hidden_layers + [output_width] + expected_parameters = sum(left * right for left, right in zip(dimensions[:-1], dimensions[1:])) + if self.network.params.numel() != expected_parameters: + raise ValueError('Unexpected FullyFusedMLP parameter layout for float32 execution') + with torch.autocast(device_type=inputs.device.type, enabled=False): + output = functional.pad(inputs.float(), (0, input_width - self.n_input_dims), value=1.0) + offset = 0 + for index, (left, right) in enumerate(zip(dimensions[:-1], dimensions[1:])): + size = left * right + weights = self.network.params[offset:offset + size].reshape(right, left).float() + output = functional.linear(output, weights) + offset += size + if index < hidden_layers: + output = functional.relu(output) + return output[..., :self.n_output_dims] + + def forward(self, features, dirs, *args): + dirs = (dirs + 1.) / 2. # (-1, 1) => (0, 1) + dirs_embd = self.encoding(dirs.view(-1, self.n_dir_dims)) + network_inp = torch.cat([features.view(-1, features.shape[-1]), dirs_embd] + [arg.view(-1, arg.shape[-1]) for arg in args], dim=-1) + if self.network_precision == 'float32': + color = self._network_forward_float32(network_inp) + else: + color = self.network(network_inp) + color = color.view(*features.shape[:-1], self.n_output_dims).float() + + if 'color_activation' in self.config: + color = get_activation(self.config.color_activation)(color) + return color + + def update_step(self, epoch, global_step): + update_module_step(self.encoding, epoch, global_step) + + def regularizations(self, out): + return {} + + +@models.register('volume-color') +class VolumeColor(nn.Module): + def __init__(self, config): + super(VolumeColor, self).__init__() + self.config = config + self.n_output_dims = 3 + self.n_input_dims = self.config.input_feature_dim + network = get_mlp(self.n_input_dims, self.n_output_dims, self.config.mlp_network_config) + self.network = network + + def forward(self, features, *args): + network_inp = features.view(-1, features.shape[-1]) + color = self.network(network_inp).view(*features.shape[:-1], self.n_output_dims).float() + if 'color_activation' in self.config: + color = get_activation(self.config.color_activation)(color) + return color + + def regularizations(self, out): + return {} diff --git a/codes/reconstruction/transientangelo/models/utils.py b/codes/reconstruction/transientangelo/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3560b5ffa41f18e41b3c06339a2598a5d2e7d4 --- /dev/null +++ b/codes/reconstruction/transientangelo/models/utils.py @@ -0,0 +1,194 @@ +import gc +from collections import defaultdict +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.autograd import Function +from torch.cuda.amp import custom_bwd, custom_fwd + +import tinycudann as tcnn + + +def chunk_batch(func, chunk_size, move_to_cpu, *args, **kwargs): + B = None + for arg in args: + if isinstance(arg, torch.Tensor): #Assuming the first tensor passed in is rays + B = arg.shape[0] #Gets the shape of the first tensor - usually num_rays + break + tensor_arg = [] + non_tensor_arg = [] + for arg in args: + if isinstance(arg, torch.Tensor): + tensor_arg.append(arg) + else: + non_tensor_arg.append(arg) + out = defaultdict(list) + out_type = None + for i in range(0, B, chunk_size): #if the last chunk might be less than chunk_size + chunked_tensors = [tensor_arg[i:i + chunk_size] for tensor_arg in tensor_arg] #Chunks the tensors rays: (chunk_size, 6) + out_chunk = func(*chunked_tensors, *non_tensor_arg, **kwargs) + if out_chunk is None: + continue + + #Checking the type of the output + out_type = type(out_chunk) + if isinstance(out_chunk, torch.Tensor): + out_chunk = {0: out_chunk} + elif isinstance(out_chunk, tuple) or isinstance(out_chunk, list): + chunk_length = len(out_chunk) + out_chunk = {i: chunk for i, chunk in enumerate(out_chunk)} + elif isinstance(out_chunk, dict): + pass + else: + print(f'Return value of func must be in type [torch.Tensor, list, tuple, dict], get {type(out_chunk)}.') + exit(1) + + #Moving every key to cpu + for k, v in out_chunk.items(): + v = v if torch.is_grad_enabled() else v.detach() + v = v.cpu() if move_to_cpu else v + if k == "ray_indices": + v = v + i + out[k].append(v) + + if out_type is None: + return + + out = {k: torch.cat(v, dim=0) for k, v in out.items()} + if out_type is torch.Tensor: + return out[0] + elif out_type in [tuple, list]: + return out_type([out[i] for i in range(chunk_length)]) + elif out_type is dict: + return out + + +class _TruncExp(Function): # pylint: disable=abstract-method + # Implementation from torch-ngp: + # https://github.com/ashawkey/torch-ngp/blob/93b08a0d4ec1cc6e69d85df7f0acdfb99603b628/activation.py + @staticmethod + @custom_fwd(cast_inputs=torch.float32) + def forward(ctx, x): # pylint: disable=arguments-differ + ctx.save_for_backward(x) + return torch.exp(x) + + @staticmethod + @custom_bwd + def backward(ctx, g): # pylint: disable=arguments-differ + x = ctx.saved_tensors[0] + return g * torch.exp(torch.clamp(x, max=15)) + +trunc_exp = _TruncExp.apply + + +def get_activation(name): + if name is None: + return lambda x: x + name = name.lower() + if name == 'none': + return lambda x: x + elif name.startswith('scale'): + scale_factor = float(name[5:]) + return lambda x: x.clamp(0., scale_factor) / scale_factor + elif name.startswith('clamp'): + clamp_max = float(name[5:]) + return lambda x: x.clamp(0., clamp_max) + elif name.startswith('mul'): + mul_factor = float(name[3:]) + return lambda x: x * mul_factor + elif name == 'lin2srgb': + return lambda x: torch.where(x > 0.0031308, torch.pow(torch.clamp(x, min=0.0031308), 1.0/2.4)*1.055 - 0.055, 12.92*x).clamp(0., 1.) + elif name == 'trunc_exp': + return trunc_exp + elif name.startswith('+') or name.startswith('-'): + return lambda x: x + float(name) + elif name == 'sigmoid': + return lambda x: torch.sigmoid(x) + elif name == 'tanh': + return lambda x: torch.tanh(x) + elif name == 'exp': + return lambda x: torch.exp(x) + else: + return getattr(F, name) + + +def dot(x, y): + return torch.sum(x*y, -1, keepdim=True) + + +def reflect(x, n): + return 2 * dot(x, n) * n - x + + +def scale_anything(dat, inp_scale, tgt_scale): + if inp_scale is None: + inp_scale = [dat.min(), dat.max()] + + dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0]) + dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0] + return dat + + + +def mapping_dist_to_bin_mitsuba(dists, n_bins, exposure_time, c=1, sigma=5): + #NOTE: ratio measures the total distance travelled by the light photon, after being emitted from the laser pulse and reflected off the object, divided by the exposure time (the time for which the laser pulse is on) + times = 2 * dists / c #(2* distances between each sample and their respective origin) + ratio = times / exposure_time #0.01, basically just 2*distances/exposure_time + + #NOTE: For each sample's distance from the origin, we center a bin around it that covers += 4*sigma distance from the sample + #so ratio-4*sigma is the left edge of the bin and we add ranges because we basically want to get this: for each sample, [ratio-4*sigma, ratio+1-4*sigma, ...], where the middle is roughly that sample's ratio + ranges = torch.arange(0, 8 * sigma, device=dists.device)[None, :].repeat(ratio.shape[0], 1) #(Create a tensor from 0-23 and repeat it to match the shape of dists) + bin_mapping = (torch.ceil(ratio-4*sigma))[:, None]+ranges #Creating a bin mapping tensor and adding elementwise elements to ranges, (n_samples, 24) + + #NOTE: For each bin mapping entry, we query a normal distribution centered around the true ratio (that sample's distance) + ranges = bin_mapping - ratio[:, None] + dist_weights = torch.exp(-ranges**2/(2*sigma**2))-math.exp(-8) #(n_samples, 24) + + dist_weights[(bin_mapping<0) ] = 0 + dist_weights[(bin_mapping>n_bins) ] = 0 + + bin_mapping = torch.clip(bin_mapping, 0, n_bins-1) + dist_weights = (dist_weights.T/(dist_weights.sum(-1)[: None]+1e-10)).T + return bin_mapping, dist_weights + + + +def mapping_dist_to_bin(dists, n_bins, exposure_time, c=1): + times = 2 * dists / c + # (torch.randn(times.shape[0])*7).to("cuda") + ratio = times / exposure_time + alpha = (torch.ceil(ratio) - ratio) / (torch.ceil(ratio) - torch.floor(ratio) + 1e-10) + + bin_numbers_floor = torch.floor(ratio) + bin_numbers_ceil = torch.ceil(ratio) + # if torch.max(bin_numbers)>bin_length: + # print("hello") + bin_numbers_floor = torch.clip(bin_numbers_floor, 0, n_bins - 1) + bin_numbers_ceil = torch.clip(bin_numbers_ceil, 0, n_bins - 1) + + return bin_numbers_floor, bin_numbers_ceil, alpha + + +def torch_laser_kernel(laser, device='cuda'): + m = torch.nn.Conv1d(1, 1, laser.shape[0], padding=(laser.shape[0] - 1) // 2, padding_mode="zeros", device=device) + m.weight.requires_grad = False + m.bias.requires_grad = False + m.bias *= 0 + m.weight = torch.nn.Parameter(laser[None, None, ...]) + return m + + +def convolve_colour(color, kernel, n_bins): + color = color.transpose(1, 2).reshape(-1, n_bins) + color = kernel(color[:, None, :]).squeeze() + color = color.reshape(-1, 3, n_bins).transpose(1, 2) + return color + + + +def cleanup(): + gc.collect() + torch.cuda.empty_cache() + tcnn.free_temporary_memory() diff --git a/codes/reconstruction/transientangelo/requirements.txt b/codes/reconstruction/transientangelo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c7f0ea92f6b8b24b07823e433a64c53c1ce3bbe --- /dev/null +++ b/codes/reconstruction/transientangelo/requirements.txt @@ -0,0 +1,34 @@ +# Install PyTorch 2.5.1 / CUDA 11.8 first; see README. +ConfigArgParse==1.7.5 +ImageIO==2.37.2 +PyMCubes==0.1.6 +PyYAML==6.0.3 +h5py==3.15.1 +imageio-ffmpeg==0.6.0 +imgviz==1.7.6 +lightning-utilities==0.15.2 +lpips==0.1.4 +matplotlib==3.10.7 +nerfacc==0.3.3 +numpy==2.2.6 +omegaconf==2.2.3 +opencv-python==4.12.0.88 +packaging==25.0 +pandas==2.3.3 +pillow==11.3.0 +prettytable==3.17.0 +pytorch-lightning==1.9.5 +scikit-image==0.25.2 +scipy==1.15.2 +sparse==0.17.0 +tensorboard==2.20.0 +torch==2.5.1 +torchmetrics==1.8.2 +torchvision==0.20.1 +tqdm==4.67.1 +trimesh==4.10.0 + +# CUDA extensions (install after PyTorch; source build needs the CUDA toolchain). +torch_efficient_distloss==0.1.3 +torch_scatter==2.1.2+pt25cu118 +tinycudann @ git+https://github.com/NVlabs/tiny-cuda-nn@38e50edc4a5f785afe0ef21f9c75b8949890be84#subdirectory=bindings/torch diff --git a/codes/reconstruction/transientangelo/systems/__init__.py b/codes/reconstruction/transientangelo/systems/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7742c5866fef438c57fd1f0c4fb5ab9243839636 --- /dev/null +++ b/codes/reconstruction/transientangelo/systems/__init__.py @@ -0,0 +1,21 @@ +systems = {} + + +def register(name): + def decorator(cls): + systems[name] = cls + return cls + return decorator + + +def make(name, config, load_from_checkpoint=None): + if load_from_checkpoint is None: + system = systems[name](config) + else: + system = systems[name].load_from_checkpoint(load_from_checkpoint, strict=False, config=config) + return system + + + + +from . import captured_neus diff --git a/codes/reconstruction/transientangelo/systems/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/transientangelo/systems/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe3d2557918882967773a86cc3eda6b8b181d847 Binary files /dev/null and b/codes/reconstruction/transientangelo/systems/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/systems/__pycache__/base.cpython-312.pyc b/codes/reconstruction/transientangelo/systems/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e2a670f493793c7eff252818d58694965b6e72 Binary files /dev/null and b/codes/reconstruction/transientangelo/systems/__pycache__/base.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/systems/__pycache__/captured_neus.cpython-312.pyc b/codes/reconstruction/transientangelo/systems/__pycache__/captured_neus.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e1c0f8c4590f0a798a91a638bd1b2fbe78f2816 Binary files /dev/null and b/codes/reconstruction/transientangelo/systems/__pycache__/captured_neus.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/systems/__pycache__/utils.cpython-312.pyc b/codes/reconstruction/transientangelo/systems/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d18cbe063f787616b5476692f4695651a6d16d1 Binary files /dev/null and b/codes/reconstruction/transientangelo/systems/__pycache__/utils.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/systems/base.py b/codes/reconstruction/transientangelo/systems/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8ccbe6942e2c000452370bf827610206c4cab4aa --- /dev/null +++ b/codes/reconstruction/transientangelo/systems/base.py @@ -0,0 +1,151 @@ +import pytorch_lightning as pl + +import time + +import models as models +from systems.utils import parse_optimizer, parse_scheduler, update_module_step +from utils.mixins import SaverMixin +from utils.misc import config_to_primitive, get_rank + + +class BaseSystem(pl.LightningModule, SaverMixin): + """ + Two ways to print to console: + 1. self.print: correctly handle progress bar + 2. rank_zero_info: use the logging module + """ + def __init__(self, config): + super().__init__() + self.config = config + self.rank = get_rank() + self._debug_step_timing = bool(self.config.system.get('debug_step_timing', False)) + self.prepare() + self.model = models.make(self.config.model.name, self.config.model) + + def prepare(self): + pass + + def forward(self, batch): + raise NotImplementedError + + def C(self, value): + if isinstance(value, int) or isinstance(value, float): + pass + else: + value = config_to_primitive(value) + if not isinstance(value, list): + raise TypeError('Scalar specification only supports list, got', type(value)) + if len(value) == 3: + value = [0] + value + assert len(value) == 4 + start_step, start_value, end_value, end_step = value + if isinstance(end_step, int): + current_step = self.global_step + value = start_value + (end_value - start_value) * max(min(1.0, (current_step - start_step) / (end_step - start_step)), 0.0) + elif isinstance(end_step, float): + current_step = self.current_epoch + value = start_value + (end_value - start_value) * max(min(1.0, (current_step - start_step) / (end_step - start_step)), 0.0) + return value + + def preprocess_data(self, batch, stage): + pass + + """ + Implementing on_after_batch_transfer of DataModule does the same. + But on_after_batch_transfer does not support DP. + """ + def on_train_batch_start(self, batch, batch_idx, unused=0): + t0 = time.perf_counter() + if self._debug_step_timing: + self.print(f"[DBG] step={self.global_step} enter on_train_batch_start") + self.dataset = self.trainer.datamodule.train_dataloader().dataset #this creates a BlenderIterableDataset + self.preprocess_data(batch, 'train') #updates the batch + update_module_step(self.model, self.current_epoch, self.global_step) + if self._debug_step_timing: + self.print(f"[DBG] step={self.global_step} exit on_train_batch_start dt={time.perf_counter()-t0:.3f}s") + + def on_before_backward(self, loss): + if self._debug_step_timing: + self.print(f"[DBG] step={self.global_step} before backward") + + def on_after_backward(self): + if self._debug_step_timing: + self.print(f"[DBG] step={self.global_step} after backward") + + def on_before_optimizer_step(self, optimizer, optimizer_idx=None): + if self._debug_step_timing: + self.print(f"[DBG] step={self.global_step} before optimizer_step") + + def on_train_batch_end(self, outputs, batch, batch_idx): + if self._debug_step_timing: + self.print(f"[DBG] step={self.global_step} end train_batch") + + def on_validation_batch_start(self, batch, batch_idx, dataloader_idx): #This gets called when validation starts + self.dataset = self.trainer.datamodule.val_dataloader().dataset #this creates a BlenderDataset + self.preprocess_data(batch, 'validation') + # update_module_step(self.model, self.current_epoch, self.global_step) + + def on_test_batch_start(self, batch, batch_idx, dataloader_idx): + self.dataset = self.trainer.datamodule.test_dataloader().dataset #this creates a BlenderDataset + self.preprocess_data(batch, 'test') + # update_module_step(self.model, self.current_epoch, self.global_step) + + def on_predict_batch_start(self, batch, batch_idx, dataloader_idx): + self.dataset = self.trainer.datamodule.predict_dataloader().dataset + self.preprocess_data(batch, 'predict') + update_module_step(self.model, self.current_epoch, self.global_step) + + def training_step(self, batch, batch_idx): + raise NotImplementedError + + """ + # aggregate outputs from different devices (DP) + def training_step_end(self, out): + pass + """ + + """ + # aggregate outputs from different iterations + def training_epoch_end(self, out): + pass + """ + + def validation_step(self, batch, batch_idx): + raise NotImplementedError + + """ + # aggregate outputs from different devices when using DP + def validation_step_end(self, out): + pass + """ + + # def validation_epoch_end(self, out): + # """ + # Gather metrics from all devices, compute mean. + # Purge repeated results using data index. + # """ + # raise NotImplementedError + + def test_step(self, batch, batch_idx): + raise NotImplementedError + + def test_epoch_end(self, out): + """ + Gather metrics from all devices, compute mean. + Purge repeated results using data index. + """ + raise NotImplementedError + + def export(self): + raise NotImplementedError + + def configure_optimizers(self): + optim = parse_optimizer(self.config.system.optimizer, self.model) + ret = { + 'optimizer': optim, + } + if 'scheduler' in self.config.system: + ret.update({ + 'lr_scheduler': parse_scheduler(self.config.system.scheduler, optim), + }) + return ret diff --git a/codes/reconstruction/transientangelo/systems/captured_neus.py b/codes/reconstruction/transientangelo/systems/captured_neus.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae98ea070ab55a69e619ee3dce5c6f733fe858f --- /dev/null +++ b/codes/reconstruction/transientangelo/systems/captured_neus.py @@ -0,0 +1,605 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch_efficient_distloss import flatten_eff_distloss +import numpy as np +from scipy.ndimage import correlate1d +import os +import math +import time +import json +from pathlib import Path +import matplotlib.pyplot as plt +import pytorch_lightning as pl +from pytorch_lightning.utilities.rank_zero import rank_zero_info, rank_zero_debug +from pytorch_lightning.loggers import TensorBoardLogger +import imageio +import imgviz +import models as models +from models.ray_utils import get_rays, spatial_filter, generate_unseen_poses +from models.mesh_utils import calculate_chamfer_distance +import systems as systems +from systems.base import BaseSystem + + +@systems.register('captured-neus-system') +class CapturedNeuSSystem(BaseSystem): + """ + Two ways to print to console: + 1. self.print: correctly handle progress bar + 2. rank_zero_info: use the logging module + """ + def prepare(self): + self.train_num_samples = self.config.model.train_num_rays * self.config.model.num_samples_per_ray + self.train_num_rays = self.config.model.train_num_rays + self.register_buffer("train_rep", torch.tensor(1, dtype=torch.long)) + + def on_train_batch_start(self, batch, batch_idx, unused=0): + super().on_train_batch_start(batch, batch_idx, unused) + from evaluation.units import scalar + self._image_metric_training_scale = scalar(self.dataset.focal) + + def on_save_checkpoint(self, checkpoint): + self._validate_checkpoint(checkpoint) + if hasattr(self, '_image_metric_training_scale'): + checkpoint['image_metric_training_scale'] = self._image_metric_training_scale + + def on_load_checkpoint(self, checkpoint): + self._validate_checkpoint(checkpoint) + if 'image_metric_training_scale' in checkpoint: + self._image_metric_training_scale = float(checkpoint['image_metric_training_scale']) + + def _validate_checkpoint(self, checkpoint): + for name, value in checkpoint['state_dict'].items(): + if value.is_floating_point() and not torch.isfinite(value).all(): + raise FloatingPointError( + f"Non-finite checkpoint tensor {name} at step {checkpoint.get('global_step')}; " + 'refusing to load or save corrupt model state.' + ) + + def _get_meas_peak_threshold_norm(self): + meas_peak_min = float(getattr(self.config.dataset, "meas_peak_min", 0.0)) + if meas_peak_min <= 0: + return None + scale = getattr(self.dataset, "focal", 1.0) + if torch.is_tensor(scale): + scale = float(scale.detach().cpu().reshape(-1)[0].item()) + else: + scale = float(scale) + scale = max(scale, 1e-8) + return meas_peak_min / scale + + def _use_regnerf(self, stage: str) -> bool: + if not bool(self.config.model.get("use_reg_nerf", False)): + return False + if stage != "train": + return bool(self.config.model.get("use_regnerf_viz", True)) + start_step = int(self.config.model.get("regnerf_start_step", 0)) + interval = max(1, int(self.config.model.get("regnerf_interval", 1))) + if int(self.global_step) < start_step: + return False + return ((int(self.global_step) - start_step) % interval) == 0 + + @torch.no_grad() + def _save_train_full_view_visualization(self, camera_index=None): + if hasattr(self, "trainer") and self.trainer is not None and (not self.trainer.is_global_zero): + return + if not bool(self.config.system.get("save_train_full_view_vis", True)): + return + if not hasattr(self.dataset, "all_images") or len(self.dataset.all_images) == 0: + return + + if torch.is_tensor(camera_index): + camera_index = int(camera_index.reshape(-1)[0].item()) + elif camera_index is None: + camera_index = int(self.config.system.get("train_full_view_vis_view_index", 0)) + else: + camera_index = int(camera_index) + camera_index = max(0, min(camera_index, len(self.dataset.all_images) - 1)) + + W, H = self.dataset.img_wh + x, y = torch.meshgrid( + torch.arange(self.dataset.w, device=self.dataset.all_c2w.device), + torch.arange(self.dataset.h, device=self.dataset.all_c2w.device), + indexing="xy", + ) + x = x.flatten().to(self.rank) + y = y.flatten().to(self.rank) + c2w = self.dataset.all_c2w[torch.as_tensor([camera_index], dtype=torch.long)] + camera_dirs = self.dataset.K(x, y) + rays_d = (camera_dirs[:, None, :] * c2w[:, :3, :3].to(self.rank)).sum(dim=-1) + rays_o = torch.broadcast_to(c2w[:, :3, -1], rays_d.shape).to(self.rank) + rays = torch.cat([rays_o, F.normalize(rays_d, p=2, dim=-1)], dim=-1).float() + + rays_dict = { + "training_rays": { + "rays": rays, + "rotation_matrix": c2w[:, :3, :3], + "index": torch.as_tensor([camera_index], dtype=torch.long), + }, + "stage": "test", + "use_regnerf": False, + } + + was_training = self.model.training + self.model.eval() + try: + out = self.model(rays_dict, self.dataset.laser_kernel) + finally: + if was_training: + self.model.train() + + pred_rgb = out["rgb"].reshape(H, W, self.dataset.n_bins, 3).detach().cpu().numpy().astype(np.float32) + gt_rgb = self.dataset.all_images[camera_index].detach().cpu().numpy().astype(np.float32) + + pred_depth = np.argmax(pred_rgb[..., 0], axis=-1).astype(np.float32) * float(self.model.exposure_time) / 2.0 + gt_depth = np.argmax(gt_rgb[..., 0], axis=-1).astype(np.float32) * float(self.model.exposure_time) / 2.0 + pred_intensity = pred_rgb[..., 0].sum(axis=-1).astype(np.float32) + gt_intensity = gt_rgb[..., 0].sum(axis=-1).astype(np.float32) + + mask = gt_rgb[..., 0].sum(axis=-1) > 0 + if hasattr(self.dataset, "valid_mask") and self.dataset.valid_mask is not None: + mask = mask & self.dataset.valid_mask.detach().cpu().numpy().astype(bool) + peak_thre_norm = self._get_meas_peak_threshold_norm() + if peak_thre_norm is not None: + meas_peak_mask = np.max(gt_rgb[..., 0], axis=-1) >= float(peak_thre_norm) + mask = mask & meas_peak_mask + + depth_for_viz = gt_depth[mask] if np.any(mask) else gt_depth[np.isfinite(gt_depth)] + if depth_for_viz.size > 0: + vmin = float(np.percentile(depth_for_viz, 1.0)) + vmax = float(np.percentile(depth_for_viz, 99.0)) + if vmax <= vmin: + vmax = vmin + 1e-6 + else: + vmin, vmax = 0.0, 1.0 + + if np.any(mask): + intensity_scale = max( + float(np.max(gt_intensity[mask])), + float(np.max(pred_intensity[mask])), + 1e-8, + ) + else: + intensity_scale = max(float(np.max(gt_intensity)), float(np.max(pred_intensity)), 1e-8) + gt_intensity_vis = np.clip(gt_intensity / intensity_scale, 0.0, 1.0) ** (1.0 / 2.2) + pred_intensity_vis = np.clip(pred_intensity / intensity_scale, 0.0, 1.0) ** (1.0 / 2.2) + + save_prefix = f"it{self.global_step}-train-vis/{camera_index}" + plt.imsave(self.get_save_path(f"{save_prefix}_depth_gt.png"), gt_depth, cmap="inferno", vmin=vmin, vmax=vmax) + plt.imsave(self.get_save_path(f"{save_prefix}_depth_pred.png"), pred_depth, cmap="inferno", vmin=vmin, vmax=vmax) + imageio.imwrite(self.get_save_path(f"{save_prefix}_intensity_gt.png"), (gt_intensity_vis * 255.0).astype(np.uint8)) + imageio.imwrite(self.get_save_path(f"{save_prefix}_intensity_pred.png"), (pred_intensity_vis * 255.0).astype(np.uint8)) + np.save(self.get_save_path(f"{save_prefix}_depth_gt.npy"), gt_depth) + np.save(self.get_save_path(f"{save_prefix}_depth_pred.npy"), pred_depth) + np.save(self.get_save_path(f"{save_prefix}_intensity_gt.npy"), gt_intensity) + np.save(self.get_save_path(f"{save_prefix}_intensity_pred.npy"), pred_intensity) + + + def forward(self, batch): + return self.model(batch["rays_dict"], batch["laser_kernel"]) + + def preprocess_data(self, batch, stage): + #This populates the batch to feed into forward + if hasattr(self.dataset, "n_bins"): + self.model.n_bins = int(self.dataset.n_bins) + if hasattr(self.dataset, "exposure_time"): + self.model.exposure_time = float(self.dataset.exposure_time) + if hasattr(self.dataset, "near"): + self.model.near_plane = float(self.dataset.near) + if hasattr(self.dataset, "far"): + self.model.far_plane = float(self.dataset.far) + + rays_dict = {} + if 'index' in batch: # validation / testing + index = batch['index'] + else: + if self.config.model.batch_image_sampling: + index = torch.randint(0, len(self.dataset.all_images), size=(self.train_num_rays,), device=self.dataset.all_images.device) + else: + index = torch.randint(0, len(self.dataset.all_images), size=(1,), device=self.dataset.all_images.device) + index = index.cpu() + regnerf_active = self._use_regnerf(stage) + if stage in ['train']: + + train_x = torch.randint( + 0, self.dataset.w, size=(self.train_num_rays,), device=self.dataset.all_images.device + ) + train_y = torch.randint( + 0, self.dataset.h, size=(self.train_num_rays,), device=self.dataset.all_images.device + ) + train_x = train_x.repeat(self.train_rep) #(n_rays*rep) + train_y = train_y.repeat(self.train_rep) #(n_rays*rep) + index = index.repeat(self.train_rep) + rgb = self.dataset.all_images[index, train_y, train_x].view(-1, self.dataset.all_images.shape[-1]).float().to(self.rank) #(n_rays*rep, 1200, 3) + if hasattr(self.dataset, "valid_mask") and self.dataset.valid_mask is not None: + data_valid_mask = self.dataset.valid_mask[train_y.long(), train_x.long()] + else: + data_valid_mask = torch.ones_like(train_x, dtype=torch.bool) + + + train_x = train_x.to(self.rank) + train_y = train_y.to(self.rank) + train_sx, train_sy, weights = spatial_filter(train_x, train_y, sigma=self.dataset.rfilter_sigma, rep = self.train_rep, prob_dithering=self.dataset.sample_as_per_distribution) + s_x = torch.clip(train_x + torch.from_numpy(train_sx).to(self.rank), 0, self.dataset.w - 1) #Small perturbations to the pixel locations + s_y = torch.clip(train_y + torch.from_numpy(train_sy).to(self.rank), 0, self.dataset.h - 1) + weights = torch.Tensor(weights).to(self.rank) + + if regnerf_active: + #NOTE: the regnerf patch rays are always concatenated at the end + patch_size = self.config.model.train_patch_size + n_sparse_rays = self.config.model.sparse_rays_size + img_wh = self.dataset.w, self.dataset.h + regnerf_x, regnerf_y, unseen_rotation_matrix, unseen_translation_vector = generate_unseen_poses(patch_size, img_wh, self.dataset.all_c2w, n_sparse_rays=n_sparse_rays, + bounding_form =self.config.model.bounding_form, mean_focus_point = self.dataset.mean_focus_point, + sample_boundary = self.config.model.sample_boundary, write_poses = self.config.model.write_poses, captured=True) + regnerf_x, regnerf_y = regnerf_x.to(self.rank), regnerf_y.to(self.rank) + unseen_rotation_matrix = torch.from_numpy(unseen_rotation_matrix).to(self.rank) + #Calculate the rays for the unseen patch using the new rotation matrix and translation vector + s_x, s_y = torch.cat([s_x, regnerf_x], dim=0), torch.cat([s_y, regnerf_y], dim=0) + + + elif stage in ["validation"]: + #Selecting all tuples (x,y) of the image + train_x, train_y = torch.meshgrid( + torch.arange(self.dataset.w, device=self.dataset.all_c2w.device), + torch.arange(self.dataset.h, device=self.dataset.all_c2w.device), + indexing="xy", + ) #(self.dataset.w, self.dataset.h) + train_x = train_x.flatten() + train_y = train_y.flatten() + train_x = train_x.to(self.rank) + train_y = train_y.to(self.rank) + s_x = train_x + s_y = train_y + + if regnerf_active: + #NOTE: use this for visualization + patch_size = int(self.config.model.get("regnerf_val_patch_size", 32)) + n_sparse_rays = self.config.model.sparse_rays_size + img_wh = self.dataset.w, self.dataset.h + regnerf_x, regnerf_y, unseen_rotation_matrix, unseen_translation_vector = generate_unseen_poses(patch_size, img_wh, self.dataset.all_c2w, n_sparse_rays=n_sparse_rays, + bounding_form =self.config.model.bounding_form, mean_focus_point = self.dataset.mean_focus_point, + sample_boundary = self.config.model.sample_boundary, captured=True) + regnerf_x, regnerf_y = regnerf_x.to(self.rank), regnerf_y.to(self.rank) + unseen_rotation_matrix = torch.from_numpy(unseen_rotation_matrix).to(self.rank) + #Calculate the rays for the unseen patch using the new rotation matrix and translation vector + s_x, s_y = torch.cat([s_x, regnerf_x], dim=0), torch.cat([s_y, regnerf_y], dim=0) + + + elif stage in ["test"]: + train_x, train_y = torch.meshgrid( + torch.arange(self.dataset.w, device=self.dataset.all_c2w.device), + torch.arange(self.dataset.h, device=self.dataset.all_c2w.device), + indexing="xy", + ) #(self.dataset.w, self.dataset.h) + train_x = train_x.flatten() + train_y = train_y.flatten() + rgb = self.dataset.all_images[index, train_y, train_x] + if hasattr(self.dataset, "valid_mask") and self.dataset.valid_mask is not None: + data_valid_mask = self.dataset.valid_mask[train_y.long(), train_x.long()] + else: + data_valid_mask = torch.ones_like(train_x, dtype=torch.bool) + + self.train_rep = torch.tensor(1, dtype=torch.long) + train_x = train_x.to(self.rank) + train_y = train_y.to(self.rank) + s_x, s_y, weights = spatial_filter(train_x, train_y, sigma=self.dataset.rfilter_sigma, rep = self.dataset.rep, prob_dithering=self.dataset.sample_as_per_distribution) + s_x = (torch.clip(train_x + torch.from_numpy(s_x).to(self.rank), 0, self.dataset.w - 1).to(torch.float32)) + s_y = (torch.clip(train_y + torch.from_numpy(s_y).to(self.rank), 0, self.dataset.h - 1).to(torch.float32)) + weights = torch.Tensor(weights).to(self.rank) + + + + c2w = self.dataset.all_c2w[index] # (n_rays, 4, 4), repeats the same c2w matrix for all rays belonging to the same image + camera_dirs = self.dataset.K(s_x, s_y) + if stage in ["train", "validation"]: + if regnerf_active: + patch_size = self.config.model.train_patch_size if stage == "train" else int(self.config.model.get("regnerf_val_patch_size", 32)) + regnerf_rays_d = (camera_dirs[-patch_size**2:, None, :] * unseen_rotation_matrix.to(self.rank)).sum(dim=-1) #upper left corner of the c2w + unseen_rays_o = torch.broadcast_to(unseen_translation_vector, regnerf_rays_d.shape).to(self.rank).float() + unseen_rays = torch.cat([unseen_rays_o, F.normalize(regnerf_rays_d, p=2, dim=-1)], dim=-1).float() #(self.patch_size**2 + sparse_rays, 6) + rays_dict.update({"regnerf_patch": {'rays': unseen_rays, 'rotation_matrix': unseen_rotation_matrix}}) + if self.trainer.global_step == 1: + self.print("Regnerf patch rays has been added!") + + rays_d = (camera_dirs[:train_x.shape[0], None, :] * c2w[:, :3, :3].to(self.rank)).sum(dim=-1) + #NOTE: in captured, we use pixel coordinates and interpolate the camera directions based on the known camera directions stored in rays + rays_o = torch.broadcast_to(c2w[:,:3, -1], rays_d.shape).to(self.rank) + rays = torch.cat([rays_o, F.normalize(rays_d, p=2, dim=-1)], dim=-1).float() + rays_dict.update({"training_rays": {"rays": rays, 'rotation_matrix': c2w[:, :3, :3], 'index': index}}) + if self.trainer.global_step == 1: + self.print("Training rays has been added!") + + rays_dict.update({"stage": stage}) + rays_dict.update({"use_regnerf": regnerf_active}) + + if self.config.model.background_color == 'white': + self.model.background_color = torch.ones((3,), dtype=torch.float32, device=self.rank) + elif self.config.model.background_color == 'random': + self.model.background_color = torch.rand((3,), dtype=torch.float32, device=self.rank) + elif self.config.model.background_color == "black": + self.model.background_color = torch.zeros(3, dtype = torch.float32, device=self.rank) + else: + raise NotImplementedError + + # if self.dataset.apply_mask: + # rgb = rgb * fg_mask[...,None] + self.model.background_color * (1 - fg_mask[...,None]) + + if stage in ["train"]: + batch.update({ + 'rays_dict': rays_dict, + 'rgb': rgb.view(-1, self.dataset.n_bins*3), + 'weights': weights, + 'valid_mask': data_valid_mask.view(-1).to(torch.bool), + 'laser_kernel': self.dataset.laser_kernel + }) + + elif stage in ["validation"]: + batch.update({ + 'rays_dict': rays_dict, + 'laser_kernel': self.dataset.laser_kernel + }) + + elif stage in ["test"]: + batch.update({ + 'rays_dict': rays_dict, + 'rgb': rgb.view(-1, self.dataset.n_bins*3), + 'weights': weights, + 'valid_mask': data_valid_mask.view(-1).to(torch.bool), + 'laser_kernel': self.dataset.laser_kernel + }) + + def training_step(self, batch, batch_idx): + t0 = time.perf_counter() if getattr(self, "_debug_step_timing", False) else None + out = self(batch) + if t0 is not None: + self.print(f"[DBG] step={self.global_step} forward+loss_prep dt={time.perf_counter()-t0:.3f}s") + + training_rays = batch["rays_dict"]["training_rays"]["rays"] + loss = 0. + if "num_samples_regnerf" in out: + if out["num_samples_regnerf"] > 0: + transient_patch = out["transient_patch"] + depth_variance_patch = out["depth_variance_patch"] + + # Keep depth-related regularization consistent with eval depth definition when requested. + if bool(self.config.system.get("depth_from_transient_peak_for_losses", True)): + depth_patch = ( + torch.argmax(transient_patch[..., 0], dim=-1).to(transient_patch.dtype) + * (float(self.model.exposure_time) / 2.0) + ).reshape(self.config.model.train_patch_size, self.config.model.train_patch_size) + else: + depth_patch = out["depth_patch"].reshape(self.config.model.train_patch_size, self.config.model.train_patch_size) + + ##NOTE: Depth smoothness regularizer + v00 = depth_patch[:-1, :-1] + v01 = depth_patch[:-1, 1:] + v10 = depth_patch[1:, :-1] + smoothness_loss = torch.mean(((v00 - v01) ** 2) + ((v00 - v10) ** 2)) + + # Only apply depth variance loss to rays that actually see geometry + # (opacity above threshold). Rays that miss the scene have near-zero + # opacity; applying depth variance on them creates destructive gradients. + opacity_patch = out["opacity_patch"] # (patch_size, patch_size) + regnerf_opacity_threshold = float(self.config.system.get("regnerf_opacity_threshold", 0.1)) + visible_mask = opacity_patch.detach() > regnerf_opacity_threshold + if visible_mask.any(): + # Normalize depth variance by scene scale to prevent gradient + # explosion in large-scale scenes. Raw depth_variance scales as + # distance^2, so dividing by scene_extent^2 makes the loss + # magnitude scene-independent. + scene_extent = (self.model.scene_aabb[3:] - self.model.scene_aabb[:3]).max().item() + scene_scale_sq = max(scene_extent ** 2, 1.0) + raw_var = depth_variance_patch[visible_mask] + normalized_var = raw_var / scene_scale_sq + # Clamp to prevent outlier rays from dominating the gradient. + max_var = float(self.config.system.get("regnerf_max_depth_variance", 1.0)) + clamped_var = torch.clamp(normalized_var, max=max_var) + loss += clamped_var.mean() * self.C(self.config.system.loss.lambda_regnerf_depth_variance) + loss += smoothness_loss / scene_scale_sq * self.C(self.config.system.loss.lambda_depth_smoothness) + self.log('train/regnerf_visible_ratio', visible_mask.float().mean()) + self.log('train/regnerf_depth_var_raw', depth_variance_patch.detach().mean()) + if visible_mask.any(): + self.log('train/regnerf_depth_var_norm', clamped_var.detach().mean()) + + + #doen't do anything if self.dataset.rep=1 + gt_pixs = torch.reshape(batch["rgb"][:int(training_rays.shape[0]/self.dataset.rep)], (-1, self.dataset.n_bins, 3)) #Shape (n_rays,1200, 3) + data_valid_mask = batch.get("valid_mask", None) + if data_valid_mask is not None: + data_valid_mask = data_valid_mask.to(device=gt_pixs.device, dtype=torch.bool).reshape(-1) + if data_valid_mask.numel() < gt_pixs.shape[0]: + raise ValueError( + f"valid_mask has too few elements: {data_valid_mask.numel()} < base rays {gt_pixs.shape[0]}" + ) + data_valid_mask = data_valid_mask[: gt_pixs.shape[0]] + else: + data_valid_mask = torch.ones(gt_pixs.shape[0], dtype=torch.bool, device=gt_pixs.device) + + alive_ray_mask = out["rays_valid"].squeeze(-1) #(n_rays, 1) + alive_ray_mask = alive_ray_mask.reshape(self.dataset.rep, -1) + alive_ray_mask = alive_ray_mask.sum(0).bool() #shape of (num_rays,), #binary mask + + peak_thre_norm = self._get_meas_peak_threshold_norm() + if peak_thre_norm is not None: + meas_peak = torch.amax(gt_pixs[..., 0], dim=-1) + meas_valid_mask = meas_peak >= float(peak_thre_norm) + else: + meas_valid_mask = torch.ones(gt_pixs.shape[0], dtype=torch.bool, device=gt_pixs.device) + supervised_mask = alive_ray_mask & meas_valid_mask & data_valid_mask + + predicted_rgb = torch.reshape(out["rgb"], (-1, self.dataset.n_bins, 3))*batch["weights"][:, None, None] #(16, 1200, 3) + carve_mask = gt_pixs.sum(-1).repeat(self.dataset.rep, 1) < 1e-7 + valid_mask_flat = data_valid_mask.repeat(self.dataset.rep)[:, None] + carve_mask = carve_mask & valid_mask_flat.expand(-1, self.dataset.n_bins) + if carve_mask.any(): + comp_weights = out["comp_weights"][carve_mask].mean() + else: + comp_weights = torch.tensor(0.0, device=gt_pixs.device) + + + #the code below only makes a difference if self.rep > 1 + rgb = torch.zeros((int(predicted_rgb.shape[0]/self.dataset.rep), self.dataset.n_bins, 3)).to(self.rank) + index = torch.arange(int(predicted_rgb.shape[0]/self.dataset.rep)).repeat(self.dataset.rep)[:, None, None].expand(-1, self.dataset.n_bins, 3).to(self.rank) #(?,1200,3) + rgb.scatter_add_(0, index.type(torch.int64), predicted_rgb) + + # gt_pixs = torch.log(gt_pixs + 1) #(num_ray,n_bins,RGB) + # predicted_rgb = torch.log(rgb + 1) # (num_rays, n_bins, RGB) + gt_pixs = gt_pixs + predicted_rgb = rgb + + vis_every = max(1, int(self.config.system.get("train_full_view_vis_every_n_steps", 1000))) + vis_start = max(0, int(self.config.system.get("train_full_view_vis_start_step", 0))) + if self.global_step >= vis_start and self.global_step % vis_every == 0: + plot_mask = supervised_mask if supervised_mask.any() else (alive_ray_mask & data_valid_mask) + if plot_mask.any(): + plot_depth = ( + torch.argmax(predicted_rgb[plot_mask][..., 0], dim=-1).to(predicted_rgb.dtype) + * (float(self.model.exposure_time) / 2.0) + ) + self.save_plot(f"it{self.global_step}-transient_plot", torch.mean(predicted_rgb[plot_mask], dim=(0,2)), torch.mean(gt_pixs[plot_mask], dim=(0,2))) + self.save_depth_plot( + f"it{self.global_step}-transient_depth_plot", + predicted_rgb[plot_mask], + gt_pixs[plot_mask], + plot_depth, + self.model.exposure_time, + ) + self.save_sdf_plot( + f"it{self.global_step}-sdf_depth_plot", + out["sdf_samples"], + self.model.exposure_time, + out["distances_from_origin"], + plot_depth, + out["ray_indices"], + plot_mask, + ) + vis_index = None + if "rays_dict" in batch and "training_rays" in batch["rays_dict"]: + idx_tensor = batch["rays_dict"]["training_rays"].get("index", None) + if idx_tensor is not None: + vis_index = idx_tensor + try: + self._save_train_full_view_visualization(vis_index) + except Exception as ex: + self.print(f"[WARN] train full-view visualization failed at step {self.global_step}: {ex}") + + #integrated transient loss + #Normalize + Gamma correct + if supervised_mask.any(): + integrated_gt = gt_pixs[supervised_mask].sum(-2) + integrated_pred = predicted_rgb[supervised_mask].sum(-2) + loss_integrated = F.l1_loss(integrated_pred, integrated_gt, reduction="mean") + else: + loss_integrated = torch.tensor(0.0, device=gt_pixs.device) + loss += loss_integrated * self.C(self.config.system.loss.lambda_integrated_l1) + + #photometric loss + if supervised_mask.any(): + loss_rgb_l1 = F.l1_loss(predicted_rgb[supervised_mask], gt_pixs[supervised_mask]) + else: + loss_rgb_l1 = torch.tensor(0.0, device=gt_pixs.device) + self.log('train/loss_rgb', loss_rgb_l1) + self.log('train/supervised_ratio', supervised_mask.float().mean()) + loss += loss_rgb_l1 * self.C(self.config.system.loss.lambda_rgb_l1) + + + #space carving loss proposed in https://arxiv.org/pdf/2307.09555.pdf + space_carving_loss = comp_weights + self.log('train/space_carving_loss', space_carving_loss) + loss += space_carving_loss * self.C(self.config.system.loss.lambda_space_carving) + + loss_eikonal = ((torch.linalg.norm(out['sdf_grad_samples'], ord=2, dim=-1) - 1.)**2).mean() + self.log('train/loss_eikonal', loss_eikonal, prog_bar=True) + loss += loss_eikonal * self.C(self.config.system.loss.lambda_eikonal) + + loss_sparsity = torch.exp(-self.config.system.loss.sparsity_scale * out['sdf_samples'].abs()).mean() + self.log('train/loss_sparsity', loss_sparsity) + loss += loss_sparsity * self.C(self.config.system.loss.lambda_sparsity) + + if not torch.isfinite(loss).all(): + raise FloatingPointError(f'Non-finite training loss at step {self.global_step}; optimizer update aborted.') + + self.log('train/inv_s', out['inv_s'], prog_bar=True) + + if 'num_samples' in out: + self.log('train/num_samples', out['num_samples'].float().mean(), prog_bar=True) + self.log('train/num_rays', float(self.train_num_rays), prog_bar=True) + + ret = { + 'loss': loss + } + if t0 is not None: + self.print(f"[DBG] step={self.global_step} training_step total dt={time.perf_counter()-t0:.3f}s") + return ret + + """ + # aggregate outputs from different devices (DP) + def training_step_end(self, out): + pass + """ + + """ + # aggregate outputs from different iterations + def training_epoch_end(self, out): + pass + """ + + def validation_step(self, batch, batch_idx): + out = self(batch) + + W, H = self.dataset.img_wh + predicted_image = out["rgb"].reshape(H, W, self.model.n_bins, 3) #(H, W, n_bins, 3) + predicted_image = predicted_image.sum(-2) #(512,512,3) + predicted_image = predicted_image.mean(-1) #(512,512) + predicted_image = torch.stack([predicted_image, predicted_image, predicted_image], -1) #(512,512,3) + predicted_image = (predicted_image/predicted_image.max())**(1/2.2) #(512,512,3) + + point_x_patch, point_y_patch = np.meshgrid(np.arange(W//2, W//2 + 3),np.arange(H//2, H//2 + 3),indexing="xy") + point_x_patch, point_y_patch = point_x_patch.flatten(), point_y_patch.flatten() + self.save_plot_grid(f"it{self.global_step}-{batch['index'][0].item()}-regnerf_patch_transient", point_x_patch, point_y_patch, out["rgb"].view(H, W, self.model.n_bins, 3),self.global_step) + + #Sample 9 points, 3 from the top, 3 from the middle and 3 from the bottom + point_x = np.array([W//4,W//2,3*W//4,W//4,W//2,3*W//4,W//4,W//2,3*W//4]) + point_y = np.array([H//4,H//4,H//4,H//2,H//2,H//2,3*H//4,3*H//4,3*H//4]) + self.save_plot_grid(f"it{self.global_step}-{batch['index'][0].item()}-regnerf_transient.png", point_x, point_y, out["rgb"].view(H, W, self.model.n_bins, 3), self.global_step) + + depth_image = (out["depth"]*torch.squeeze(out["opacity"])).view(H,W) + + self.save_image_grid(f"it{self.global_step}-{batch['index'][0].item()}.png", [ + {'type': 'rgb', 'img': predicted_image.view(H, W, 3), 'kwargs': {'data_format': 'HWC'}}, + {'type': 'grayscale', 'img': depth_image, 'kwargs': {}} + ]) + + return True + + """ + # aggregate outputs from different devices when using DP + def validation_step_end(self, out): + pass + """ + def validation_epoch_end(self, out): + pass + + def on_test_start(self): + from evaluation.renderer import start_test + start_test(self) + + def test_step(self, batch, batch_idx): + from evaluation.renderer import render_histogram + prediction = render_histogram(self, batch) + index = int(batch['index'].reshape(-1)[0].item()) + self._evaluation_run.score(prediction, index) + + def test_epoch_end(self, out): + # Frame completeness and aggregation belong to the common evaluator. + self.print(str(self._evaluation_run.finish())) + + def export(self): + mesh = self.model.export(self.config.export) + mesh_path = self.save_mesh( + f"it{self.global_step}-{self.config.model.geometry.isosurface.method}{self.config.model.geometry.isosurface.resolution}-{self.dataset.n_views}_{self.dataset.scene}.obj", + **mesh + ) + return mesh_path diff --git a/codes/reconstruction/transientangelo/systems/utils.py b/codes/reconstruction/transientangelo/systems/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e880ebdcabc30bd25f91f4d068b953cb1cb902f0 --- /dev/null +++ b/codes/reconstruction/transientangelo/systems/utils.py @@ -0,0 +1,353 @@ +import sys +import warnings +from bisect import bisect_right + +import torch +import torch.nn as nn +from torch.optim import lr_scheduler + +from pytorch_lightning.utilities.rank_zero import rank_zero_debug +from utils.misc import config_to_primitive + + +class ChainedScheduler(lr_scheduler._LRScheduler): + """Chains list of learning rate schedulers. It takes a list of chainable learning + rate schedulers and performs consecutive step() functions belong to them by just + one call. + + Args: + schedulers (list): List of chained schedulers. + + Example: + >>> # Assuming optimizer uses lr = 1. for all groups + >>> # lr = 0.09 if epoch == 0 + >>> # lr = 0.081 if epoch == 1 + >>> # lr = 0.729 if epoch == 2 + >>> # lr = 0.6561 if epoch == 3 + >>> # lr = 0.59049 if epoch >= 4 + >>> scheduler1 = ConstantLR(self.opt, factor=0.1, total_iters=2) + >>> scheduler2 = ExponentialLR(self.opt, gamma=0.9) + >>> scheduler = ChainedScheduler([scheduler1, scheduler2]) + >>> for epoch in range(100): + >>> train(...) + >>> validate(...) + >>> scheduler.step() + """ + + def __init__(self, optimizer, schedulers): + for scheduler_idx in range(1, len(schedulers)): + if (schedulers[scheduler_idx].optimizer != schedulers[0].optimizer): + raise ValueError( + "ChainedScheduler expects all schedulers to belong to the same optimizer, but " + "got schedulers at index {} and {} to be different".format(0, scheduler_idx) + ) + self._schedulers = list(schedulers) + self.optimizer = optimizer + + def step(self): + for scheduler in self._schedulers: + scheduler.step() + + def state_dict(self): + """Returns the state of the scheduler as a :class:`dict`. + + It contains an entry for every variable in self.__dict__ which + is not the optimizer. + The wrapped scheduler states will also be saved. + """ + state_dict = {key: value for key, value in self.__dict__.items() if key not in ('optimizer', '_schedulers')} + state_dict['_schedulers'] = [None] * len(self._schedulers) + + for idx, s in enumerate(self._schedulers): + state_dict['_schedulers'][idx] = s.state_dict() + + return state_dict + + def load_state_dict(self, state_dict): + """Loads the schedulers state. + + Args: + state_dict (dict): scheduler state. Should be an object returned + from a call to :meth:`state_dict`. + """ + _schedulers = state_dict.pop('_schedulers') + self.__dict__.update(state_dict) + # Restore state_dict keys in order to prevent side effects + # https://github.com/pytorch/pytorch/issues/32756 + state_dict['_schedulers'] = _schedulers + + for idx, s in enumerate(_schedulers): + self._schedulers[idx].load_state_dict(s) + + +class SequentialLR(lr_scheduler._LRScheduler): + """Receives the list of schedulers that is expected to be called sequentially during + optimization process and milestone points that provides exact intervals to reflect + which scheduler is supposed to be called at a given epoch. + + Args: + schedulers (list): List of chained schedulers. + milestones (list): List of integers that reflects milestone points. + + Example: + >>> # Assuming optimizer uses lr = 1. for all groups + >>> # lr = 0.1 if epoch == 0 + >>> # lr = 0.1 if epoch == 1 + >>> # lr = 0.9 if epoch == 2 + >>> # lr = 0.81 if epoch == 3 + >>> # lr = 0.729 if epoch == 4 + >>> scheduler1 = ConstantLR(self.opt, factor=0.1, total_iters=2) + >>> scheduler2 = ExponentialLR(self.opt, gamma=0.9) + >>> scheduler = SequentialLR(self.opt, schedulers=[scheduler1, scheduler2], milestones=[2]) + >>> for epoch in range(100): + >>> train(...) + >>> validate(...) + >>> scheduler.step() + """ + + def __init__(self, optimizer, schedulers, milestones, last_epoch=-1, verbose=False): + for scheduler_idx in range(1, len(schedulers)): + if (schedulers[scheduler_idx].optimizer != schedulers[0].optimizer): + raise ValueError( + "Sequential Schedulers expects all schedulers to belong to the same optimizer, but " + "got schedulers at index {} and {} to be different".format(0, scheduler_idx) + ) + if (len(milestones) != len(schedulers) - 1): + raise ValueError( + "Sequential Schedulers expects number of schedulers provided to be one more " + "than the number of milestone points, but got number of schedulers {} and the " + "number of milestones to be equal to {}".format(len(schedulers), len(milestones)) + ) + self._schedulers = schedulers + self._milestones = milestones + self.last_epoch = last_epoch + 1 + self.optimizer = optimizer + + def step(self): + self.last_epoch += 1 + idx = bisect_right(self._milestones, self.last_epoch) + if idx > 0 and self._milestones[idx - 1] == self.last_epoch: + self._schedulers[idx].step(0) + else: + self._schedulers[idx].step() + + def state_dict(self): + """Returns the state of the scheduler as a :class:`dict`. + + It contains an entry for every variable in self.__dict__ which + is not the optimizer. + The wrapped scheduler states will also be saved. + """ + state_dict = {key: value for key, value in self.__dict__.items() if key not in ('optimizer', '_schedulers')} + state_dict['_schedulers'] = [None] * len(self._schedulers) + + for idx, s in enumerate(self._schedulers): + state_dict['_schedulers'][idx] = s.state_dict() + + return state_dict + + def load_state_dict(self, state_dict): + """Loads the schedulers state. + + Args: + state_dict (dict): scheduler state. Should be an object returned + from a call to :meth:`state_dict`. + """ + _schedulers = state_dict.pop('_schedulers') + self.__dict__.update(state_dict) + # Restore state_dict keys in order to prevent side effects + # https://github.com/pytorch/pytorch/issues/32756 + state_dict['_schedulers'] = _schedulers + + for idx, s in enumerate(_schedulers): + self._schedulers[idx].load_state_dict(s) + + +class ConstantLR(lr_scheduler._LRScheduler): + """Decays the learning rate of each parameter group by a small constant factor until the + number of epoch reaches a pre-defined milestone: total_iters. Notice that such decay can + happen simultaneously with other changes to the learning rate from outside this scheduler. + When last_epoch=-1, sets initial lr as lr. + + Args: + optimizer (Optimizer): Wrapped optimizer. + factor (float): The number we multiply learning rate until the milestone. Default: 1./3. + total_iters (int): The number of steps that the scheduler decays the learning rate. + Default: 5. + last_epoch (int): The index of the last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + + Example: + >>> # Assuming optimizer uses lr = 0.05 for all groups + >>> # lr = 0.025 if epoch == 0 + >>> # lr = 0.025 if epoch == 1 + >>> # lr = 0.025 if epoch == 2 + >>> # lr = 0.025 if epoch == 3 + >>> # lr = 0.05 if epoch >= 4 + >>> scheduler = ConstantLR(self.opt, factor=0.5, total_iters=4) + >>> for epoch in range(100): + >>> train(...) + >>> validate(...) + >>> scheduler.step() + """ + + def __init__(self, optimizer, factor=1.0 / 3, total_iters=5, last_epoch=-1, verbose=False): + if factor > 1.0 or factor < 0: + raise ValueError('Constant multiplicative factor expected to be between 0 and 1.') + + self.factor = factor + self.total_iters = total_iters + super(ConstantLR, self).__init__(optimizer, last_epoch, verbose) + + def get_lr(self): + if not self._get_lr_called_within_step: + warnings.warn("To get the last learning rate computed by the scheduler, " + "please use `get_last_lr()`.", UserWarning) + + if self.last_epoch == 0: + return [group['lr'] * self.factor for group in self.optimizer.param_groups] + + if (self.last_epoch > self.total_iters or + (self.last_epoch != self.total_iters)): + return [group['lr'] for group in self.optimizer.param_groups] + + if (self.last_epoch == self.total_iters): + return [group['lr'] * (1.0 / self.factor) for group in self.optimizer.param_groups] + + def _get_closed_form_lr(self): + return [base_lr * (self.factor + (self.last_epoch >= self.total_iters) * (1 - self.factor)) + for base_lr in self.base_lrs] + + +class LinearLR(lr_scheduler._LRScheduler): + """Decays the learning rate of each parameter group by linearly changing small + multiplicative factor until the number of epoch reaches a pre-defined milestone: total_iters. + Notice that such decay can happen simultaneously with other changes to the learning rate + from outside this scheduler. When last_epoch=-1, sets initial lr as lr. + + Args: + optimizer (Optimizer): Wrapped optimizer. + start_factor (float): The number we multiply learning rate in the first epoch. + The multiplication factor changes towards end_factor in the following epochs. + Default: 1./3. + end_factor (float): The number we multiply learning rate at the end of linear changing + process. Default: 1.0. + total_iters (int): The number of iterations that multiplicative factor reaches to 1. + Default: 5. + last_epoch (int): The index of the last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + + Example: + >>> # Assuming optimizer uses lr = 0.05 for all groups + >>> # lr = 0.025 if epoch == 0 + >>> # lr = 0.03125 if epoch == 1 + >>> # lr = 0.0375 if epoch == 2 + >>> # lr = 0.04375 if epoch == 3 + >>> # lr = 0.05 if epoch >= 4 + >>> scheduler = LinearLR(self.opt, start_factor=0.5, total_iters=4) + >>> for epoch in range(100): + >>> train(...) + >>> validate(...) + >>> scheduler.step() + """ + + def __init__(self, optimizer, start_factor=1.0 / 3, end_factor=1.0, total_iters=5, last_epoch=-1, + verbose=False): + if start_factor > 1.0 or start_factor < 0: + raise ValueError('Starting multiplicative factor expected to be between 0 and 1.') + + if end_factor > 1.0 or end_factor < 0: + raise ValueError('Ending multiplicative factor expected to be between 0 and 1.') + + self.start_factor = start_factor + self.end_factor = end_factor + self.total_iters = total_iters + super(LinearLR, self).__init__(optimizer, last_epoch, verbose) + + def get_lr(self): + if not self._get_lr_called_within_step: + warnings.warn("To get the last learning rate computed by the scheduler, " + "please use `get_last_lr()`.", UserWarning) + + if self.last_epoch == 0: + return [group['lr'] * self.start_factor for group in self.optimizer.param_groups] + + if (self.last_epoch > self.total_iters): + return [group['lr'] for group in self.optimizer.param_groups] + + return [group['lr'] * (1. + (self.end_factor - self.start_factor) / + (self.total_iters * self.start_factor + (self.last_epoch - 1) * (self.end_factor - self.start_factor))) + for group in self.optimizer.param_groups] + + def _get_closed_form_lr(self): + return [base_lr * (self.start_factor + + (self.end_factor - self.start_factor) * min(self.total_iters, self.last_epoch) / self.total_iters) + for base_lr in self.base_lrs] + + +custom_schedulers = ['ConstantLR', 'LinearLR'] +def get_scheduler(name): + if hasattr(lr_scheduler, name): + return getattr(lr_scheduler, name) + elif name in custom_schedulers: + return getattr(sys.modules[__name__], name) + else: + raise NotImplementedError + + +def getattr_recursive(m, attr): + for name in attr.split('.'): + m = getattr(m, name) + return m + + +def get_parameters(model, name): + module = getattr_recursive(model, name) + if isinstance(module, nn.Module): + return module.parameters() + elif isinstance(module, nn.Parameter): + return module + return [] + + +def parse_optimizer(config, model): + if hasattr(config, 'params'): + params = [{'params': get_parameters(model, name), 'name': name, **config_to_primitive(args)} for name, args in config.params.items()] + rank_zero_debug('Specify optimizer params:', config.params) + else: + params = model.parameters() + if config.name in ['FusedAdam']: + # import apex + # optim = getattr(apex.optimizers, config.name)(params, **config.args) + raise NotImplementedError + else: + optim = getattr(torch.optim, config.name)(params, **config_to_primitive(config.args)) + return optim + + +def parse_scheduler(config, optimizer): + interval = config.get('interval', 'epoch') + assert interval in ['epoch', 'step'] + if config.name == 'SequentialLR': + scheduler = { + 'scheduler': SequentialLR(optimizer, [parse_scheduler(conf, optimizer)['scheduler'] for conf in config.schedulers], milestones=list(config.milestones)), + 'interval': interval + } + elif config.name == 'Chained': + scheduler = { + 'scheduler': ChainedScheduler([parse_scheduler(conf, optimizer)['scheduler'] for conf in config.schedulers]), + 'interval': interval + } + else: + scheduler = { + 'scheduler': get_scheduler(config.name)(optimizer, **config_to_primitive(config.args)), + 'interval': interval + } + return scheduler + + +def update_module_step(m, epoch, global_step): + if hasattr(m, 'update_step'): + m.update_step(epoch, global_step) diff --git a/codes/reconstruction/transientangelo/utils/__init__.py b/codes/reconstruction/transientangelo/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/transientangelo/utils/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/transientangelo/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0488b46e0aae7b50f8f45a6c679b9c03e884e7d8 Binary files /dev/null and b/codes/reconstruction/transientangelo/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/utils/__pycache__/callbacks.cpython-312.pyc b/codes/reconstruction/transientangelo/utils/__pycache__/callbacks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56d3de43cf4789bb97c019060ecd882a872f6411 Binary files /dev/null and b/codes/reconstruction/transientangelo/utils/__pycache__/callbacks.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/utils/__pycache__/misc.cpython-312.pyc b/codes/reconstruction/transientangelo/utils/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43121c4437633cf42b80743ea171148a4de3fd12 Binary files /dev/null and b/codes/reconstruction/transientangelo/utils/__pycache__/misc.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/utils/__pycache__/mixins.cpython-312.pyc b/codes/reconstruction/transientangelo/utils/__pycache__/mixins.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22211ed839975804ae1248415bfd07a3d2018f7f Binary files /dev/null and b/codes/reconstruction/transientangelo/utils/__pycache__/mixins.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/utils/__pycache__/obj.cpython-312.pyc b/codes/reconstruction/transientangelo/utils/__pycache__/obj.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab7b00544fa6ac4a3d4c497bd59c939c724437a3 Binary files /dev/null and b/codes/reconstruction/transientangelo/utils/__pycache__/obj.cpython-312.pyc differ diff --git a/codes/reconstruction/transientangelo/utils/callbacks.py b/codes/reconstruction/transientangelo/utils/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..22f39efdb2f381ff677f5311c0586fbad88ae34f --- /dev/null +++ b/codes/reconstruction/transientangelo/utils/callbacks.py @@ -0,0 +1,99 @@ +import os +import subprocess +import shutil +from utils.misc import dump_config, parse_version + + +import pytorch_lightning +if parse_version(pytorch_lightning.__version__) > parse_version('1.8'): + from pytorch_lightning.callbacks import Callback +else: + from pytorch_lightning.callbacks.base import Callback +from pytorch_lightning.utilities.rank_zero import rank_zero_only, rank_zero_warn +from pytorch_lightning.callbacks.progress import TQDMProgressBar + + +class VersionedCallback(Callback): + def __init__(self, save_root, version=None, use_version=True): + self.save_root = save_root + self._version = version + self.use_version = use_version + + @property + def version(self) -> int: + """Get the experiment version. + + Returns: + The experiment version if specified else the next version. + """ + if self._version is None: + self._version = self._get_next_version() + return self._version + + def _get_next_version(self): + existing_versions = [] + if os.path.isdir(self.save_root): + for f in os.listdir(self.save_root): + bn = os.path.basename(f) + if bn.startswith("version_"): + dir_ver = os.path.splitext(bn)[0].split("_")[1].replace("/", "") + existing_versions.append(int(dir_ver)) + if len(existing_versions) == 0: + return 0 + return max(existing_versions) + 1 + + @property + def savedir(self): + if not self.use_version: + return self.save_root + return os.path.join(self.save_root, self.version if isinstance(self.version, str) else f"version_{self.version}") + + +class CodeSnapshotCallback(VersionedCallback): + def __init__(self, save_root, version=None, use_version=True): + super().__init__(save_root, version, use_version) + + def get_file_list(self): + return [ + b.decode() for b in + set(subprocess.check_output('git ls-files', shell=True).splitlines()) | + set(subprocess.check_output('git ls-files --others --exclude-standard', shell=True).splitlines()) + ] + + @rank_zero_only + def save_code_snapshot(self): + os.makedirs(self.savedir, exist_ok=True) + for f in self.get_file_list(): + if not os.path.exists(f) or os.path.isdir(f): + continue + os.makedirs(os.path.join(self.savedir, os.path.dirname(f)), exist_ok=True) + shutil.copyfile(f, os.path.join(self.savedir, f)) + + def on_fit_start(self, trainer, pl_module): + try: + self.save_code_snapshot() + except: + rank_zero_warn("Code snapshot is not saved. Please make sure you have git installed and are in a git repository.") + + +class ConfigSnapshotCallback(VersionedCallback): + def __init__(self, config, save_root, version=None, use_version=True): + super().__init__(save_root, version, use_version) + self.config = config + + @rank_zero_only + def save_config_snapshot(self): + os.makedirs(self.savedir, exist_ok=True) + dump_config(os.path.join(self.savedir, 'parsed.yaml'), self.config) + shutil.copyfile(self.config.cmd_args['config'], os.path.join(self.savedir, 'raw.yaml')) + + def on_fit_start(self, trainer, pl_module): + self.save_config_snapshot() + + +class CustomProgressBar(TQDMProgressBar): + def get_metrics(self, *args, **kwargs): + # don't show the version number + items = super().get_metrics(*args, **kwargs) + items.pop("v_num", None) + return items diff --git a/codes/reconstruction/transientangelo/utils/misc.py b/codes/reconstruction/transientangelo/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..c16fafa2ab8e7b934be711c41aed6e12001444fd --- /dev/null +++ b/codes/reconstruction/transientangelo/utils/misc.py @@ -0,0 +1,54 @@ +import os +from omegaconf import OmegaConf +from packaging import version + + +# ============ Register OmegaConf Recolvers ============= # +OmegaConf.register_new_resolver('calc_exp_lr_decay_rate', lambda factor, n: factor**(1./n)) +OmegaConf.register_new_resolver('add', lambda a, b: a + b) +OmegaConf.register_new_resolver('sub', lambda a, b: a - b) +OmegaConf.register_new_resolver('mul', lambda a, b: a * b) +OmegaConf.register_new_resolver('div', lambda a, b: a / b) +OmegaConf.register_new_resolver('idiv', lambda a, b: a // b) +OmegaConf.register_new_resolver('basename', lambda p: os.path.basename(p)) +# ======================================================= # + + +def prompt(question): + inp = input(f"{question} (y/n)").lower().strip() + if inp and inp == 'y': + return True + if inp and inp == 'n': + return False + return prompt(question) + + +def load_config(*yaml_files, cli_args=[]): + yaml_confs = [OmegaConf.load(f) for f in yaml_files] + cli_conf = OmegaConf.from_cli(cli_args) + conf = OmegaConf.merge(*yaml_confs, cli_conf) + OmegaConf.resolve(conf) + return conf + + +def config_to_primitive(config, resolve=True): + return OmegaConf.to_container(config, resolve=resolve) + + +def dump_config(path, config): + with open(path, 'w') as fp: + OmegaConf.save(config=config, f=fp) + +def get_rank(): + # SLURM_PROCID can be set even if SLURM is not managing the multiprocessing, + # therefore LOCAL_RANK needs to be checked first + rank_keys = ("RANK", "LOCAL_RANK", "SLURM_PROCID", "JSM_NAMESPACE_RANK") + for key in rank_keys: + rank = os.environ.get(key) + if rank is not None: + return int(rank) + return 0 + + +def parse_version(ver): + return version.parse(ver) diff --git a/codes/reconstruction/transientangelo/utils/mixins.py b/codes/reconstruction/transientangelo/utils/mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..5e59b1a49032c9d034150c500dc2d22e313e2ced --- /dev/null +++ b/codes/reconstruction/transientangelo/utils/mixins.py @@ -0,0 +1,597 @@ +import os +import re +import shutil +import numpy as np +import cv2 +import imageio +from matplotlib import cm +from matplotlib.colors import LinearSegmentedColormap +from matplotlib.gridspec import GridSpec +import matplotlib.pyplot as plt +import json +from prettytable import PrettyTable +import torch +import matplotlib.patches as patches +from nerfacc import accumulate_along_rays +from utils.obj import write_obj + + +class SaverMixin(): + @property + def save_dir(self): + return self.config.save_dir + + def convert_data(self, data): + if isinstance(data, np.ndarray): + return data + elif isinstance(data, torch.Tensor): + return data.cpu().numpy() + elif isinstance(data, list): + return [self.convert_data(d) for d in data] + elif isinstance(data, dict): + return {k: self.convert_data(v) for k, v in data.items()} + else: + raise TypeError('Data must be in type numpy.ndarray, torch.Tensor, list or dict, getting', type(data)) + + def get_save_path(self, filename): + save_path = os.path.join(self.save_dir, filename) + os.makedirs(os.path.dirname(save_path), exist_ok=True) + return save_path + + DEFAULT_RGB_KWARGS = {'data_format': 'CHW', 'data_range': (0, 1)} + DEFAULT_UV_KWARGS = {'data_format': 'CHW', 'data_range': (0, 1), 'cmap': 'checkerboard'} + DEFAULT_GRAYSCALE_KWARGS = {'data_range': None, 'cmap': 'jet'} + + def get_rgb_image_(self, img, data_format, data_range): + img = self.convert_data(img) + assert data_format in ['CHW', 'HWC'] + if data_format == 'CHW': + img = img.transpose(1, 2, 0) + img = img.clip(min=data_range[0], max=data_range[1]) + img = ((img - data_range[0]) / (data_range[1] - data_range[0]) * 255.).astype(np.uint8) + imgs = [img[...,start:start+3] for start in range(0, img.shape[-1], 3)] + imgs = [img_ if img_.shape[-1] == 3 else np.concatenate([img_, np.zeros((img_.shape[0], img_.shape[1], 3 - img_.shape[2]), dtype=img_.dtype)], axis=-1) for img_ in imgs] + img = np.concatenate(imgs, axis=1) + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + return img + + def save_rgb_image(self, filename, img, data_format=DEFAULT_RGB_KWARGS['data_format'], data_range=DEFAULT_RGB_KWARGS['data_range']): + img = self.get_rgb_image_(img, data_format, data_range) + cv2.imwrite(self.get_save_path(filename), img) + + def get_uv_image_(self, img, data_format, data_range, cmap): + img = self.convert_data(img) + assert data_format in ['CHW', 'HWC'] + if data_format == 'CHW': + img = img.transpose(1, 2, 0) + img = img.clip(min=data_range[0], max=data_range[1]) + img = (img - data_range[0]) / (data_range[1] - data_range[0]) + assert cmap in ['checkerboard', 'color'] + if cmap == 'checkerboard': + n_grid = 64 + mask = (img * n_grid).astype(int) + mask = (mask[...,0] + mask[...,1]) % 2 == 0 + img = np.ones((img.shape[0], img.shape[1], 3), dtype=np.uint8) * 255 + img[mask] = np.array([255, 0, 255], dtype=np.uint8) + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + elif cmap == 'color': + img_ = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) + img_[..., 0] = (img[..., 0] * 255).astype(np.uint8) + img_[..., 1] = (img[..., 1] * 255).astype(np.uint8) + img_ = cv2.cvtColor(img_, cv2.COLOR_RGB2BGR) + img = img_ + return img + + def save_uv_image(self, filename, img, data_format=DEFAULT_UV_KWARGS['data_format'], data_range=DEFAULT_UV_KWARGS['data_range'], cmap=DEFAULT_UV_KWARGS['cmap']): + img = self.get_uv_image_(img, data_format, data_range, cmap) + cv2.imwrite(self.get_save_path(filename), img) + + def get_grayscale_image_(self, img, data_range, cmap): + img = self.convert_data(img) + img = np.nan_to_num(img) + if data_range is None: + img = (img - img.min()) / (img.max() - img.min()) + else: + img = img.clip(data_range[0], data_range[1]) + img = (img - data_range[0]) / (data_range[1] - data_range[0]) + assert cmap in [None, 'jet', 'magma'] + if cmap == None: + img = (img * 255.).astype(np.uint8) + img = np.repeat(img[...,None], 3, axis=2) + elif cmap == 'jet': + img = (img * 255.).astype(np.uint8) + img = cv2.applyColorMap(img, cv2.COLORMAP_JET) + elif cmap == 'magma': + img = 1. - img + base = cm.get_cmap('magma') + num_bins = 256 + colormap = LinearSegmentedColormap.from_list( + f"{base.name}{num_bins}", + base(np.linspace(0, 1, num_bins)), + num_bins + )(np.linspace(0, 1, num_bins))[:,:3] + a = np.floor(img * 255.) + b = (a + 1).clip(max=255.) + f = img * 255. - a + a = a.astype(np.uint16).clip(0, 255) + b = b.astype(np.uint16).clip(0, 255) + img = colormap[a] + (colormap[b] - colormap[a]) * f[...,None] + img = (img * 255.).astype(np.uint8) + return img + + def save_grayscale_image(self, filename, img, data_range=DEFAULT_GRAYSCALE_KWARGS['data_range'], cmap=DEFAULT_GRAYSCALE_KWARGS['cmap']): + img = self.get_grayscale_image_(img, data_range, cmap) + cv2.imwrite(self.get_save_path(filename), img) + + def get_image_grid_(self, imgs): + if isinstance(imgs[0], list): + return np.concatenate([self.get_image_grid_(row) for row in imgs], axis=0) + cols = [] + for col in imgs: + assert col['type'] in ['rgb', 'uv', 'grayscale'] + if col['type'] == 'rgb': + rgb_kwargs = self.DEFAULT_RGB_KWARGS.copy() + rgb_kwargs.update(col['kwargs']) + cols.append(self.get_rgb_image_(col['img'], **rgb_kwargs)) + elif col['type'] == 'uv': + uv_kwargs = self.DEFAULT_UV_KWARGS.copy() + uv_kwargs.update(col['kwargs']) + cols.append(self.get_uv_image_(col['img'], **uv_kwargs)) + elif col['type'] == 'grayscale': + grayscale_kwargs = self.DEFAULT_GRAYSCALE_KWARGS.copy() + grayscale_kwargs.update(col['kwargs']) + cols.append(self.get_grayscale_image_(col['img'], **grayscale_kwargs)) + return np.concatenate(cols, axis=1) + + def save_image_grid(self, filename, imgs): + img = self.get_image_grid_(imgs) + cv2.imwrite(self.get_save_path(filename), img) + + def save_image_plot_grid(self, filename, imgs): + '''Assume the imgs are already preprocessed and ready to be plotted. + imgs is a list of dicts where each dict has some keys with plotting options such as title or cmap. + + ''' + fig, axes = plt.subplots(1, len(imgs), figsize=(20, 5)) + for i, img_dict in enumerate(imgs): + if img_dict["type"] == "rgb": + axes[i].imshow(img_dict["img"]) + + elif img_dict["type"] == "depth": + axes[i].imshow(img_dict["img"], cmap=img_dict["kwargs"]["cmap"], vmin=img_dict["kwargs"]["vmin"], vmax=img_dict["kwargs"]["vmax"]) + + axes[i].set_title(img_dict["kwargs"]["title"]) + axes[i].axis('off') + + plt.savefig(self.get_save_path(filename)) + plt.close(fig) + + + def save_image(self, filename, img): + img = self.convert_data(img) + assert img.dtype == np.uint8 + if img.shape[-1] == 3: + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + elif img.shape[-1] == 4: + img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGRA) + cv2.imwrite(self.get_save_path(filename), img) + + def save_cubemap(self, filename, img, data_range=(0, 1)): + img = self.convert_data(img) + assert img.ndim == 4 and img.shape[0] == 6 and img.shape[1] == img.shape[2] + + imgs_full = [] + for start in range(0, img.shape[-1], 3): + img_ = img[...,start:start+3] + img_ = np.stack([self.get_rgb_image_(img_[i], 'HWC', data_range) for i in range(img_.shape[0])], axis=0) + size = img_.shape[1] + placeholder = np.zeros((size, size, 3), dtype=np.float32) + img_full = np.concatenate([ + np.concatenate([placeholder, img_[2], placeholder, placeholder], axis=1), + np.concatenate([img_[1], img_[4], img_[0], img_[5]], axis=1), + np.concatenate([placeholder, img_[3], placeholder, placeholder], axis=1) + ], axis=0) + img_full = cv2.cvtColor(img_full, cv2.COLOR_RGB2BGR) + imgs_full.append(img_full) + + imgs_full = np.concatenate(imgs_full, axis=1) + cv2.imwrite(self.get_save_path(filename), imgs_full) + + def save_data(self, filename, data): + data = self.convert_data(data) + if isinstance(data, dict): + if not filename.endswith('.npz'): + filename += '.npz' + np.savez(self.get_save_path(filename), **data) + else: + if not filename.endswith('.npy'): + filename += '.npy' + np.save(self.get_save_path(filename), data) + + def save_state_dict(self, filename, data): + torch.save(data, self.get_save_path(filename)) + + def generate_video(images, output_path, fps): + # Determine the width and height of the images + writer = imageio.get_writer(output_path, fps=fps) + for image in images: + writer.append_data(image) + writer.close() + + + def save_img_sequence(self, filename, img_dir, matcher, save_format='gif', fps=30, reversed=False): + assert save_format in ['gif', 'mp4'] + if not filename.endswith(save_format): + filename += f".{save_format}" + matcher = re.compile(matcher) + img_dir = os.path.join(self.save_dir, img_dir) + imgs = [] + for f in os.listdir(img_dir): + if matcher.search(f): + imgs.append(f) + imgs = sorted(imgs, key=lambda f: int(matcher.search(f).groups()[0])) + if reversed: + imgs = imgs[::-1] + imgs = [cv2.imread(os.path.join(img_dir, f)) for f in imgs] + + if save_format == 'gif': + imgs = [cv2.cvtColor(i, cv2.COLOR_BGR2RGB) for i in imgs] + imageio.mimsave(self.get_save_path(filename), imgs, fps=fps, palettesize=256) + elif save_format == 'mp4': + imgs = [cv2.cvtColor(i, cv2.COLOR_BGR2RGB) for i in imgs] + imageio.mimsave(self.get_save_path(filename), imgs, fps=fps) + + def save_mesh(self, filename, v_pos, t_pos_idx, v_tex=None, t_tex_idx=None, v_rgb=None): + ''' + Return the path to the saved mesh file and also saves the mesh file. + ''' + v_pos, t_pos_idx = self.convert_data(v_pos), self.convert_data(t_pos_idx) + if v_rgb is not None: + v_rgb = self.convert_data(v_rgb) + + import trimesh + mesh = trimesh.Trimesh( + vertices=v_pos, + faces=t_pos_idx, + vertex_colors=v_rgb + ) + saved_path = self.get_save_path(filename) + mesh.export(saved_path) + return saved_path + + def save_file(self, filename, src_path): + shutil.copyfile(src_path, self.get_save_path(filename)) + + def save_json(self, filename, payload): + with open(self.get_save_path(filename), 'w') as f: + f.write(json.dumps(payload)) + + def save_plot(self, filename, predicted, gt): + assert predicted.dim() == 1 + assert predicted.shape == gt.shape + plt.plot(predicted.cpu().detach().numpy(), label='predicted transient') + plt.plot(gt.cpu().detach().numpy(), label='ground truth transient') + plt.legend() + plt.title("Channel-Averaged Ground Truth vs Predicted Transient") + plt.savefig(self.get_save_path(filename)) + plt.close() + + + def save_depth_plot(self, filename, predicted, gt, depth, exposure_time): + ''' + Logic: pick the first gt transient of the first ray and average intensity across color channel and plot the depth values + ''' + plt.plot(torch.mean(predicted[0], dim=-1).cpu().detach().numpy(), label = "Predicted transient") + plt.plot(torch.mean(gt[0], dim=-1).cpu().detach().numpy(), label = "Ground truth transient") + plt.axvline(x=(depth[0]*2/exposure_time).detach().cpu().numpy(), color='r', linestyle='--', label='Predicted depth') + plt.legend(fontsize="small") + plt.title("Ground Truth vs Predicted Transient with Depth for the first visible ray and first color channel", fontsize=10) + + plt.savefig(self.get_save_path(filename)) + plt.close() + + + def save_sdf_plot(self, filename, sdf, exposure_time, distances_from_origin, depth, ray_indices, alive_ray_mask): + ''' + Plot the sdfs plot as a function of the distances from the origin and depth + ''' + #Find the first ray that is visible and plot the SDFs of that ray + first_alive_ray = torch.nonzero(alive_ray_mask)[0] + distances_from_origin = distances_from_origin[ray_indices == first_alive_ray] + sdf = sdf[ray_indices == first_alive_ray] + + distances_from_origin = 2 * distances_from_origin / exposure_time + plt.plot(distances_from_origin.cpu().detach().numpy(), sdf.cpu().detach().numpy(), label='SDFs') + plt.axvline(x=(depth[0]*2/exposure_time).detach().cpu().numpy(), color='r', linestyle='--', label='Predicted depth') + plt.legend() + plt.title("Predicted SDFs along the first ray") + + plt.savefig(self.get_save_path(filename)) + plt.close() + + + def save_sdf_normal_plot(self, filename, sdf, distances_from_origin, depth, ray_indices, alive_ray_mask): + ''' + Plot the sdfs plot as a function of the distances from the origin and depth + ''' + #Find the first ray that is visible and plot the SDFs of that ray + first_alive_ray = torch.nonzero(alive_ray_mask.squeeze())[0] + distances_from_origin = distances_from_origin[ray_indices == first_alive_ray] + sdf = sdf[ray_indices == first_alive_ray] + plt.plot(distances_from_origin.cpu().detach().numpy(), sdf.cpu().detach().numpy(), label='SDFs') + plt.axvline(x=(depth[0]).detach().cpu().numpy(), color='r', linestyle='--', label='Predicted depth') + plt.legend() + plt.title("Predicted SDFs along the first ray") + + plt.savefig(self.get_save_path(filename)) + plt.close() + + + + def save_image_n_dots(self, filename, image, points_x, points_y): + ''' + Plot the predicted image along with the three red dots on the image. + image: (H,W,3) + points_x: (3,1) + points_y: (3,1) + ''' + assert len(image.shape) == 3, "Image should be of shape (H,W,3)" + assert image.shape[:-1] == self.config.dataset.img_wh + plt.imshow(image) + plt.plot(points_x, points_y,'.', markersize=10, color='red') + plt.title("Image with 3 sampled dots") + plt.savefig(self.get_save_path(filename)) + plt.close() + + + def save_sdf_plots(self, filename, top_3, dists_from_origin, ray_indices, exposure_time, depth, sdf): + ''' + Given three red dots on the image, plot the SDFs of each point + point_x: (3,1) + point_y: (3,1) + sdfs: (n_samples, 1) + In the original script, they use point_y = plotting_subset_y + ''' + sdf_figure, sdf_axes = plt.subplots(1, len(top_3), figsize=(7.5, 10), dpi=250) + dists_from_origin = 2 * dists_from_origin / exposure_time + + for idx, ax in enumerate(sdf_axes): + #PLotting the SDFs + + sdf_min = sdf[ray_indices == top_3[idx]].min().item() + sdf_max = sdf[ray_indices == top_3[idx]].max().item() + + # If you want a buffer around the min and max, you can add it + buffer = (sdf_max - sdf_min) * 0.1 # 10% buffer for example + sdf_min -= buffer + sdf_max += buffer + ax.set_ylim([sdf_min, sdf_max]) + sdf_ticks = np.linspace(sdf_min, sdf_max, num=5) + + #append zero to the set of ticks + # if current_min <= 0 and current_max >= 0: + # # Include 0 in the ticks + # sdf_ticks = np.append(sdf_ticks, 0) + # # Sort the ticks since append doesn't maintain order + # sdf_ticks = np.sort(sdf_ticks) + + ax.set_yticks(sdf_ticks) + ax.yaxis.tick_right() + ax.scatter(dists_from_origin[ray_indices == top_3[idx]].detach().cpu().numpy(), sdf[ray_indices == top_3[idx]].detach().cpu().numpy(), alpha=0.5, color="blue", label='SDFs') + + # x = dists_from_origin[ray_indices == top_3[idx]].detach().cpu().numpy() + # y = sdf[ray_indices == top_3[idx]].detach().cpu().numpy() + + # # Perform linear regression + # slope, intercept, _,_,_ = stats.linregress(x, y) + + # # Generate points for the fitted line + # fitted_line = slope * x + intercept + + # Plot the fitted line + # ax.plot(x, fitted_line, color="red", label='Fitted SDF') + # ax.legend(loc='best') + + ax.axvline(x=(depth[top_3][idx] * 2 / exposure_time)[0].detach().cpu().numpy(), color='magenta', linestyle='--', linewidth=2, label='Depth Line') + shape_info = ray_indices[ray_indices == top_3[idx]].shape[0] + depth_info = (depth[top_3][idx] * 2 / exposure_time)[0].detach().cpu().numpy() + #Displaying the number of samples belonging to those sampled rays + ax.text(0.95, 0.95, f'Number of samples: {shape_info}', transform=ax.transAxes, fontsize=10, + verticalalignment='top', horizontalalignment='right', bbox=dict(boxstyle="round,pad=0.3", edgecolor='gray', facecolor='white', alpha=0.5)) + ax.text(0.95, 0.7, f'Depth: {depth_info:.2f}', transform=ax.transAxes, fontsize=10, + verticalalignment='top', horizontalalignment='right', bbox=dict(boxstyle="round,pad=0.3", edgecolor='gray', facecolor='white', alpha=0.5)) + ax.set_xlabel('Distance from the origin') + ax.set_ylabel('SDF values') + ax.set_title(f'Plot {idx+1}') + + sdf_figure.savefig(self.get_save_path(filename)) + plt.close(sdf_figure) + + def save_metrics(self, filename, metrics_dict): + ''' + Save the metrics in a nice table format. + Expects the metrics_dict to contain the names of all the metrics + ''' + table = PrettyTable() + table.field_names = ["Metric", "Value"] + for key in metrics_dict.keys(): + table.add_row([key, metrics_dict[key]]) + table.border = True + save_path = self.get_save_path(filename) + with open(save_path, 'w') as f: + f.write(str(table)) + + + def save_plot_grid(self, filename, point_x, point_y, transient, global_step, channel=0): + assert len(point_x) == len(point_y) + + n_points = len(point_x) + fig = plt.figure(figsize=(20, 5)) # Define a figure + + # Create a GridSpec layout + gs = GridSpec(1, n_points + 1, width_ratios=[3] + [1]*n_points) # First subplot 3 times wider + + integrated_transient = transient.sum(-2) # sums along the time dimension to get the integrated transient + integrated_transient = (integrated_transient / integrated_transient.max()) ** (1 / 2.2) # gamma correct it + integrated_transient = integrated_transient.float() + # Plot the integrated transient in a larger subplot + ax0 = fig.add_subplot(gs[0, 0]) + ax0.imshow(integrated_transient) + for i in range(n_points): + ax0.scatter(point_x[i], point_y[i], color="red") + ax0.set_title(f'Integrated transient at {global_step} steps') + + # Plot the transients for the selected points + for i in range(n_points): + ax = fig.add_subplot(gs[0, i+1]) # Create each subsequent subplot + selected_transient = transient[point_y[i], point_x[i], :, channel] #The convention for indexing is (y,x) whereas for plotting is (x,y) + argmax_index = np.argmax(selected_transient) + ax.plot(selected_transient) + ax.set_title(f'Plot {i+1} - {point_x[i], point_y[i]}') + ax.set_xlabel('Time') + ax.set_ylabel(f'Intensity for Channel {channel}') + + textstr = f'argmax: {argmax_index}' + # These are matplotlib.patch.Patch properties + props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) + # Place the text box in upper left in axes coords + ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=8.5, verticalalignment='top', bbox=props) + + plt.tight_layout() + plt.savefig(self.get_save_path(filename)) + plt.close(fig) + + + def save_weight_grid(self, filename, point_x, point_y, transient, weights, depth, exposure_time, distances_from_origin, ray_indices, t_ends, t_starts, global_step): + ''' + Plot the weight distribution of the selected points for each point (point_x, point_y) + ''' + height = transient.shape[0] + n_points = len(point_x) + fig = plt.figure(figsize=(20, 5)) + gs = GridSpec(1, n_points + 1, width_ratios=[3] + [1]*n_points) # First subplot 3 times wider + integrated_transient = transient.sum(-2) # sums along the time dimension to get the integrated transient + integrated_transient = (integrated_transient / integrated_transient.max()) ** (1 / 2.2) # gamma correct it + variance = ((t_ends - depth[ray_indices]) ** 2 + (t_ends - depth[ray_indices])*(t_starts - depth[ray_indices]) + (t_starts - depth[ray_indices]) ** 2)/3 + # Plot the integrated transient in a larger subplot + ax0 = fig.add_subplot(gs[0, 0]) + ax0.imshow(integrated_transient) + for i in range(n_points): + ax0.scatter(point_x[i], point_y[i], color="red") + ax0.set_title(f'Integrated transient at {global_step} steps') + + for i in range(n_points): + ax = fig.add_subplot(gs[0, i+1]) # Create each subsequent subplot + #Find the ray index for the selected point + linear_index = point_y[i] * height + point_x[i] + ray_index = torch.where(ray_indices == linear_index)[0] + + #Selecting the corresponding samples/ray + selected_weight = weights[ray_index] + selected_variance = torch.squeeze(variance[ray_index]) + selected_distances = distances_from_origin[ray_index]*2/exposure_time + selected_depth = depth[linear_index] + depth_variance = (selected_weight*selected_variance).mean() #Calculate the depth variance for one ray + + ax.plot(selected_distances, selected_weight) + ax.text(0.05, 0.95, f'Depth Variance: {depth_variance.item():.5f}', transform=ax.transAxes, fontsize=8.5, verticalalignment='top', bbox=dict(boxstyle="round,pad=0.3", edgecolor='gray', facecolor='white', alpha=0.5)) + plt.axvline(x=(selected_depth*2/exposure_time).item(), color='r', linestyle='--', label='Predicted depth') + ax.set_title(f'Plot {i+1} - {point_x[i], point_y[i]}') + ax.set_xlabel('Dists') + ax.set_ylabel('Weights') + plt.tight_layout() + plt.savefig(self.get_save_path(filename)) + plt.close(fig) + + def save_weight_plot(self, filename, weights, exposure_time, distances_from_origin, depth, ray_indices, alive_ray_mask=None, depth_variance=None): + ''' + Plot the weights plot as a function of the distances from the origin and depth + ''' + #Find the first ray that is visible and plot the SDFs of that ray + if isinstance(alive_ray_mask, torch.Tensor): + first_alive_ray = torch.nonzero(alive_ray_mask)[0] + else: + first_alive_ray = 0 + distances_from_origin = distances_from_origin[ray_indices == first_alive_ray] + weights = weights[ray_indices == first_alive_ray] + distances_from_origin = 2 * distances_from_origin / exposure_time + + plt.plot(distances_from_origin.cpu().detach().numpy(), weights.cpu().detach().numpy(), label='Weights') + if isinstance(depth_variance, torch.Tensor): + x_pos = distances_from_origin.mean().cpu().detach().numpy() + y_pos = weights.max().cpu().detach().numpy() * 0.5 # Placing text at 50% of max weight for visibility + plt.text(x_pos, y_pos, f'Variance: {depth_variance[first_alive_ray].item():.2f}') + + plt.axvline(x=(depth[first_alive_ray]*2/exposure_time).detach().cpu().numpy(), color='r', linestyle='--', label='Predicted depth') + plt.legend() + plt.title("Predicted weights along the first ray") + + plt.savefig(self.get_save_path(filename)) + plt.close() + + + + def save_transient_figures(self, filename, gt_transients, predicted_transients, number_of_transients=20): + ''' + Plot a figure of all gt_transients and predicted_transients (assuming that they are already masked for the visible rays) + Take the first color channel. + ''' + mask = gt_transients.abs().sum(dim=(1, 2)) > 1e-5 + mask = torch.ones(mask.shape, dtype=torch.bool) + non_zero_gt_transients = gt_transients[mask] + non_zero_pred_transients = predicted_transients[mask] + + num_rows = (number_of_transients + 1) // 2 # Ensure there's enough rows + + plt.figure(figsize=(15,20)) + number_of_plots = min(number_of_transients, len(non_zero_gt_transients)) + for i in range(number_of_plots): + plt.subplot(num_rows,2,i+1) + plt.plot(non_zero_gt_transients[i,:,0].cpu().detach().numpy(), label='Non-zero Ground truth transient') + plt.plot(non_zero_pred_transients[i,:,0].cpu().detach().numpy(), label='Non-zero Predicted transient') + plt.title(f"Transients for the {i+1}th ray") + plt.legend() + + plt.tight_layout() + plt.savefig(self.get_save_path(filename)) + plt.close() + + + + + def save_color_figures(self, filename, gt_transients, predicted_transients, number_of_transients=20): + ''' + Plot a figure of all gt vs predicted integrated transients (assuming that they are already masked for the visible rays) + ''' + #First need to normalize + gamma correct + gt_transients = gt_transients.sum(-2) + gt_transients = gt_transients / gt_transients.max() + gt_transients = gt_transients ** (1/2.2) + + predicted_transients = predicted_transients.sum(-2) + predicted_transients = predicted_transients / predicted_transients.max() + predicted_transients = predicted_transients ** (1/2.2) + + + # Create a figure with enough subplots in a single column + fig, ax = plt.subplots(figsize=(4, 20)) # Adjust the size as needed + + for i in range(20): + gt_transients_pixel = patches.Rectangle((0, i * 1.05), 1, 1, linewidth=1, edgecolor='none', facecolor=gt_transients[i].numpy()) + ax.add_patch(gt_transients_pixel) + + predicted_transients_pixel = patches.Rectangle((1.05, i * 1.05), 1, 1, linewidth=1, edgecolor='none', facecolor=predicted_transients[i].numpy()) + ax.add_patch(predicted_transients_pixel) + + ax.text(0.5, -0.5, 'gt_color', va='center', ha='center') + ax.text(1.55, -0.5, 'predicted_color', va='center', ha='center') + + # Set plot limits and aspect + ax.set_xlim(0, 2.1) + ax.set_ylim(0, 21) + ax.set_aspect('auto') # Auto aspect to fit the layout + plt.axis('off') # Hide the axes + + # Show the plot + plt.savefig(self.get_save_path(filename)) + plt.close() \ No newline at end of file diff --git a/codes/reconstruction/transientangelo/utils/obj.py b/codes/reconstruction/transientangelo/utils/obj.py new file mode 100644 index 0000000000000000000000000000000000000000..da6d11938c244a6b982ec8c3f36a90a7a5fd2831 --- /dev/null +++ b/codes/reconstruction/transientangelo/utils/obj.py @@ -0,0 +1,74 @@ +import numpy as np + + +def load_obj(filename): + # Read entire file + with open(filename, 'r') as f: + lines = f.readlines() + + # load vertices + vertices, texcoords = [], [] + for line in lines: + if len(line.split()) == 0: + continue + + prefix = line.split()[0].lower() + if prefix == 'v': + vertices.append([float(v) for v in line.split()[1:]]) + elif prefix == 'vt': + val = [float(v) for v in line.split()[1:]] + texcoords.append([val[0], 1.0 - val[1]]) + + uv = len(texcoords) > 0 + faces, tfaces = [], [] + for line in lines: + if len(line.split()) == 0: + continue + prefix = line.split()[0].lower() + if prefix == 'usemtl': # Track used materials + pass + elif prefix == 'f': # Parse face + vs = line.split()[1:] + nv = len(vs) + vv = vs[0].split('/') + v0 = int(vv[0]) - 1 + if uv: + t0 = int(vv[1]) - 1 if vv[1] != "" else -1 + for i in range(nv - 2): # Triangulate polygons + vv1 = vs[i + 1].split('/') + v1 = int(vv1[0]) - 1 + vv2 = vs[i + 2].split('/') + v2 = int(vv2[0]) - 1 + faces.append([v0, v1, v2]) + if uv: + t1 = int(vv1[1]) - 1 if vv1[1] != "" else -1 + t2 = int(vv2[1]) - 1 if vv2[1] != "" else -1 + tfaces.append([t0, t1, t2]) + vertices = np.array(vertices, dtype=np.float32) + faces = np.array(faces, dtype=np.int64) + if uv: + assert len(tfaces) == len(faces) + texcoords = np.array(texcoords, dtype=np.float32) + tfaces = np.array(tfaces, dtype=np.int64) + else: + texcoords, tfaces = None, None + + return vertices, faces, texcoords, tfaces + + +def write_obj(filename, v_pos, t_pos_idx, v_tex, t_tex_idx): + with open(filename, "w") as f: + for v in v_pos: + f.write('v {} {} {} \n'.format(v[0], v[1], v[2])) + + if v_tex is not None: + assert(len(t_pos_idx) == len(t_tex_idx)) + for v in v_tex: + f.write('vt {} {} \n'.format(v[0], 1.0 - v[1])) + + # Write faces + for i in range(len(t_pos_idx)): + f.write("f ") + for j in range(3): + f.write(' %s/%s' % (str(t_pos_idx[i][j]+1), '' if v_tex is None else str(t_tex_idx[i][j]+1))) + f.write("\n") diff --git a/codes/reconstruction/trnerf/.gitignore b/codes/reconstruction/trnerf/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6107427c6ea2f841b6eb0ac6c8b4886c2ba04a85 --- /dev/null +++ b/codes/reconstruction/trnerf/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.pyc +results/ +exp/ +runs/ +*.pth +*.ckpt diff --git a/codes/reconstruction/trnerf/README.md b/codes/reconstruction/trnerf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5b10a072e8275feff0492636f726673535c8bb9c --- /dev/null +++ b/codes/reconstruction/trnerf/README.md @@ -0,0 +1,72 @@ +# trnerf 最小复现版 + +保留原生训练、模型与采样代码;共同指标集中在 `evaluation/`,唯一评价入口为 `eval.py`。 + +在项目根目录执行;服务器模型解释器为 `/work/runrong/.conda/envs/transientnerf/bin/python`: + +```bash +export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python +python train_ours.py -c configs/train.ini +python eval.py render --config configs/eval.ini \ + --checkpoint_dir /absolute/checkpoint_directory --step 300000 \ + --output /absolute/new_result_directory +``` + +历史权重没有训练归一化记录时,加 `--shared-prediction-scale` 并填写已核实的实际训练常数。 + +示例为 design_floor1 / 10 视角;参数模板来自原 designbuilding1 配置,不代表论文完整历史配置。其他场景、3/5 视角需要修改数据和训练位姿路径及对应模型参数,保持 canonical 测试位姿。训练方法、损失不因本次评价整理而改变。 + +## 共同评价协议(V4) + +`eval.py` 是唯一公开评价入口,`render` 和 `saved` 最终均调用 `evaluation/evaluator.py`。`evaluation/renderer.py` 仅适配本方法的模型和射线采样;直方图和图像指标实现与其他两个项目相同。原来的两个 `shared_*` 包、`evaluate_metrics_shared.py`、FWP 的 `eval_ours.py` 和独立旧评分分支已移除。 + +### 强度尺度与直方图 PSNR + +评分前逐 bin 恢复全曝光光子计数: + +``` +trnerf / transientangelo: prediction_counts = prediction_encoded * actual_training_scale +FlyingWithPhotons: prediction_counts = prediction_encoded ** training_gamma * dataset_scale +reference_counts: 共同参考缓存中的已标定、未独立归一化的光子计数 +MSE = mean((prediction_counts - reference_counts)^2) # 共同有效像素的全部 bins / channels +histogram_psnr = 20*log10(P_scene) - 10*log10(MSE) +``` + +`P_scene` 固定于同一场景的十视角训练候选池,在三种方法及 3/5/10 视角配置之间共用。预测峰值、测试最大值和每视角拟合系数都不用于确定它。预测直方图不做上限裁剪、显示 gamma 或曝光拟合;FWP 的逆训练 gamma 在积分前逐 bin 执行。缺失实际训练尺度时直接报错,禁止用测试集最大值代替。TN/FWP 新训练会记录 `image_metric_normalization.json`;TA 将训练尺度写入 checkpoint。历史权重须提供经过核实的训练常数,代码不能从测试集推断它。 + +共同参考由校准后全计数 GT 生成;掩码为硬件有效像素、GT 峰值 ≥100、正信号的交集,独立于预测。直方图峰值 `P_scene` 与积分图像尺度 `D_scene` 是两个不同的固定量。显示图像 PSNR、SSIM、LPIPS 沿用整理前 V4 所采用的显示变换,另报无显示 gamma 的 `linear_psnr`。这些图像分数不应标成直方图 PSNR。SSIM 使用完整有效 7×7 窗口;LPIPS 使用统一环境的 VGG v0.1 / FP32。 + +### 对 Q6–Q8 的代码说明 + +- **Q6:不是未经修改的发布版 eval.py。** 当前只提供统一 V4;取消旧 `scale_int` 和动态预测/GT 峰值评分。GT、掩码、固定场景尺度来自同一份 contract。原生测试均执行 30 次前向:TN 每次重新获取带抖动射线,TA 复用同一抖动批次,FWP 复用像素射线。因此不能把三者概括为“30 次独立像素抖动”。这些方法自身的采样逻辑保留。 +- **Q7:内部归一化不直接作为比较尺度。** TN/TA 预测乘回实际训练常数;FWP 逐 bin 逆训练 gamma 并乘回训练 dataset_scale;共同 GT 直接使用计数。测试加载器内部即使独立归一化,也不会把它的归一化 GT 或最大值用于评分。这解决当前流程中由训练/测试独立归一化引入的比较尺度不一致。 +- **Q8:三种视角设置均使用共同的 canonical test.json 帧及原始位姿。** 九场景合计 158 帧,逐场景 contract 强制核对完整唯一帧集合及位姿,拒绝只评部分帧或同名不同位姿。低视角下剩余训练候选帧不额外加入测试;十视角候选池仍用于冻结共同评价尺度,属于评价标定数据,不作为低视角方法的额外训练输入。 + +以上描述的是修订后的代码协议,不能用来证明历史论文分数已经重算。此次目录整理没有重新训练模型,也没有完成九场景全量模型评测。 + +### 输出、环境与迁移 + +输出为 `prediction_manifest.json` 和 `unified_metrics/` 下的协议记录、逐视角指标、完整集合汇总及浮点评分数组。记录含训练尺度、gamma、共同参考/掩码校验和、评分代码哈希和解释器路径。可加 `--save-predictions` 保存未裁剪编码直方图以便复算;不保存旧口径指标和旧图表。已有结果目录禁止覆盖。 + +三个项目必须使用同一个图像评价环境。服务器运行前设置: + +```bash +export STB_METRICS_PYTHON=/work/runrong/.conda/envs/transientangelo/bin/python +``` + +迁移机器后将它改为共同评价环境的 Python 绝对路径。数据、标定、权重、共同参考缓存不复制进代码包;README 中的示例配置仍指向服务器的实际路径,发布数据时需同时提供对应 contract/GT 缓存并改为新路径。每种方法使用同一场景的同一份 contract。保存目录名中的旧日期仅是外部参考数据的位置,不再是代码导入依赖。 + +评分已有预测统一使用 `python eval.py saved --help` 查看参数,例如: + +```bash +python eval.py saved --prediction-dir /absolute/predictions \ + --prediction-manifest /absolute/predictions/prediction_manifest.json \ + --prediction-scale ACTUAL_TRAINING_SCALE --prediction-gamma 1 \ + --prediction-bin-width-s 7.5e-10 \ + --shared-reference-contract /absolute/reference/contract.json \ + --output /absolute/new_scores --device cpu +``` + +FWP 编码输出填写真实训练 gamma;已经恢复完整计数的导出填写 scale=1、gamma=1。有单位记录的 manifest 与命令参数冲突时会报错。 + +`requirements.txt` 保留各模型依赖。先安装匹配 CUDA 11.8 的 PyTorch 2.5.1 / torchvision 0.20.1,再安装其余依赖和 CUDA 扩展;模型环境可以不同,图像评价子进程保持一致。训练日志中的训练集损失/PSNR 仅用于优化诊断,不是测试集 benchmark 分数。 diff --git a/codes/reconstruction/trnerf/__pycache__/train_ours.cpython-312.pyc b/codes/reconstruction/trnerf/__pycache__/train_ours.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..619c4a54f0e072b697707d2876744390732c310c Binary files /dev/null and b/codes/reconstruction/trnerf/__pycache__/train_ours.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/__pycache__/utils.cpython-312.pyc b/codes/reconstruction/trnerf/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b53686b68d83664de1dc10bb9fd759468c137673 Binary files /dev/null and b/codes/reconstruction/trnerf/__pycache__/utils.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/configs/eval.ini b/codes/reconstruction/trnerf/configs/eval.ini new file mode 100644 index 0000000000000000000000000000000000000000..ae72b53cebc40842602ece14a84d76cdbcda66e3 --- /dev/null +++ b/codes/reconstruction/trnerf/configs/eval.ini @@ -0,0 +1,50 @@ +# STB design_floor1 / 10 views example. See README for configuration origin. +exp_name = "design_floor1_10views" +test_chunk_size = 256 +num_rays_per_batch = 512 +starting_rays_per_pixel = 1 +tfilter_sigma = 3 +rfilter_sigma = 0.15 +space_carving = 0.0 +lr = 0.0001 +num_views = 10 +n_bins = 672 +aabb = "[-30.723363, -32.531209, -1.819858, 30.377352, 12.024207, 9.260004]" +version = captured +data_root_fp = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views" +measurement_root = "/work/runrong/dataset/paper_data/design_floor1" +data_exts = ".npz,.txt,.pt,.h5,.hdf5" +irf_path = "/work/runrong/dataset/paper1_data/raw/new_IRF_global.csv" +irf_column = "irf" +irf_half_window = 50 +intrinsics = "/work/runrong/dataset/intrinsics.npy" +invalid_mask_path = "/work/runrong/dataset/paper1_data/offset.txt" +invalid_mask_invalid_gt = 10.0 +exposure_time = 0.2248443435 +bin_width_s_loader = 7.5e-10 +thold_warmup = 80000 +max_steps = 300001 +img_height_test = 192 +img_width_test = 256 +img_shape = 256 +img_shape_test = 256 +near_plane = 0.100000 +far_plane = 28.000000 +alpha_thre = 0 +occ_thre = 0.0000001 +sample_as_per_distribution = False +render_n_samples = 1024 +exp = True +final = True +steps_til_checkpoint = 10000 +grid_resolution = 128 +grid_nlvl = 1 +outpath = "./results" +pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"] +img_scale = 100 +seed = 42 +device = cuda:0 +test_folder_path = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views" +split = test +rep_number = 30 +shared_reference_contract = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/contract.json" diff --git a/codes/reconstruction/trnerf/configs/train.ini b/codes/reconstruction/trnerf/configs/train.ini new file mode 100644 index 0000000000000000000000000000000000000000..49598e1c0bb1618a92e8eb005727732ec880c72f --- /dev/null +++ b/codes/reconstruction/trnerf/configs/train.ini @@ -0,0 +1,48 @@ +# STB design_floor1 / 10 views example. See README for configuration origin. +exp_name = "design_floor1_10views" +test_chunk_size = 256 +num_rays_per_batch = 512 +starting_rays_per_pixel = 1 +tfilter_sigma = 3 +rfilter_sigma = 0.15 +space_carving = 0.0 +lr = 0.0001 +num_views = 10 +n_bins = 672 +aabb = "[-30.723363, -32.531209, -1.819858, 30.377352, 12.024207, 9.260004]" +version = captured +data_root_fp = "/work/runrong/project_all/shared_transient_metrics_20261016/references/design_floor1/poses/ten_views" +measurement_root = "/work/runrong/dataset/paper_data/design_floor1" +data_exts = ".npz,.txt,.pt,.h5,.hdf5" +irf_path = "/work/runrong/dataset/paper1_data/raw/new_IRF_global.csv" +irf_column = "irf" +irf_half_window = 50 +intrinsics = "/work/runrong/dataset/intrinsics.npy" +invalid_mask_path = "/work/runrong/dataset/paper1_data/offset.txt" +invalid_mask_invalid_gt = 10.0 +exposure_time = 0.2248443435 +bin_width_s_loader = 7.5e-10 +thold_warmup = 80000 +max_steps = 300001 +img_height = 192 +img_width = 256 +img_height_test = 192 +img_width_test = 256 +img_shape = 256 +img_shape_test = 256 +near_plane = 0.100000 +far_plane = 28.000000 +alpha_thre = 0 +occ_thre = 0.0000001 +sample_as_per_distribution = False +render_n_samples = 1024 +exp = True +final = True +steps_til_checkpoint = 10000 +grid_resolution = 128 +grid_nlvl = 1 +outpath = "./results" +pixels_to_plot = ["(40, 60)", "(60, 100)", "(80, 60)"] +img_scale = 100 +seed = 42 +device = cuda:0 diff --git a/codes/reconstruction/trnerf/eval.py b/codes/reconstruction/trnerf/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..156428c137ff4a40e071acd2dbb76990a15b8cca --- /dev/null +++ b/codes/reconstruction/trnerf/eval.py @@ -0,0 +1,5 @@ +"""The only public evaluation entry: render predictions or score saved histograms.""" +from evaluation.cli import main + +if __name__ == "__main__": + main() diff --git a/codes/reconstruction/trnerf/evaluation/__init__.py b/codes/reconstruction/trnerf/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4587915b0d7bc01640496b06530c1fa02f2321b0 --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/__init__.py @@ -0,0 +1,4 @@ +"""Common count-domain transient evaluation, independent of model training units.""" +PROTOCOL = 'shared_transient_counts_v4_20261016' +TRANSIENT_KEYS = ('histogram_psnr', 'histogram_mse_counts', 'histogram_mae_counts', + 'depth_l1_m', 'transient_iou') diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f28281e1c047615a1d8327a77c81d39eb1d4dcb Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/arguments.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c77ea0cfd6ce0d7413d3386a274b234fdcf16eb Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/arguments.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/cli.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae842e5c337bea1a773e11d79c2f4259dbe9b682 Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/cli.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/core.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60fd7268525f440e1d3d03e6da4f21e4e02af8f9 Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/core.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/evaluator.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73046df2ef8e2080b518d09a6d316b44747903ba Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/evaluator.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/image_metrics.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/image_metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a090b7717a8a1d2127c810b1cce513779e81680f Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/image_metrics.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/io.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d82282df2e79583f19e62ebb623cfc35cc0d7b9d Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/io.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/renderer.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/renderer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57be859b9310b07cbb21a25fa3eb22538abd65a4 Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/renderer.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/units.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/units.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd800674a3ea821377de5e72aef3b0e5cfde14fb Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/units.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/__pycache__/worker.cpython-312.pyc b/codes/reconstruction/trnerf/evaluation/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b654311761c2e077badcc435273aadfcbfcaf79a Binary files /dev/null and b/codes/reconstruction/trnerf/evaluation/__pycache__/worker.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/evaluation/arguments.py b/codes/reconstruction/trnerf/evaluation/arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..a658cce1e3ccfeb121584aa6fe5bab855103fdb3 --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/arguments.py @@ -0,0 +1,133 @@ +"""Model rendering options; all scoring options are fixed by the reference contract.""" +import ast +import configargparse +from utils import str2bool, load_args + +def load_eval_args(): + parser = configargparse.ArgumentParser() + parser.add('--config', '-tc', '--test_config', dest='test_config', + is_config_file=True, + default=None, + help='Path to config file.' + ) + parser.add_argument( + "--scene", + type=str, + default="cinema", + # choices=[ + # # nerf transient + # "lego", + # "chair", + # "drums", + # "ficus", + # "hotdog", + # "bench", + # "boar", + # "benches" + # ], + help="scene to evaluate the models on", + ) + parser.add_argument( + "--rep_number", + type=int, + default=30, + ) + parser.add_argument( + "--step", + type=int, + default=290000, + ) + parser.add_argument( + "--split", + type=str, + default="test", + ) + parser.add_argument( + "--test_folder_path", + type=str, + default="test2", + ) + parser.add_argument( + "--checkpoint_dir", + type=str, + default="/scratch/ondemand28/anagh/tnerf_release/multiview_transient/results/cinema_two_views_04-18_02:10:32", + ) + parser.add_argument( + "--data_folder_path", + type=str, + default="./data", + ) + parser.add_argument( + "--irf_path", + type=str, + default="", + help="Path to IRF file (.csv/.npy/.mat/.pt). If empty, fallback to --pulse_path.", + ) + parser.add_argument( + "--irf_column", + type=str, + default="irf", + help="CSV column name for IRF values.", + ) + parser.add_argument( + "--irf_half_window", + type=int, + default=50, + help="Half window around IRF peak. Set <=0 to disable cropping.", + ) + parser.add_argument( + "--no_irf_reverse", + action="store_true", + help="Disable reverse before Conv1d kernel creation.", + ) + parser.add_argument( + "--measurement_root", + type=str, + default="", + help="Optional measurement root for captured-ours loader.", + ) + parser.add_argument( + "--data_exts", + type=str, + default=".npz,.txt,.pt,.h5,.hdf5", + help="Comma-separated measurement extension lookup order.", + ) + parser.add_argument( + "--bin_width_s_loader", + type=float, + default=None, + help="Optional bin width in seconds for shift resampling.", + ) + parser.add_argument( + "--img_height_test", + type=int, + default=None, + help="Test image height. If empty, use --img_shape_test.", + ) + parser.add_argument( + "--img_width_test", + type=int, + default=None, + help="Test image width. If empty, use --img_shape_test.", + ) + parser.add_argument( + "--invalid_mask_path", + type=str, + default="", + help="Optional offset map path for valid-pixel mask.", + ) + parser.add_argument( + "--invalid_mask_invalid_gt", + type=float, + default=10.0, + help="Offset threshold: pixels with offset > threshold are invalid.", + ) + parser.add_argument("--shared-reference-contract", "--shared_reference_contract", default=None, + help="Verified reference contract matching this scene and split.") + parser.add_argument("--shared-prediction-scale", "--shared_prediction_scale", type=float, default=None, + help="TRAINING histogram normalization to restore predicted photon counts.") + parser.add_argument("--output", "--shared-output-dir", "--shared_output_dir", dest="shared_output_dir", default=None, + help="Fresh output directory for unified V4 metrics.") + parser.add_argument("--save-predictions", action="store_true", help="Save unmodified encoded histograms for re-scoring") + args = load_args(eval=True, parser=parser) + return args diff --git a/codes/reconstruction/trnerf/evaluation/cli.py b/codes/reconstruction/trnerf/evaluation/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..75f1ced0c673a449a2511fb744c102c7384cdaab --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/cli.py @@ -0,0 +1,54 @@ +"""One entry point and one protocol, for all three methods.""" +import argparse +import json +import sys +from pathlib import Path + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', choices=('render', 'saved'), + help='render a checkpoint, or score unmodified saved histograms') + if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'): + parser.print_help() + return + mode = parser.parse_args(sys.argv[1:2]).source + sys.argv = [sys.argv[0]] + sys.argv[2:] + from . import renderer + if mode == 'render': + return renderer.main() + from .evaluator import EvaluationRun + from .io import load_histogram, write_json, sha256 + p = argparse.ArgumentParser(description='Score saved histograms with the same V4 evaluator as render.') + p.add_argument('--prediction-dir', required=True) + p.add_argument('--prediction-pattern', default='{view}_transient_array.npy') + p.add_argument('--prediction-scale', type=float, required=True, + help='ACTUAL TRAINING normalization; 1 only for full-count exports') + p.add_argument('--prediction-gamma', type=float, default=1.) + p.add_argument('--prediction-bin-width-s', type=float, required=True) + p.add_argument('--prediction-manifest', required=True, + help='Actual rendered frames and poses, in prediction-file order') + p.add_argument('--shared-reference-contract', required=True) + p.add_argument('--output', required=True) + p.add_argument('--device', default='cpu') + a = p.parse_args() + a.bin_width_s_loader = a.prediction_bin_width_s + a.n_bins = json.loads(Path(a.shared_reference_contract).read_text())['n_bins'] + manifest = json.loads(Path(a.prediction_manifest).read_text()) + if (Path(a.output)/'prediction_manifest.json').resolve() == Path(a.prediction_manifest).resolve(): + raise ValueError('Use a separate output directory to preserve the source manifest') + # Generated manifests are binding; do not silently override their physical units. + for key, actual in [('prediction_scale', a.prediction_scale), + ('prediction_gamma', a.prediction_gamma), + ('bin_width_s', a.prediction_bin_width_s)]: + if key in manifest and float(manifest[key]) != actual: + raise ValueError('Prediction manifest disagrees with '+key) + frames = manifest['frames'] + run = EvaluationRun(renderer.PROJECT, a, a.output, frames, a.prediction_scale, + a.prediction_gamma, rendering=manifest.get('rendering')) + run.evaluator.metadata.update(prediction_manifest=str(Path(a.prediction_manifest).resolve()), + prediction_manifest_sha256=sha256(a.prediction_manifest)) + write_json(run.evaluator.output/'evaluation_protocol.json', run.evaluator.metadata) + for i, frame in enumerate(frames): + path = Path(a.prediction_dir)/a.prediction_pattern.format(view=i, stem=Path(frame['file_path']).stem) + run.score(load_histogram(path), i) + print(run.finish()) diff --git a/codes/reconstruction/trnerf/evaluation/core.py b/codes/reconstruction/trnerf/evaluation/core.py new file mode 100644 index 0000000000000000000000000000000000000000..27d91f197d2e6648591d1ad87e1ff28c6d8e4b8e --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/core.py @@ -0,0 +1,81 @@ +"""Pure NumPy scoring. No data-dependent exposure fitting or upper clipping.""" +import numpy as np + +C = 299792458.0 + +def positive(x, name): + x = float(x) + if not np.isfinite(x) or x <= 0: + raise ValueError(name + ' must be finite and positive') + return x + +def histogram(x): + if hasattr(x, 'detach'): + x = x.detach().cpu().numpy() + x = np.asarray(x) + if x.ndim == 3: + x = x[..., None] + if x.ndim != 4 or x.shape[-1] not in (1, 3) or min(x.shape) <= 0: + raise ValueError('Expected H x W x T x (1 or 3) histogram') + return x + +def decode(x, scale, gamma=1.0): + """Inverse training encoding, applied per bin before any summation.""" + scale, gamma = positive(scale, 'training scale'), positive(gamma, 'gamma') + x = np.asarray(x, dtype=np.float64) + if not np.isfinite(x).all() or np.any(x < 0): + raise ValueError('Histogram must be finite and nonnegative, even outside the mask') + y = np.power(x, gamma) * scale if gamma != 1.0 else x * scale + if not np.isfinite(y).all(): + raise ValueError('Count decoding overflow') + return y + +def score_histograms(prediction, reference, mask, *, prediction_scale, + reference_scale, histogram_peak, bin_width_s, + prediction_gamma=1.0, row_chunk=4): + """MSE over all bins/channels of GT-valid pixels, using a frozen train peak. + + A one-channel capture is broadcast to RGB when necessary. All RGB channels + enter MSE; peak depth uses their arithmetic mean. Chunking bounds RAM use. + """ + pred, ref = histogram(prediction), histogram(reference) + if pred.shape[:3] != ref.shape[:3]: + raise ValueError('Prediction/reference pixel grid or temporal window differs') + mask = np.asarray(mask) + if mask.shape != pred.shape[:2] or not np.isin(mask, [0, 1]).all(): + raise ValueError('Expected binary HW reference-only mask') + mask = mask.astype(bool) + if not mask.any(): + raise ValueError('No valid reference pixels') + peak = positive(histogram_peak, 'fixed histogram peak') + dt = positive(bin_width_s, 'physical bin width') + if int(row_chunk) != row_chunk or row_chunk < 1: + raise ValueError('row_chunk must be a positive integer') + h, w, t = pred.shape[:3] + channels = max(pred.shape[-1], ref.shape[-1]) + ip, ig = np.zeros((h,w,3)), np.zeros((h,w,3)) + dp, dg = np.zeros((h,w)), np.zeros((h,w)) + squared = absolute = intersection = union = 0.0 + for start in range(0,h,int(row_chunk)): + sl = slice(start,min(h,start+int(row_chunk))) + p = decode(pred[sl], prediction_scale, prediction_gamma) + g = decode(ref[sl], reference_scale) + ip[sl] = np.broadcast_to(p.sum(axis=-2), (len(p),w,3)) + ig[sl] = np.broadcast_to(g.sum(axis=-2), (len(g),w,3)) + dp[sl] = p.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0 + dg[sl] = g.mean(axis=-1).argmax(axis=-1) * C * dt / 2.0 + a,b = np.broadcast_arrays(p[mask[sl]], g[mask[sl]]) + error = a-b + squared += np.square(error).sum(dtype=np.float64) + absolute += np.abs(error).sum(dtype=np.float64) + intersection += np.minimum(a,b).sum(dtype=np.float64) + union += np.maximum(a,b).sum(dtype=np.float64) + count = int(mask.sum()) * t * channels + mse = squared/count + psnr = float(20*np.log10(peak)-10*np.log10(mse)) if mse>0 else float('inf') + scores = dict(histogram_psnr=psnr, histogram_mse_counts=float(mse), + histogram_mae_counts=float(absolute/count), + depth_l1_m=float(np.abs(dp[mask]-dg[mask]).mean()), + transient_iou=float(intersection/union) if union>0 else 1.0) + return scores, dict(prediction=ip, reference=ig, mask=mask, + prediction_depth=dp, reference_depth=dg) diff --git a/codes/reconstruction/trnerf/evaluation/evaluator.py b/codes/reconstruction/trnerf/evaluation/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..ed102f188ebd8079a33eeca554a87db7a6ce9278 --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/evaluator.py @@ -0,0 +1,161 @@ +"""Frame-bound common scoring adapter for all three native and saved entrances.""" +import json +import operator +import os +from pathlib import Path +import subprocess +import sys +import numpy as np +from . import PROTOCOL +from .core import C,positive,score_histograms +from .io import sha256,verified,load_histogram,write_json + +BASE=Path(__file__).resolve().parent.parent +PYTHON=os.environ.get('STB_METRICS_PYTHON') or '/work/runrong/.conda/envs/transientangelo/bin/python' + +def resolve_contract(args): + explicit=getattr(args,'shared_reference_contract',None) or os.environ.get('SHARED_REFERENCE_CONTRACT') + if explicit:return Path(explicit).resolve() + measurement=getattr(args,'measurement_root',None) + matches=[] + for p in Path(os.environ.get('STB_REFERENCE_ROOT', str(BASE/'references'))).glob('*/contract.json'): + d=json.loads(p.read_text()) + if measurement and Path(d['measurement_root']).resolve()==Path(measurement).resolve():matches.append(p) + if len(matches)!=1: + raise ValueError('A prepared V4 canonical reference is required. Pass --shared-reference-contract ' + 'with the matching contract.json; no legacy/test-scale fallback.') + return matches[0] + +class UnifiedEvaluator: + def __init__(self,project,args,output_dir,frames): + if project not in ('trnerf','transientangelo','FlyingWithPhotons'):raise ValueError('Unknown project') + if not Path(PYTHON).is_file():raise FileNotFoundError('Set STB_METRICS_PYTHON to the common evaluation Python: '+str(PYTHON)) + self.project=project;self.path=resolve_contract(args);self.digest=sha256(self.path) + self.contract=c=json.loads(self.path.read_text()) + if c.get('protocol')!=PROTOCOL: + raise ValueError('V4 needs a histogram reference contract, not an intensity-only V2/V3 contract') + self.peak=positive(c['histogram_peak'],'fixed training histogram peak') + self.display_scale=positive(c['display_scale'],'fixed training display scale') + dt=positive(c['bin_width_s'],'reference bin width') + if not c.get('training_frames') or not c.get('scale_policy') or c.get('time_start')!=0: + raise ValueError('Missing frozen training-scale provenance or invalid time origin') + for k in ('height','width','n_bins'): + if type(c[k]) is not int or c[k]<=0:raise ValueError('Invalid '+k) + measurement=getattr(args,'measurement_root',None) + if measurement and Path(measurement).resolve()!=Path(c['measurement_root']).resolve(): + raise ValueError('Measurement scene does not match reference') + intrinsics=getattr(args,'intrinsics',None) or getattr(args,'intrinsics_path',None) + if intrinsics and sha256(intrinsics)!=c['intrinsics_sha256']:raise ValueError('Calibration mismatch') + actual=getattr(args,'bin_width_s_loader',None) + if actual is None:actual=getattr(args,'bin_width_s',None) + if actual is None and hasattr(args,'exposure_time'): + actual=float(args.exposure_time)/(C/2 if project=='FlyingWithPhotons' else C) + if actual is None or not np.isclose(float(actual),dt,rtol=1e-6,atol=0):raise ValueError('Physical bin width mismatch/missing') + # FWP uses one-way range/bin; verify it even when a loader override exists. + if project=='FlyingWithPhotons' and hasattr(args,'exposure_time'): + if not np.isclose(float(args.exposure_time)/(C/2),dt,rtol=1e-6,atol=0):raise ValueError('FWP exposure_time mismatch') + for name,want in [('n_bins',c['n_bins']),('t_min_test',0),('t_max_test',c['n_bins']), + ('img_height_test',c['height']),('img_width_test',c['width'])]: + actual=getattr(args,name,None) + if actual is not None and int(actual)!=want:raise ValueError('Common window/grid mismatch: '+name) + frames=list(frames);records={Path(f['file_path']).stem:f for f in c['frames']} + ids=[Path(f['file_path']).stem for f in frames] + if (not frames or len(records)!=len(c['frames']) or len(set(ids))!=len(ids) + or set(ids)!=set(records)): + raise ValueError('Evaluation must declare the complete, unique canonical test frame set') + self.frames=[] + for f,key in zip(frames,ids): + r=records[key];pose=np.asarray(f['transform_matrix']);rp=np.asarray(r['transform_matrix']) + 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): + raise ValueError('Test frame pose differs from canonical reference: '+key) + self.frames.append(r) + self.output=Path(output_dir)/'unified_metrics' + if (self.output/'evaluation_protocol.json').exists(): + raise FileExistsError('Use a fresh V4 output directory; existing scores are not overwritten') + self.output.mkdir(parents=True,exist_ok=True);self.rows=[] + self.device=os.environ.get('STB_METRICS_DEVICE') or str(getattr(args,'device','cpu')) + self.metadata=dict(protocol=PROTOCOL,project=project,reference_contract=str(self.path), + reference_sha256=self.digest,scene_id=c['scene_id'],histogram_peak=self.peak, + display_scale=self.display_scale,mask_policy=c['mask_policy'],n_bins=c['n_bins'],bin_width_s=dt, + frames=[f['file_path'] for f in self.frames], + histogram_psnr='20log10(frozen train peak)-10log10(mean squared count error); all valid bins/channels; no upper clipping/gamma', + depth='argmax of channel-mean full-count histogram; bin_index*c*dt/2, metres; canonical GT mask', + aggregation='arithmetic mean of per-view metrics, only complete frame sets receive an aggregate', + training_scale_policy='explicit actual training scale; never test maximum', + 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')}, + image_code_sha256=sha256(Path(__file__).with_name('image_metrics.py'))) + from .image_metrics import PROTOCOL_INFO + self.metadata['image_metric_definition']=dict(PROTOCOL_INFO,scale=self.display_scale) + self.metadata['checkpoint_dir']=getattr(args,'checkpoint_dir',None) + self.metadata['checkpoint_step']=getattr(args,'step',None) + 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.' + write_json(self.output/'evaluation_protocol.json',self.metadata) + + def score(self,prediction_histogram,frame_index,prediction_scale,prediction_gamma=1.0): + if isinstance(frame_index,(bool,np.bool_)):raise IndexError('Boolean frame index') + i=operator.index(frame_index) + if i<0 or i>=len(self.frames):raise IndexError(i) + if sha256(self.path)!=self.digest:raise ValueError('Reference contract changed during evaluation') + f=self.frames[i];c=self.contract + hp=verified(self.path.parent/f['histogram_path'],f['histogram_sha256']) + mp=verified(self.path.parent/f['mask_path'],f['mask_sha256']) + reference=load_histogram(hp);mask=np.load(mp,allow_pickle=False) + if reference.shape[:3]!=(c['height'],c['width'],c['n_bins']):raise ValueError('Reference shape differs from contract') + scores,arrays=score_histograms(prediction_histogram,reference,mask, + prediction_scale=prediction_scale,reference_scale=f['reference_scale'], + histogram_peak=self.peak,bin_width_s=c['bin_width_s'],prediction_gamma=prediction_gamma) + 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' + np.savez_compressed(inp,**arrays) + env=dict(os.environ);env['PYTHONPATH']=str(BASE)+os.pathsep+env.get('PYTHONPATH','') + if self.device=='cpu':env['CUDA_VISIBLE_DEVICES']='' + proc=subprocess.run([PYTHON,'-m','evaluation.worker', + '--input',str(inp),'--output',str(result),'--display',str(display), + '--scale',str(self.display_scale),'--device',self.device],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True) + if proc.returncode:raise RuntimeError('Common image scorer failed: '+proc.stdout[-5000:]) + scores.update(json.loads(result.read_text())) + row=dict(view=i,frame=f['file_path'],prediction_scale=float(prediction_scale), + prediction_gamma=float(prediction_gamma),valid_pixels=int(mask.sum()),**scores) + self.rows=[r for r in self.rows if r['view']!=i]+[row];self.rows.sort(key=lambda r:r['view']) + write_json(self.output/'metrics_per_view.json',self.rows) + complete=len(self.rows)==len(self.frames) + write_json(self.output/'progress.json',dict(completed_views=len(self.rows),expected_views=len(self.frames),complete=complete)) + if complete: + write_json(self.output/'metrics_aggregate.json',{k:float(np.mean([r[k] for r in self.rows])) for k in scores}) + with np.load(display) as d:p,g=d['prediction'],d['reference'] + return dict(scores,psnr=scores['image_psnr'],prediction_display=p,reference_display=g, + reference_histogram=reference,reference_scale=f['reference_scale'], + prediction_intensity_counts=arrays['prediction'],reference_intensity_counts=arrays['reference'], + mask=arrays['mask'],prediction_depth=arrays['prediction_depth'],reference_depth=arrays['reference_depth'],protocol=PROTOCOL) + +class EvaluationRun: + """The same scoring/output path for native rendering and saved predictions.""" + def __init__(self, project, args, output_dir, frames, scale, gamma=1.0, + rendering=None, save_predictions=False): + self.scale = positive(scale, 'actual training scale') + self.gamma = positive(gamma, 'actual training gamma') + self.evaluator = UnifiedEvaluator(project, args, output_dir, frames) + self.output = Path(output_dir) + self.save_predictions = save_predictions + manifest = dict(frames=frames, prediction_scale=self.scale, + prediction_gamma=self.gamma, + bin_width_s=self.evaluator.contract['bin_width_s'], + rendering=rendering or {'source': 'saved histograms; see source manifest'}) + write_json(self.output/'prediction_manifest.json', manifest) + self.evaluator.metadata.update(prediction_scale=self.scale, prediction_gamma=self.gamma, + rendering=manifest['rendering']) + write_json(self.evaluator.output/'evaluation_protocol.json', self.evaluator.metadata) + + def score(self, prediction, index): + if self.save_predictions: + if hasattr(prediction, 'detach'): + prediction = prediction.detach().cpu().numpy() + np.save(self.output/f'{index}_transient_array.npy', prediction) + scores = self.evaluator.score(prediction, index, self.scale, self.gamma) + print(self.evaluator.project, index, {k: scores[k] for k in + ('histogram_psnr', 'image_psnr', 'ssim', 'lpips', 'depth_l1_m')}, flush=True) + return scores + + def finish(self): + if len(self.evaluator.rows) != len(self.evaluator.frames): + raise ValueError('Incomplete canonical test set: no complete evaluation result') + return self.evaluator.output/'metrics_aggregate.json' diff --git a/codes/reconstruction/trnerf/evaluation/image_metrics.py b/codes/reconstruction/trnerf/evaluation/image_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..21f88ff92b2aefd2895c10990710d0d069d76b61 --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/image_metrics.py @@ -0,0 +1,114 @@ +"""Shared TA-style display metrics, with uncensored linear-count diagnostics. + +Not an exact upstream reproduction: all projects use one reference-only mask, +explicit SSIM settings, a frozen training scale, and FP32 LPIPS. +""" +import numpy as np +import torch +import lpips +from contextlib import contextmanager +from scipy.ndimage import minimum_filter +from skimage.metrics import structural_similarity + +PROTOCOL = 'shared_ta_display_psnr_ssim_lpips_v3_20260929' +PRIMARY_KEYS = ('psnr', 'ssim', 'lpips') +AUXILIARY_KEYS = ('linear_psnr', 'prediction_above_scale_percent', + 'reference_above_scale_percent', 'max_prediction_over_scale', + 'max_reference_over_scale') +SCORE_KEYS = PRIMARY_KEYS + AUXILIARY_KEYS +PROTOCOL_INFO = dict( + protocol=PROTOCOL, + scale_policy="explicit frozen per-scene record; no numeric scene fallback", + metric_labels=dict(psnr='PSNR-display', ssim='SSIM-display', lpips='LPIPS-display', + linear_psnr='PSNR-linear (auxiliary)'), + prediction_display='clip(I/D,0,1) ** (1/2.2)', + reference_display='(I/D) ** (1/2.2), no upper clipping', + psnr='-10log10 valid-reference-pixel/RGB display MSE; fixed peak 1', + ssim='RGB, data_range=1, uniform 7x7, sample covariance, complete reference-valid windows', + lpips='same display RGB, common invalid region black, [-1,1] transform, VGG0.1 FP32', + linear_psnr='-10log10 mean(((prediction-reference)/D)^2); no upper clipping or gamma', + above_scale_percent='percentage of reference-valid pixels with ANY RGB channel > D', + aggregation='arithmetic mean of per-view metrics; saturation percentages are mean per-view percentages', + prediction_upper_clip=True, reference_upper_clip=False, + count_domain_upper_clip=False, fitted_test_exposure=False, + preview_png='clip display arrays only for uint8 export; floating scoring arrays are retained', + upstream_exact=False, +) + +@contextmanager +def scoring_precision(): + previous = (torch.get_float32_matmul_precision(), + torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32) + try: + torch.set_float32_matmul_precision('highest') + torch.backends.cuda.matmul.allow_tf32=False + torch.backends.cudnn.allow_tf32=False + yield + finally: + torch.set_float32_matmul_precision(previous[0]) + torch.backends.cuda.matmul.allow_tf32=previous[1] + torch.backends.cudnn.allow_tf32=previous[2] + +def tone_map(image, scale, *, prediction): + """Role is explicit: upstream prediction and reference transforms differ.""" + x=np.asarray(image,dtype=np.float64) + if not np.isfinite(scale) or scale <= 0: + raise ValueError('positive fixed scale required') + if not np.isfinite(x).all() or np.any(x<0): + raise ValueError('Expected finite nonnegative counts; no silent masking/clipping of invalid inputs') + x=x/scale + if prediction: + x=np.clip(x,0.,1.) + return x**(1/2.2) + +def display_pair(prediction, reference, scale, mask=None): + p=tone_map(prediction,scale,prediction=True) + g=tone_map(reference,scale,prediction=False) + if mask is not None: + mask=np.asarray(mask,bool) + p[~mask]=0;g[~mask]=0 + return p,g + +def preview_uint8(display_image): + """PNG encoding only. Never pass this output back to a metric.""" + return np.rint(np.clip(display_image,0.,1.)*255.).astype(np.uint8) + +def _psnr(mse): + return float(-10*np.log10(mse)) if mse>0 else float('inf') + +class ImageMetrics: + def __init__(self, scale, device='cuda'): + if not np.isfinite(scale) or scale<=0: + raise ValueError('positive fixed scale required') + self.scale=float(scale);self.device=str(device) + self.net=lpips.LPIPS(net='vgg',version='0.1').float().to(device).eval() + + def __call__(self, prediction, reference, mask): + pred=np.asarray(prediction,np.float64);ref=np.asarray(reference,np.float64) + mask=np.asarray(mask,dtype=bool) + if pred.shape!=ref.shape or pred.ndim!=3 or pred.shape[-1]!=3 or mask.shape!=pred.shape[:2]: + raise ValueError('Expected matching HWC3 images and HW reference mask') + if not mask.any(): + raise ValueError('No reference-valid pixels') + x,y=display_pair(pred,ref,self.scale) + psnr=_psnr(np.mean((x[mask]-y[mask])**2,dtype=np.float64)) + linear_psnr=_psnr(np.mean(((pred[mask]-ref[mask])/self.scale)**2,dtype=np.float64)) + windows=minimum_filter(mask.astype(np.uint8),size=7,mode='constant',cval=0).astype(bool) + if not windows.any(): + raise ValueError('No complete 7x7 reference-valid SSIM windows') + _,ssim_map=structural_similarity(y,x,data_range=1.,channel_axis=-1, + win_size=7,gaussian_weights=False,use_sample_covariance=True,full=True) + ssim=float(ssim_map[windows].mean()) + x[~mask]=0;y[~mask]=0 + tensor=lambda z: torch.from_numpy(z.astype(np.float32)).permute(2,0,1)[None].to(self.device)*2-1 + with scoring_precision(),torch.no_grad(),torch.autocast(device_type=self.device.split(':')[0],enabled=False): + score=self.net(tensor(x),tensor(y)) + return dict(psnr=psnr,ssim=ssim,lpips=float(score.item()),linear_psnr=linear_psnr, + prediction_above_scale_percent=float(np.any(pred[mask]>self.scale,axis=-1).mean()*100), + reference_above_scale_percent=float(np.any(ref[mask]>self.scale,axis=-1).mean()*100), + max_prediction_over_scale=float(pred[mask].max()/self.scale), + max_reference_over_scale=float(ref[mask].max()/self.scale)) + +def aggregate(rows): + if not rows:raise ValueError('Cannot aggregate empty results') + return {k:float(np.mean([r[k] for r in rows],dtype=np.float64)) for k in SCORE_KEYS} diff --git a/codes/reconstruction/trnerf/evaluation/io.py b/codes/reconstruction/trnerf/evaluation/io.py new file mode 100644 index 0000000000000000000000000000000000000000..7e60dcd7d8efcae23e61ced00e87642448edd9f3 --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/io.py @@ -0,0 +1,30 @@ +import hashlib +import json +import os +from pathlib import Path +import numpy as np + +def sha256(path): + h=hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block) + return h.hexdigest() + +def write_json(path, data): + path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) + tmp=path.with_name(path.name+'.%d.tmp'%os.getpid()) + tmp.write_text(json.dumps(data,indent=2,allow_nan=True));tmp.replace(path) + +def verified(path, digest): + path=Path(path) + if not path.is_file() or sha256(path)!=digest: + raise ValueError('Frozen input missing or changed: '+str(path)) + return path + +def load_histogram(path): + path=Path(path) + if path.suffix=='.npy':return np.load(path,mmap_mode='r',allow_pickle=False) + if path.suffix in ('.h5','.hdf5'): + import h5py + with h5py.File(path,'r') as f:return np.asarray(f['data']) + raise ValueError('Use unclipped .npy or .h5 histogram exports: '+str(path)) diff --git a/codes/reconstruction/trnerf/evaluation/renderer.py b/codes/reconstruction/trnerf/evaluation/renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..66d5263dee09eb15a1267dc4579316422cd66ecd --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/renderer.py @@ -0,0 +1,164 @@ +"""trnerf model loading and native ray sampling; no method-specific scoring.""" +import json +import math +import os +from pathlib import Path +import numpy as np + +PROJECT = 'trnerf' + +def _to_numpy(x): + if isinstance(x, np.ndarray): + return x + if isinstance(x, torch.Tensor): + return x.detach().cpu().numpy() + return np.asarray(x) + +def _load_irf_series(path: str, column: str) -> np.ndarray: + ext = os.path.splitext(path)[1].lower() + if ext == ".csv": + df = pd.read_csv(path, sep=",") + if column in df.columns: + arr = df[column].to_numpy(dtype=np.float64) + else: + numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)] + if not numeric_cols: + raise ValueError(f"No numeric columns found in IRF CSV: {path}") + arr = df[numeric_cols[0]].to_numpy(dtype=np.float64) + return arr.squeeze() + if ext == ".npy": + return np.load(path).astype(np.float64).squeeze() + if ext == ".mat": + mat = sio.loadmat(path) + if "out" in mat: + return _to_numpy(mat["out"]).astype(np.float64).squeeze() + for value in mat.values(): + if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1: + return _to_numpy(value).astype(np.float64).squeeze() + raise ValueError(f"Cannot find valid IRF series in mat file: {path}") + if ext == ".pt": + return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze() + raise ValueError(f"Unsupported IRF extension: {ext}") + +def build_irf_kernel(args, device): + irf_path = getattr(args, "irf_path", "") or args.pulse_path + if not irf_path: + raise ValueError("IRF path is empty. Set --irf_path or --pulse_path.") + + irf_column = getattr(args, "irf_column", "irf") + irf_half_window = int(getattr(args, "irf_half_window", 50)) + no_irf_reverse = bool(getattr(args, "no_irf_reverse", False)) + + irf = _load_irf_series(irf_path, irf_column) + if irf.ndim != 1: + irf = irf.reshape(-1) + if irf.size == 0: + raise ValueError(f"Loaded empty IRF from: {irf_path}") + + peak_idx = int(np.argmax(irf)) + if irf_half_window > 0: + lo = max(0, peak_idx - irf_half_window) + hi = min(len(irf), peak_idx + irf_half_window + 1) + irf = irf[lo:hi] + + irf = irf / (irf.sum() + 1e-8) + if not no_irf_reverse: + irf = irf[::-1].copy() + + laser = torch.tensor(irf, dtype=torch.float32, device=device) + return torch_laser_kernel(laser, device=device) + + +def render_histogram(dataset, index, render, height, width, bins, repeats=30, + ray_chunk_size=None): + """Retain the native float32 weighted average and fresh jitter per repeat.""" + pred = np.zeros((height, width, bins, 3), dtype=np.float32) + flat_pred = pred.reshape(-1, bins, 3) + weights = np.zeros((height, width), dtype=np.float32) + ray_count = height * width + chunk_size = ray_count if ray_chunk_size is None else int(ray_chunk_size) + if chunk_size <= 0: + raise ValueError('Test ray chunk size must be positive') + for _ in range(repeats): + data = dataset[index] + rays = data['rays'] + rays = rays._replace(origins=rays.origins.reshape(-1, 3), + viewdirs=rays.viewdirs.reshape(-1, 3)) + ray_weights = data['weights'].reshape(-1) + for start in range(0, ray_count, chunk_size): + stop = min(start + chunk_size, ray_count) + chunk_rays = rays._replace(origins=rays.origins[start:stop], + viewdirs=rays.viewdirs[start:stop]) + out = render(chunk_rays) + flat_pred[start:stop] += (out['colors'] * ray_weights[start:stop, None]).reshape( + stop - start, bins, 3).detach().cpu().numpy() + del out + weights += data['weights'].detach().cpu().numpy().reshape(height, width) + return pred / np.clip(weights, 1e-8, None)[..., None, None] + +def main(): + global torch, pd, sio, torch_laser_kernel + import torch + import pandas as pd + import scipy.io as sio + from nerfacc import OccGridEstimator + from misc.transient_volrend import torch_laser_kernel + from loaders.loader_captured_ours import LearnRays, SubjectLoaderTransientRealOurs + from radiance_fields.ngp import NGPRadianceField + from utils import render_transient + from .arguments import load_eval_args + from .units import tn_training_scale + from .evaluator import EvaluationRun + + args = load_eval_args() + if args.version != 'captured' or args.split != 'test': + raise ValueError('This benchmark evaluates captured canonical test frames only') + if args.rep_number != 30: + raise ValueError('The published benchmark evaluation uses 30 forward repetitions') + frames = json.loads((Path(args.test_folder_path)/'transforms_test.json').read_text())['frames'] + scale = tn_training_scale(args) + output = args.shared_output_dir or str(Path(args.checkpoint_dir)/f'evaluation_step{args.step}') + run = EvaluationRun(PROJECT, args, output, frames, scale, + rendering=dict(forward_repeats=30, sampling='native fresh ray jitter and weighted average', + ray_chunk_size=args.test_chunk_size, accumulation_device='cpu'), + save_predictions=args.save_predictions) + device = args.device + aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device) + h = int(args.img_height_test or args.img_shape_test) + w = int(args.img_width_test or args.img_shape_test) + params = np.load(args.intrinsics, allow_pickle=True)[()] + shift, calibrated_rays = _to_numpy(params['shift']), _to_numpy(params['rays']) + args.laser_kernel = build_irf_kernel(args, device) + dataset = SubjectLoaderTransientRealOurs( + subject_id=args.scene, root_fp=args.test_folder_path, split='test', num_rays=None, + img_shape=(h,w), have_images=True, n_bins=args.n_bins, color_bkgd_aug='black', + rfilter_sigma=args.rfilter_sigma, shift=shift, + measurement_root=args.measurement_root.strip() or None, + data_exts=tuple(e.strip() for e in args.data_exts.split(',') if e.strip()), + bin_width_s=args.bin_width_s_loader or args.exposure_time/299792458., + source_img_shape=calibrated_rays.shape[:2], + invalid_mask_path=args.invalid_mask_path.strip() or None, + invalid_mask_invalid_gt=args.invalid_mask_invalid_gt, + testing=True, sample_as_per_distribution=args.sample_as_per_distribution) + dataset.K = LearnRays(calibrated_rays, device=device, img_shape=(h,w)).to(device) + dataset.rep = 1 + dataset.camtoworlds = dataset.camtoworlds.to(device) + dataset.K = dataset.K.to(device) + estimator = OccGridEstimator(roi_aabb=aabb, resolution=args.grid_resolution, + levels=args.grid_nlvl).to(device) + model = NGPRadianceField(use_viewdirs=True, aabb=aabb, unbounded=False, + radiance_activation=torch.exp, args=args).to(device) + model.load_state_dict(torch.load(Path(args.checkpoint_dir)/f'radiance_field_{args.step:04d}.pth', map_location=device)) + estimator.load_state_dict(torch.load(Path(args.checkpoint_dir)/f'occupancy_grid_{args.step:04d}.pth', map_location=device)) + model.eval() + estimator.eval() + step_size = (((aabb[3:]-aabb[:3]).max()*math.sqrt(3))/args.render_n_samples).item() + def render(rays): + return render_transient(model, estimator, rays, near_plane=args.near_plane, + far_plane=args.far_plane, render_step_size=step_size, cone_angle=args.cone_angle, + alpha_thre=args.alpha_thre, use_normals=False, args=args) + with torch.no_grad(): + for i in range(len(dataset)): + run.score(render_histogram(dataset, i, render, h, w, args.n_bins, + ray_chunk_size=args.test_chunk_size), i) + print(run.finish()) diff --git a/codes/reconstruction/trnerf/evaluation/units.py b/codes/reconstruction/trnerf/evaluation/units.py new file mode 100644 index 0000000000000000000000000000000000000000..00b727d7a5b2f38cb6231a55ea00deb768afdee8 --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/units.py @@ -0,0 +1,84 @@ +import math +"""Actual training units; a test-split maximum is never a fallback.""" +import ast +import json +from pathlib import Path +from types import SimpleNamespace +from .core import positive +from .io import write_json,sha256 + +def record_training_units(directory,scale,gamma,train_poses,project,measurement_root=None,intrinsics=None): + path=Path(directory)/'image_metric_normalization.json' + data=dict(training_scale=positive(scale,'training scale'),training_gamma=positive(gamma,'training gamma'), + project=project,train_poses=str(Path(train_poses).resolve()),train_poses_sha256=sha256(train_poses), + measurement_root=measurement_root,intrinsics=intrinsics, + intrinsics_sha256=sha256(intrinsics) if intrinsics else None, + source='actual training loader/configuration; never computed from test data') + if path.exists(): + old=json.loads(path.read_text()) + if (float(old['training_scale'])!=data['training_scale'] or + float(old.get('training_gamma',1.0))!=data['training_gamma']): + raise ValueError('Checkpoint directory already records different training units') + for key in ('train_poses_sha256','intrinsics_sha256','measurement_root'): + if key in old and old[key]!=data[key]: + raise ValueError('Checkpoint training provenance differs: '+key) + return + write_json(path,data) + +def fwp_training_units(args): + root=Path(args.checkpoint_dir);metadata=root/'image_metric_normalization.json' + if metadata.exists(): + record=json.loads(metadata.read_text()) + scale,gamma=record['training_scale'],record['training_gamma'] + else: + params=root/'params_full.txt' + if not params.is_file():raise ValueError('FWP requires saved training params_full.txt or normalization metadata') + values={} + for line in params.read_text().splitlines(): + if '=' not in line or line.lstrip().startswith('#'):continue + k,v=line.split('=',1) + if k.strip() in ('dataset_scale','gamma'):values[k.strip()]=ast.literal_eval(v.strip()) + scale,gamma=values['dataset_scale'],values['gamma'] + scale,gamma=positive(scale,'training dataset_scale'),positive(gamma,'training gamma') + if float(args.dataset_scale)!=scale or float(args.gamma)!=gamma: + raise ValueError('Evaluation dataset_scale/gamma differs from saved FWP training units') + return scale,gamma + +def scalar(value): + if hasattr(value, 'detach'): + value = value.detach().cpu().item() + value = float(value) + if not math.isfinite(value) or value <= 0: + raise ValueError('A finite positive count scale is required') + return value + +def resolve_prediction_scale(system): + value = system.config.dataset.get('image_metric_training_scale', None) + if hasattr(system, '_image_metric_training_scale'): + if value is not None and scalar(value) != scalar(system._image_metric_training_scale): + raise ValueError('Explicit training scale conflicts with checkpoint metadata') + return scalar(system._image_metric_training_scale), 'training/checkpoint metadata' + if value is not None: + return scalar(value), 'explicit dataset.image_metric_training_scale' + raise ValueError('Missing actual training scale; use checkpoint metadata or set dataset.image_metric_training_scale. Never substitute the test maximum.') + +def tn_training_scale(args): + """Restore model output units; the independently normalized test split is not valid here.""" + explicit = getattr(args, "shared_prediction_scale", None) + path = Path(args.checkpoint_dir) / "image_metric_normalization.json" + recorded = None + if path.is_file(): + recorded = json.loads(path.read_text()).get("training_scale") + if explicit is None and recorded is None: + raise ValueError( + "Shared metrics require the TRAINING histogram normalization. " + "Supply --shared-prediction-scale from the training loader, or create " + + str(path) + " with training_scale and its training-data provenance. " + "The test split maximum must never be substituted." + ) + if explicit is not None and recorded is not None and float(explicit) != float(recorded): + raise ValueError("Explicit prediction scale conflicts with checkpoint normalization metadata") + value = float(recorded if explicit is None else explicit) + if not math.isfinite(value) or value <= 0: + raise ValueError("Training histogram normalization must be finite and positive") + return value diff --git a/codes/reconstruction/trnerf/evaluation/worker.py b/codes/reconstruction/trnerf/evaluation/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..2e99015d8a945dbd42af07654af354978dffcb1f --- /dev/null +++ b/codes/reconstruction/trnerf/evaluation/worker.py @@ -0,0 +1,21 @@ +"""Run image scoring in the same installed environment for all three methods.""" +import argparse +from pathlib import Path +import numpy as np +from .io import write_json + +def main(): + p=argparse.ArgumentParser() + for k in ('input','output','display'):p.add_argument('--'+k,required=True) + p.add_argument('--scale',required=True,type=float);p.add_argument('--device',default='cpu') + a=p.parse_args() + from .image_metrics import ImageMetrics,display_pair + with np.load(a.input) as d: + pred,ref,mask=d['prediction'],d['reference'],d['mask'].astype(bool) + scores=ImageMetrics(a.scale,a.device)(pred,ref,mask) + scores['image_psnr']=scores.pop('psnr') + x,y=display_pair(pred,ref,a.scale,mask) + np.savez_compressed(a.display,prediction=x,reference=y) + write_json(a.output,scores) + +if __name__=='__main__':main() diff --git a/codes/reconstruction/trnerf/loaders/__init__.py b/codes/reconstruction/trnerf/loaders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/trnerf/loaders/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/trnerf/loaders/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba6fafc2731476b405fd40be4324cffc84175ae0 Binary files /dev/null and b/codes/reconstruction/trnerf/loaders/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/loaders/__pycache__/loader_captured_ours.cpython-312.pyc b/codes/reconstruction/trnerf/loaders/__pycache__/loader_captured_ours.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38b8d319f8252937587ced9439e050adfc057946 Binary files /dev/null and b/codes/reconstruction/trnerf/loaders/__pycache__/loader_captured_ours.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/loaders/__pycache__/utils.cpython-312.pyc b/codes/reconstruction/trnerf/loaders/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1961f8b475edc03842c9630d85b9913aff03f6c9 Binary files /dev/null and b/codes/reconstruction/trnerf/loaders/__pycache__/utils.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/loaders/loader_captured_ours.py b/codes/reconstruction/trnerf/loaders/loader_captured_ours.py new file mode 100644 index 0000000000000000000000000000000000000000..9d247e0468669c83db7e9e229ddebc2ac027c00e --- /dev/null +++ b/codes/reconstruction/trnerf/loaders/loader_captured_ours.py @@ -0,0 +1,680 @@ +import json +import os +from typing import Sequence, Tuple + +# import h5py +import numpy as np +import scipy +import torch +import torch.nn.functional as F +from tqdm import tqdm + +from .utils import Rays + + +C = 299792458.0 + + +def _normalize_index(idx: torch.Tensor, size: int) -> torch.Tensor: + if size <= 1: + return torch.zeros_like(idx) + return 2.0 * idx / float(size - 1) - 1.0 + + +def _load_numpy_coo_npz(npz_path: str) -> np.ndarray: + pack = np.load(npz_path, allow_pickle=False) + try: + if "format" not in pack: + raise ValueError("missing 'format' key in npz") + fmt = str(np.asarray(pack["format"]).item()) + if fmt != "coo_numpy": + raise ValueError(f"unsupported npz format tag: {fmt}") + + shape = tuple(np.asarray(pack["shape"], dtype=np.int64).tolist()) + row = np.asarray(pack["row"], dtype=np.int64) + col = np.asarray(pack["col"], dtype=np.int64) + data = np.asarray(pack["data"]) + + dense = np.zeros(shape, dtype=data.dtype) + np.add.at(dense, (row, col), data) + return dense + finally: + pack.close() + + +def _load_histogram_2d(path: str, dtype=np.float32) -> np.ndarray: + ext = os.path.splitext(path)[1].lower() + if ext == ".txt": + arr = np.loadtxt(path, dtype=dtype) + elif ext == ".npz": + try: + from scipy import sparse # type: ignore + + arr = sparse.load_npz(path).toarray() + except Exception: + arr = _load_numpy_coo_npz(path) + if dtype is not None: + arr = np.asarray(arr, dtype=dtype) + else: + raise ValueError(f"unsupported histogram extension for 2D loader: {ext}") + + arr = np.asarray(arr, dtype=dtype) + if arr.ndim == 1: + arr = arr.reshape(1, -1) + return arr + + +def _reshape_histogram_to_hwt(arr: np.ndarray, hw: Tuple[int, int]) -> torch.Tensor: + h, w = int(hw[0]), int(hw[1]) + if arr.ndim == 3: + if arr.shape[0] == h and arr.shape[1] == w: + out = arr + elif arr.shape[0] == w and arr.shape[1] == h: + out = arr.transpose(1, 0, 2) + else: + raise ValueError(f"3D histogram shape {arr.shape} incompatible with target ({h}, {w}, T)") + return torch.from_numpy(np.asarray(out, dtype=np.float32)) + + if arr.ndim != 2: + raise ValueError(f"expected 2D/3D histogram array, got shape={arr.shape}") + + if arr.shape[0] == h * w: + out = arr.reshape(h, w, arr.shape[1]) + elif arr.shape[1] == h * w: + out = arr.T.reshape(h, w, arr.shape[0]) + else: + raise ValueError( + f"2D histogram shape {arr.shape} does not match H*W={h*w}; " + "expected [H*W, bins] or [bins, H*W]." + ) + return torch.from_numpy(np.asarray(out, dtype=np.float32)) + + +def _load_valid_mask_from_offset( + offset_path: str, + source_hw: Tuple[int, int], + target_hw: Tuple[int, int], + invalid_gt: float = 10.0, +) -> torch.Tensor: + ext = os.path.splitext(offset_path)[1].lower() + if ext == ".npy": + arr = np.load(offset_path).astype(np.float32) + else: + arr = np.loadtxt(offset_path, dtype=np.float32) + arr = np.asarray(arr, dtype=np.float32).squeeze() + + src_h, src_w = int(source_hw[0]), int(source_hw[1]) + if arr.ndim == 1: + if arr.size != src_h * src_w: + raise ValueError( + f"offset map length {arr.size} does not match source H*W={src_h*src_w}" + ) + arr = arr.reshape(src_h, src_w) + elif arr.ndim == 2: + if arr.shape == (src_h, src_w): + pass + elif arr.shape == (src_w, src_h): + arr = arr.T + elif arr.size == src_h * src_w: + arr = arr.reshape(src_h, src_w) + else: + raise ValueError( + f"offset map shape {arr.shape} incompatible with source shape ({src_h}, {src_w})" + ) + else: + raise ValueError(f"offset map must be 1D/2D, got shape={arr.shape}") + + valid = (arr <= float(invalid_gt)).astype(np.float32) + valid_t = torch.from_numpy(valid)[None, None, ...] + + dst_h, dst_w = int(target_hw[0]), int(target_hw[1]) + if (src_h, src_w) != (dst_h, dst_w): + valid_t = F.interpolate( + valid_t, + size=(dst_h, dst_w), + mode="nearest", + ) + return valid_t.squeeze(0).squeeze(0) > 0.5 + + +def _load_measurement_histogram(path: str, hw: Tuple[int, int]) -> torch.Tensor: + ext = os.path.splitext(path)[1].lower() + if ext in (".txt", ".npz"): + arr = _load_histogram_2d(path, dtype=np.float32) + hist = _reshape_histogram_to_hwt(arr, hw) + elif ext == ".pt": + raw = torch.load(path, map_location="cpu") + if not isinstance(raw, torch.Tensor): + raise ValueError(f".pt file must contain a tensor: {path}") + hist = raw.to_dense() if raw.is_sparse else raw + hist = hist.to(torch.float32).cpu() + if hist.ndim == 2: + hist = _reshape_histogram_to_hwt(hist.numpy(), hw) + elif hist.ndim == 3: + pass + else: + raise ValueError(f"unsupported tensor shape in {path}: {tuple(hist.shape)}") + # elif ext in (".h5", ".hdf5"): + # with h5py.File(path, "r") as f: + # if "data" not in f: + # raise ValueError(f"h5 file missing key 'data': {path}") + # arr = np.asarray(f["data"]) + # hist = _reshape_histogram_to_hwt(arr, hw) + else: + raise ValueError(f"unsupported measurement extension: {ext}") + + if hist.ndim == 4 and hist.shape[-1] == 1: + hist = hist[..., 0] + if hist.ndim == 4 and hist.shape[-1] == 3: + hist = hist[..., 0] + if hist.ndim != 3: + raise ValueError(f"expected histogram shape [H,W,T], got {tuple(hist.shape)} from {path}") + return hist + + +def _parse_shift_for_grid(shift, hw: Tuple[int, int]): + h, w = int(hw[0]), int(hw[1]) + arr = np.asarray(shift, dtype=np.float32) + if arr.ndim == 0: + return float(arr.item()), None + + arr = arr.squeeze() + if arr.ndim == 0 or arr.size == 1: + return float(arr.reshape(-1)[0]), None + + if arr.ndim == 1 and arr.size == h * w: + return 0.0, torch.from_numpy(arr.reshape(h, w)) + + if arr.ndim == 2: + shift_map = torch.from_numpy(arr.astype(np.float32)) + if tuple(shift_map.shape) != (h, w): + shift_map = F.interpolate( + shift_map[None, None, ...], + size=(h, w), + mode="bilinear", + align_corners=True, + ).squeeze(0).squeeze(0) + return 0.0, shift_map + + return float(arr.reshape(-1)[0]), None + + +def _build_shift_grid( + hw: Tuple[int, int], + n_bins: int, + shift, + bin_width_s: float, + device: str = "cpu", +) -> torch.Tensor: + h, w = int(hw[0]), int(hw[1]) + exposure_time = C * float(bin_width_s) + shift_scalar, shift_map = _parse_shift_for_grid(shift, hw) + + z = torch.arange(n_bins, device=device, dtype=torch.float32)[:, None, None] + z = z * exposure_time / 2.0 + if shift_map is not None: + z = z - shift_map.to(device)[None, ...] + else: + z = z - float(shift_scalar) + z = z * 2.0 / exposure_time + z = _normalize_index(z, n_bins) + + x = _normalize_index(torch.arange(w, device=device, dtype=torch.float32), w) + y = _normalize_index(torch.arange(h, device=device, dtype=torch.float32), h) + + x = x[None, None, :].expand(n_bins, h, w) + y = y[None, :, None].expand(n_bins, h, w) + z = z.expand(n_bins, h, w) + + # grid_sample 5D grid order is (x, y, z) for input shaped [N,C,D,H,W]. + grid = torch.stack((x, y, z), dim=-1)[None, ...] + return grid + + +def _apply_shift(hist: torch.Tensor, shift, bin_width_s: float) -> torch.Tensor: + h, w, t = hist.shape + grid = _build_shift_grid((h, w), t, shift, bin_width_s, device=hist.device) + # [H, W, T] -> [N=1, C=1, D=T, H, W] + hist_dhw = hist.permute(2, 0, 1)[None, None, ...] + shifted = F.grid_sample(hist_dhw, grid, align_corners=True) + # back to [H, W, T] + return shifted.squeeze(0).squeeze(0).permute(1, 2, 0) + + +def _resize_hist_spatial(hist: torch.Tensor, target_hw: Tuple[int, int]) -> torch.Tensor: + target_h, target_w = int(target_hw[0]), int(target_hw[1]) + h, w, _ = hist.shape + if (h, w) == (target_h, target_w): + return hist + # [H,W,T] -> [1,T,H,W] for spatial resize only. + hist_chw = hist.permute(2, 0, 1)[None, ...] + resized = F.interpolate(hist_chw, size=(target_h, target_w), mode="area") + return resized.squeeze(0).permute(1, 2, 0) + + +def _resolve_measurement_path( + data_dir: str, + split: str, + frame_file_path: str, + measurement_root: str = None, + data_exts: Sequence[str] = (".npz", ".txt", ".pt", ".h5", ".hdf5"), +) -> str: + raw = str(frame_file_path) + if os.path.isabs(raw) and os.path.isfile(raw): + return raw + + rel = raw.replace("\\", "/").lstrip("./") + base = os.path.basename(rel) + stem, ext = os.path.splitext(base) + rel_stem = os.path.splitext(rel)[0] + + roots = [] + if measurement_root: + roots.extend([measurement_root, os.path.join(measurement_root, split)]) + roots.extend([data_dir, os.path.join(data_dir, split)]) + + seen_roots = set() + unique_roots = [] + for r in roots: + rr = os.path.normpath(r) + if rr not in seen_roots: + unique_roots.append(rr) + seen_roots.add(rr) + + # Prefer exact path if extension already exists. + if ext: + for root in unique_roots: + for rel_name in (rel, base): + cand = os.path.normpath(os.path.join(root, rel_name)) + if os.path.isfile(cand): + return cand + + # Then resolve by stem and supported extensions. + for root in unique_roots: + for data_ext in data_exts: + for rel_name in (rel_stem + data_ext, stem + data_ext): + cand = os.path.normpath(os.path.join(root, rel_name)) + if os.path.isfile(cand): + return cand + + raise FileNotFoundError( + f"Cannot resolve measurement file for frame '{frame_file_path}'. " + f"Searched roots={unique_roots}, exts={tuple(data_exts)}." + ) + + +def _load_renderings_transient_real_ours( + root_fp: str, + split: str, + have_images=True, + img_shape=(256, 256), + source_img_shape=None, + n_bins=4096, + shift=0, + bin_width_s=4e-12, + measurement_root=None, + data_exts=(".npz", ".txt", ".pt", ".h5", ".hdf5"), +): + data_dir = root_fp + with open(os.path.join(data_dir, f"transforms_{split}.json"), "r", encoding="utf-8") as fp: + meta = json.load(fp) + + images = [] + camtoworlds = [] + + if have_images: + tqdm.write("Loading data") + reshape_hw = tuple(source_img_shape) if source_img_shape is not None else tuple(img_shape) + for i in tqdm(range(len(meta["frames"]))): + frame = meta["frames"][i] + file_key = frame.get("file_path", frame.get("filepath")) + if file_key is None: + raise KeyError("Each frame in transforms json must contain 'file_path' or 'filepath'.") + measurement_path = _resolve_measurement_path( + data_dir=data_dir, + split=split, + frame_file_path=file_key, + measurement_root=measurement_root, + data_exts=data_exts, + ) + + hist = _load_measurement_histogram(measurement_path, reshape_hw).to(torch.float32).cpu() + hist = torch.clip(hist, min=0.0) + hist = _apply_shift(hist, shift=shift, bin_width_s=bin_width_s) + + if hist.shape[-1] != int(n_bins): + raise ValueError( + f"Histogram bin count mismatch for '{measurement_path}': " + f"loaded {hist.shape[-1]} vs config n_bins={n_bins}. " + "This pipeline does not truncate or adjacent-bin average." + ) + + hist = _resize_hist_spatial(hist, img_shape) + hist_rgb = hist[..., None].repeat(1, 1, 1, 3) + + camtoworlds.append(frame["transform_matrix"]) + images.append(hist_rgb) + + images = torch.stack(images, axis=0) + max_value = torch.max(images).clamp_min(1e-8) + images = images / max_value + camtoworlds = np.stack(camtoworlds, axis=0) + else: + for frame in meta["frames"]: + camtoworlds.append(frame["transform_matrix"]) + camtoworlds = np.stack(camtoworlds, axis=0) + max_value = torch.tensor(1.0) + + return images, camtoworlds, max_value + + +class SubjectLoaderTransientRealOurs(torch.utils.data.Dataset): + """Captured-data loader for custom txt/npz/pt histograms without bin truncation/averaging.""" + + SPLITS = ["train", "val", "trainval", "test"] + NEAR, FAR = 0, 6 + OPENGL_CAMERA = True + + def __init__( + self, + subject_id: str, + root_fp: str, + split: str, + color_bkgd_aug: str = "black", + num_rays: int = None, + near: float = None, + far: float = None, + batch_over_images: bool = True, + have_images=True, + img_shape=(256, 256), + source_img_shape=None, + n_bins=10000, + rfilter_sigma=0.15, + sample_as_per_distribution=True, + shift=0.0, + testing=False, + bin_width_s=4e-12, + measurement_root=None, + data_exts=(".npz", ".txt", ".pt", ".h5", ".hdf5"), + invalid_mask_path=None, + invalid_mask_invalid_gt=10.0, + ): + super().__init__() + assert color_bkgd_aug in ["white", "black", "random"] + self.sample_as_per_distribution = sample_as_per_distribution + self.rfilter_sigma = rfilter_sigma + self.HEIGHT, self.WIDTH = int(img_shape[0]), int(img_shape[1]) + self.split = split + self.testing = testing + self.num_rays = num_rays + self.near = self.NEAR if near is None else near + self.far = self.FAR if far is None else far + self.training = (num_rays is not None) and (split in ["train", "trainval"]) + self.shift = shift + self.rep = 1 + self.color_bkgd_aug = color_bkgd_aug + self.batch_over_images = batch_over_images + self.have_images = have_images + self.n_bins = int(n_bins) + self.bin_width_s = float(bin_width_s) + self.measurement_root = measurement_root + self.data_exts = tuple(data_exts) + self.source_img_shape = tuple(source_img_shape) if source_img_shape is not None else None + self.invalid_mask_path = invalid_mask_path + self.invalid_mask_invalid_gt = float(invalid_mask_invalid_gt) + + if have_images: + self.images, self.camtoworlds, self.max = _load_renderings_transient_real_ours( + root_fp=root_fp, + split=split, + n_bins=self.n_bins, + shift=shift, + img_shape=(self.HEIGHT, self.WIDTH), + source_img_shape=self.source_img_shape, + bin_width_s=self.bin_width_s, + measurement_root=self.measurement_root, + data_exts=self.data_exts, + ) + self.images = self.images.to(torch.float32) + assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH) + else: + raise ValueError("have_images=False is not supported in SubjectLoaderTransientRealOurs.") + + self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32) + if self.invalid_mask_path: + source_hw = ( + tuple(self.source_img_shape) + if self.source_img_shape is not None + else (self.HEIGHT, self.WIDTH) + ) + self.valid_mask = _load_valid_mask_from_offset( + self.invalid_mask_path, + source_hw=source_hw, + target_hw=(self.HEIGHT, self.WIDTH), + invalid_gt=self.invalid_mask_invalid_gt, + ).to(torch.bool) + else: + self.valid_mask = torch.ones((self.HEIGHT, self.WIDTH), dtype=torch.bool) + + def __len__(self): + return len(self.camtoworlds) + + def __getitem__(self, index): + data = self.fetch_data(index) + data = self.preprocess(data) + return data + + def preprocess(self, data): + rgba, rays = data["rgba"], data["rays"] + + if rgba is not None: + pixels = rgba.to(self.camtoworlds.device) + else: + pixels = rgba + + if self.color_bkgd_aug == "random": + color_bkgd = torch.rand(3, device=self.camtoworlds.device) + elif self.color_bkgd_aug == "white": + color_bkgd = torch.ones(3, device=self.camtoworlds.device) + else: + color_bkgd = torch.zeros(3, device=self.camtoworlds.device) + + return { + "pixels": pixels, + "rays": rays, + "color_bkgd": color_bkgd, + **{k: v for k, v in data.items() if k not in ["rgba", "rays"]}, + } + + def update_num_rays(self, num_rays): + self.num_rays = num_rays + + def fetch_data(self, index, rep=None, num_rays=None): + if num_rays is None: + num_rays = self.num_rays + if rep is None: + rep = self.rep + + if self.training: + if self.batch_over_images: + image_id = torch.randint( + 0, + len(self.images), + size=(num_rays,), + device=self.images.device, + ) + else: + image_id = [index] + x = torch.randint(0, self.WIDTH, size=(num_rays,), device="cpu") + y = torch.randint(0, self.HEIGHT, size=(num_rays,), device="cpu") + x = x.repeat(rep) + y = y.repeat(rep) + image_id = image_id.repeat(rep) + rgba = self.images[image_id, y, x] + elif self.testing: + image_id = [index] + x, y = torch.meshgrid( + torch.arange(self.WIDTH, device="cpu"), + torch.arange(self.HEIGHT, device="cpu"), + indexing="xy", + ) + x = x.flatten().repeat(rep) + y = y.flatten().repeat(rep) + rgba = self.images[image_id, y, x] if self.have_images else None + else: + image_id = [index] + x, y = torch.meshgrid( + torch.arange(self.WIDTH, device=self.camtoworlds.device), + torch.arange(self.HEIGHT, device=self.camtoworlds.device), + indexing="xy", + ) + x = x.flatten() + y = y.flatten() + rgba = self.images[image_id, y, x] if self.have_images else None + + x_cpu_long = x.detach().cpu().long() + y_cpu_long = y.detach().cpu().long() + valid_mask = self.valid_mask[y_cpu_long, x_cpu_long] + + c2w = self.camtoworlds[image_id] + scale = self.rfilter_sigma + + if self.training or self.testing: + s_x, s_y, weights = spatial_filter( + x, + y, + sigma=scale, + rep=self.rep, + prob_dithering=self.sample_as_per_distribution, + ) + s_x = torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH - 1).to(self.camtoworlds.device).to(torch.float32) + s_y = torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT - 1).to(self.camtoworlds.device).to(torch.float32) + weights = torch.tensor(weights, device=self.camtoworlds.device, dtype=torch.float32) + else: + s_x = x + s_y = y + weights = None + + camera_dirs = self.K(s_x, s_y) + + directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1) + origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape) + viewdirs = directions / torch.linalg.norm(directions, dim=-1, keepdims=True) + + if self.training: + origins = torch.reshape(origins, (-1, 3)) + viewdirs = torch.reshape(viewdirs, (-1, 3)) + rgba = torch.reshape(rgba, (-1, self.n_bins * 3)) + valid_mask = torch.reshape(valid_mask, (-1,)) + elif self.testing: + origins = torch.reshape(origins, (-1, 3)) + viewdirs = torch.reshape(viewdirs, (-1, 3)) + if self.have_images: + rgba = torch.reshape(rgba, (-1, self.n_bins * 3)) + valid_mask = torch.reshape(valid_mask, (-1,)) + elif self.have_images: + origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3)) + viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3)) + rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, self.n_bins * 3)) + valid_mask = torch.reshape(valid_mask, (self.HEIGHT, self.WIDTH)) + else: + origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3)) + viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3)) + rgba = None + valid_mask = torch.reshape(valid_mask, (self.HEIGHT, self.WIDTH)) + + rays = Rays(origins=origins, viewdirs=viewdirs) + if self.training or self.testing: + return {"rgba": rgba, "rays": rays, "weights": weights, "valid_mask": valid_mask} + return {"rgba": rgba, "rays": rays, "valid_mask": valid_mask} + + +class LearnRays(torch.nn.Module): + """Interpolation-based ray lookup from per-pixel ray table (H,W,3).""" + + def __init__(self, rays, device="cuda:0", img_shape=(256, 256)): + super().__init__() + self.device = device + self.img_shape = (int(img_shape[0]), int(img_shape[1])) + self.height = self.img_shape[0] + self.width = self.img_shape[1] + + rays = np.asarray(rays, dtype=np.float32) + if rays.ndim != 3 or rays.shape[-1] != 3: + raise ValueError(f"rays must be [H,W,3], got shape={rays.shape}") + + rays_t = torch.from_numpy(rays).to(self.device) + if tuple(rays_t.shape[:2]) != self.img_shape: + rays_t = F.interpolate( + rays_t.permute(2, 0, 1)[None, ...], + size=self.img_shape, + mode="bilinear", + align_corners=True, + ).squeeze(0).permute(1, 2, 0) + + rays_t = rays_t / torch.linalg.norm(rays_t, dim=-1, keepdims=True).clamp_min(1e-8) + self.rays = rays_t + + def forward(self, x0, y0): + rays = self.rays + x0 = x0.to(rays.device).float() + y0 = y0.to(rays.device).float() + + x1 = torch.floor(x0) + y1 = torch.floor(y0) + x2 = x1 + 1 + y2 = y1 + 1 + + x1 = torch.clip(x1, 0, self.width - 1) + y1 = torch.clip(y1, 0, self.height - 1) + x2 = torch.clip(x2, 0, self.width - 1) + y2 = torch.clip(y2, 0, self.height - 1) + + wx2 = ((x0 - x1) / (x2 - x1 + 1e-8))[:, None] + wx1 = 1.0 - wx2 + wy2 = ((y0 - y1) / (y2 - y1 + 1e-8))[:, None] + wy1 = 1.0 - wy2 + + x1 = x1.long() + y1 = y1.long() + x2 = x2.long() + y2 = y2.long() + + out = ( + wx1 * wy1 * rays[y1, x1] + + wx1 * wy2 * rays[y2, x1] + + wx2 * wy1 * rays[y1, x2] + + wx2 * wy2 * rays[y2, x2] + ) + out = out / torch.linalg.norm(out, dim=-1, keepdims=True).clamp_min(1e-8) + return out.float() + + +def spatial_filter(x, y, sigma, rep, prob_dithering=True): + pdf_fn = lambda z: np.exp(-z / (2 * sigma**2)) - np.exp(-16) + if prob_dithering: + bounds_max = [4 * sigma] * x.shape[0] + loc = 0 + s_x = scipy.stats.truncnorm.rvs( + (-np.array(bounds_max) - loc) / sigma, + (np.array(bounds_max) - loc) / sigma, + loc=loc, + scale=sigma, + ) + s_y = scipy.stats.truncnorm.rvs( + (-np.array(bounds_max) - loc) / sigma, + (np.array(bounds_max) - loc) / sigma, + loc=loc, + scale=sigma, + ) + weights = np.ones_like(s_x) * 1 / rep + else: + s_x = np.random.uniform(low=-4 * sigma, high=4 * sigma, size=(rep, x.shape[0] // rep)) + s_y = np.random.uniform(low=-4 * sigma, high=4 * sigma, size=(rep, x.shape[0] // rep)) + dists = s_x**2 + s_y**2 + weights = pdf_fn(dists) + weights = weights / weights.sum(0)[None, :] + s_x = s_x.flatten() + s_y = s_y.flatten() + weights = weights.flatten() + return s_x, s_y, weights diff --git a/codes/reconstruction/trnerf/loaders/loader_synthetic.py b/codes/reconstruction/trnerf/loaders/loader_synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e2ef447981753cfe20c00a595cea8f154536e6 --- /dev/null +++ b/codes/reconstruction/trnerf/loaders/loader_synthetic.py @@ -0,0 +1,453 @@ +import collections +import json +import os + +import imageio.v2 as imageio +import numpy as np +import torch +import torch.nn.functional as F +import scipy +import zipfile +from .utils import Rays +import sys +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from misc.dataset_utils import read_h5 +from tqdm import tqdm + +def _load_renderings(root_fp: str, subject_id: str, split: str, have_images=True, img_shape=(256, 256)): + """Load images from disk.""" + # if not root_fp.startswith("/"): + # # allow relative path. e.g., "./data/nerf_synthetic/" + # root_fp = os.path.join( + # os.path.dirname(os.path.abspath(__file__)), + # "..", + # "..", + # root_fp, + # ) + + data_dir = root_fp + with open( + os.path.join(data_dir, "transforms_{}.json".format(split)), "r" + ) as fp: + meta = json.load(fp) + images = [] + camtoworlds = [] + + if have_images: + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + number = int(frame["file_path"].split("_")[-1]) + fname = os.path.join(data_dir, f"{number:03d}" + ".png") + + # fname = os.path.join(data_dir, frame["file_path"] + ".png") + rgba = imageio.imread(fname) + camtoworlds.append(frame["transform_matrix"]) + images.append(rgba) + + images = np.stack(images, axis=0) + camtoworlds = np.stack(camtoworlds, axis=0) + + h, w = images.shape[1:3] + else: + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + camtoworlds.append(frame["transform_matrix"]) + + camtoworlds = np.stack(camtoworlds, axis=0) + + h, w = img_shape + + camera_angle_x = float(meta["camera_angle_x"]) + focal = 0.5 * w / np.tan(0.5 * camera_angle_x) + + return images, camtoworlds, focal + + +def _load_renderings_transient(root_fp: str, subject_id: str, split: str, num_views= None, have_images=True, img_shape=(256, 256), gamma=False): + """Load images from disk.""" + # if not root_fp.startswith("/"): + # # allow relative path. e.g., "./data/nerf_synthetic/" + # root_fp = os.path.join( + # os.path.dirname(os.path.abspath(__file__)), + # "..", + # "..", + # root_fp, + # ) + + data_dir = root_fp + if split == "train": tname = f"train_v{num_views}" + else: tname = split + + with open( + os.path.join(data_dir, "transforms_{}.json".format(tname)), "r" + ) as fp: + meta = json.load(fp) + images = [] + camtoworlds = [] + + if have_images: + for i in tqdm(range(len(meta["frames"]))): + frame = meta["frames"][i] + number = int(frame["file_path"].split("_")[-1]) + + try: + files_dir = os.path.join(data_dir, split) + fname = os.path.join(files_dir, f"{split}_{number:03d}" + ".h5") + rgba = read_h5(fname) + except: + try: + files_dir = os.path.join(data_dir, "test") + fname = os.path.join(files_dir, f"test_{number:03d}" + ".h5") + rgba = read_h5(fname) + except: + try: + files_dir = os.path.join(data_dir, "test") + fname = os.path.join(files_dir, f"test_{number:03d}" + ".h5") + archive = zipfile.ZipFile(f"{fname}.zip") + file = archive.open(f"test_{number:03d}" + ".h5") + rgba = read_h5(file) + file.close() + except: + pass + + + + rgba = rgba[..., :3] + + if gamma: + print("using gamma") + rgba_sum = rgba.sum(-2) + rgba_sum_normalized = rgba_sum/rgba_sum.max() + rgba_sum_norm_gamma = rgba_sum_normalized**(1/2.2) + rgba = (rgba*rgba_sum_norm_gamma[..., None, :])/(rgba_sum[..., None, :]+1e-10) + + camtoworlds.append(frame["transform_matrix"]) + rgba = torch.clip(torch.Tensor(rgba), 0, None) + images.append(torch.Tensor(rgba)) + + + images = torch.stack(images, axis=0) + + if split == "test": + quotient = images.shape[1]//img_shape[0] + times_downsample = int(np.log2(quotient)) + + for i in range(times_downsample): + images = (images[:, 1::2, ::2] + images[:, ::2, ::2] + images[:, 1::2, 1::2] + images[:, ::2, 1::2])/4 + + + if not gamma: + #np.save(os.path.join(data_dir, "max.npy"), torch.max(images).numpy()) + max = torch.max(images) + images /= torch.max(images) + + camtoworlds = np.stack(camtoworlds, axis=0) + + h, w = images.shape[1:3] + else: + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + camtoworlds.append(frame["transform_matrix"]) + + camtoworlds = np.stack(camtoworlds, axis=0) + + h, w = img_shape + + camera_angle_x = float(meta["camera_angle_x"]) + focal = 0.5 * w / np.tan(0.5 * camera_angle_x) + + return images, camtoworlds, focal, max + + + +class SubjectLoaderTransient(torch.utils.data.Dataset): + """Single subject data loader for training and evaluation.""" + + SPLITS = ["train", "val", "trainval", "test"] + + # WIDTH, HEIGHT = 64, 64 + NEAR, FAR = 0, 6 + OPENGL_CAMERA = True + + def __init__( + self, + subject_id: str, + root_fp: str, + split: str, + color_bkgd_aug: str = "black", + num_rays: int = None, + near: float = None, + far: float = None, + batch_over_images: bool = True, + have_images=True, + img_shape=(256, 256), + n_bins=10000, + testing=False, + rfilter_sigma=0.3, + scene=None, + sample_as_per_distribution = True, + gamma=False, + num_views = None + ): + super().__init__() + self.testing = testing + # assert split in self.SPLITS, "%s" % split + assert color_bkgd_aug in ["white", "black", "random"] + self.sample_as_per_distribution = sample_as_per_distribution + + self.HEIGHT, self.WIDTH = img_shape + self.split = split + self.num_rays = num_rays + self.near = self.NEAR if near is None else near + self.far = self.FAR if far is None else far + self.training = (num_rays is not None) and ( + split in ["train", "trainval"] + ) + self.rep = 0 + self.color_bkgd_aug = color_bkgd_aug + self.batch_over_images = batch_over_images + self.have_images = have_images + self.rfilter_sigma = rfilter_sigma + self.n_bins = n_bins + if split == "trainval": + _images_train, _camtoworlds_train, _focal_train = _load_renderings_transient( + root_fp, subject_id, "train", gamma=gamma + ) + _images_val, _camtoworlds_val, _focal_val = _load_renderings_transient( + root_fp, subject_id, "val", gamma=gamma + ) + self.images = np.concatenate([_images_train, _images_val]) + self.camtoworlds = np.concatenate( + [_camtoworlds_train, _camtoworlds_val] + ) + self.focal = _focal_train + self.images = torch.from_numpy(self.images).to(torch.float32) + + # ste for transient + self.images = torch.reshape(self.images, (-1, self.HEIGHT, self.WIDTH, self.n_bins*3)) + # assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH) + + elif have_images: + self.images, self.camtoworlds, self.focal, self.max = _load_renderings_transient( + root_fp, subject_id, split, gamma=gamma, img_shape=img_shape, num_views=num_views + ) + self.images = self.images.to(torch.float32) + assert self.images.shape[1:3] == (self.HEIGHT, self.WIDTH) + else: + _, self.camtoworlds, self.focal = _load_renderings( + root_fp, subject_id, split, have_images=have_images, img_shape=img_shape, num_views=num_views + ) + + self.camtoworlds = torch.from_numpy(self.camtoworlds).to(torch.float32) + self.K = torch.tensor( + [ + [self.focal, 0, self.WIDTH / 2.0], + [0, self.focal, self.HEIGHT / 2.0], + [0, 0, 1], + ], + dtype=torch.float32, + ) # (3, 3) + + def __len__(self): + return len(self.camtoworlds) + + @torch.no_grad() + def __getitem__(self, index): + data = self.fetch_data(index) + data = self.preprocess(data) + return data + + def preprocess(self, data): + """Process the fetched / cached data with randomness.""" + rgba, rays = data["rgba"], data["rays"] + # pixels, alpha = torch.split(rgba, [3, 1], dim=-1) + if rgba is not None: + pixels = rgba.to(self.camtoworlds.device) + else: + pixels = rgba + + if self.color_bkgd_aug == "random": + color_bkgd = torch.rand(3, device=self.camtoworlds.device) + elif self.color_bkgd_aug == "white": + color_bkgd = torch.ones(3, device=self.camtoworlds.device) + elif self.color_bkgd_aug == "black": + color_bkgd = torch.zeros(3, device=self.camtoworlds.device) + + # pixels = pixels * alpha + color_bkgd * (1.0 - alpha) + return { + "pixels": pixels, # [n_rays, 3] or [h, w, 3] + "rays": rays, # [n_rays,] or [h, w] + "color_bkgd": color_bkgd, # [3,] + **{k: v for k, v in data.items() if k not in ["rgba", "rays"]}, + } + + def update_num_rays(self, num_rays): + self.num_rays = num_rays + + def fetch_data(self, index, rep=None, num_rays=None): + """Fetch the data (it maybe cached for multiple batches).""" + if num_rays==None: + num_rays = self.num_rays + if rep==None: + rep = self.rep + + if self.training: + if self.batch_over_images: + image_id = torch.randint( + 0, + len(self.images), + size=(num_rays,), + device=self.images.device, + ) + else: + image_id = [index] + x = torch.randint( + 0, self.WIDTH, size=(num_rays,), device=self.images.device + ) + y = torch.randint( + 0, self.HEIGHT, size=(num_rays,), device=self.images.device + ) + x = x.repeat(rep) + y = y.repeat(rep) + image_id = image_id.repeat(rep) + + + rgba = self.images[image_id, y, x] # (num_rays, 4) + + elif self.testing: + image_id = [index] + x, y = torch.meshgrid( + torch.arange(self.WIDTH, device="cpu"), + torch.arange(self.HEIGHT, device="cpu"), + indexing="xy", + ) + x = x.flatten() + y = y.flatten() + x = x.repeat(rep) + y = y.repeat(rep) + # image_id = image_id.repeat(rep) + try: + rgba = self.images[image_id, y, x] # (num_rays, 4) + except: rgba=None + + elif self.have_images: + image_id = [index] + x, y = torch.meshgrid( + torch.arange(self.WIDTH, device=self.camtoworlds.device), + torch.arange(self.HEIGHT, device=self.camtoworlds.device), + indexing="xy", + ) + x = x.flatten() + y = y.flatten() + rgba = self.images[image_id, y, x] # (num_rays, 4) + else: + image_id = [index] + x, y = torch.meshgrid( + torch.arange(self.WIDTH, device=self.camtoworlds.device), + torch.arange(self.HEIGHT, device=self.camtoworlds.device), + indexing="xy", + ) + x = x.flatten() + y = y.flatten() + + # generate rays + + scale = self.rfilter_sigma + c2w = self.camtoworlds[image_id] # (num_rays, 3, 4) + bounds_max = [4*scale]*x.shape[0] + loc = 0 + if self.training: + s_x, s_y, weights = spatial_filter(x, y, sigma=scale, rep = self.rep, prob_dithering=self.sample_as_per_distribution) + s_x = (torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH).to(self.camtoworlds.device)).to(torch.float32) + s_y = (torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT).to(self.camtoworlds.device)).to(torch.float32) + weights = torch.Tensor(weights).to(self.camtoworlds.device) + #s_x = x.to(self.camtoworlds.device).to(torch.float32) + #s_y = y.to(self.camtoworlds.device).to(torch.float32) + + elif self.testing: + s_x, s_y, weights = spatial_filter(x, y, sigma=scale, rep = self.rep, prob_dithering=self.sample_as_per_distribution, normalize=False) + s_x = (torch.clip(x + torch.from_numpy(s_x), 0, self.WIDTH).to(self.camtoworlds.device)).to(torch.float32) + s_y = (torch.clip(y + torch.from_numpy(s_y), 0, self.HEIGHT).to(self.camtoworlds.device)).to(torch.float32) + weights = torch.Tensor(weights).to(self.camtoworlds.device) + #s_x = x.to(self.camtoworlds.device).to(torch.float32) + #s_y = y.to(self.camtoworlds.device).to(torch.float32) + else: + s_x = x + s_y = y + + camera_dirs = F.pad( + torch.stack( + [ + (s_x - self.K[0, 2] + 0.5) / self.K[0, 0], + (s_y - self.K[1, 2] + 0.5) + / self.K[1, 1] + * (-1.0 if self.OPENGL_CAMERA else 1.0), + ], + dim=-1, + ), + (0, 1), + value=(-1.0 if self.OPENGL_CAMERA else 1.0), + ) + + directions = (camera_dirs[:, None, :] * c2w[:, :3, :3]).sum(dim=-1) + origins = torch.broadcast_to(c2w[:, :3, -1], directions.shape) + viewdirs = directions / torch.linalg.norm( + directions, dim=-1, keepdims=True + ) + + if self.training: + origins = torch.reshape(origins, (-1, 3)) + viewdirs = torch.reshape(viewdirs, (-1, 3)) + # here + rgba = torch.reshape(rgba, (-1,self.n_bins*3)) + elif self.testing: + origins = torch.reshape(origins, (-1, 3)) + viewdirs = torch.reshape(viewdirs, (-1, 3)) + # here + try: rgba = torch.reshape(rgba, (-1,self.n_bins*3)) + except: rgba = None + + elif self.have_images: + origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3)) + viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3)) + rgba = torch.reshape(rgba, (self.HEIGHT, self.WIDTH, self.n_bins * 3)) + else: + origins = torch.reshape(origins, (self.HEIGHT, self.WIDTH, 3)) + viewdirs = torch.reshape(viewdirs, (self.HEIGHT, self.WIDTH, 3)) + rgba = None + + rays = Rays(origins=origins, viewdirs=viewdirs) + if self.training or self.testing: + return { + "rgba": rgba, # [h, w, 4] or [num_rays, 4] + "rays": rays, # [h, w, 3] or [num_rays, 3] + "weights":weights + } + + return { + "rgba": rgba, # [h, w, 4] or [num_rays, 4] + "rays": rays, # [h, w, 3] or [num_rays, 3] + } + + +def spatial_filter(x, y, sigma, rep, prob_dithering=True, normalize=True): + pdf_fn = lambda x: np.exp(-x/(2*sigma**2)) - np.exp(-16) + if prob_dithering: + bounds_max = [4*sigma]*x.shape[0] + loc = 0 + s_x = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma) + s_y = scipy.stats.truncnorm.rvs((-np.array(bounds_max)-loc)/sigma, (np.array(bounds_max)-loc)/sigma, loc=loc, scale=sigma) + weights = np.ones_like(s_x)*1/rep + + else: + s_x = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep)) + s_y = np.random.uniform(low=-4*sigma, high=4*sigma, size=(rep, x.shape[0]//rep)) + dists = (s_x**2 + s_y**2) + weights = pdf_fn(dists) + if normalize: + weights = weights/weights.sum(0)[None, :] + s_x = s_x.flatten() + s_y = s_y.flatten() + weights = weights.flatten() + + return s_x, s_y, weights \ No newline at end of file diff --git a/codes/reconstruction/trnerf/loaders/utils.py b/codes/reconstruction/trnerf/loaders/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..04d223f54022448c9827f4f26768a2b5973ba37a --- /dev/null +++ b/codes/reconstruction/trnerf/loaders/utils.py @@ -0,0 +1,12 @@ +""" +Copyright (c) 2022 Ruilong Li, UC Berkeley. +""" + +import collections + +Rays = collections.namedtuple("Rays", ("origins", "viewdirs")) + + +def namedtuple_map(fn, tup): + """Apply `fn` to each element of `tup` and cast to `tup`'s namedtuple.""" + return type(tup)(*(None if x is None else fn(x) for x in tup)) diff --git a/codes/reconstruction/trnerf/misc/__init__.py b/codes/reconstruction/trnerf/misc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/trnerf/misc/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/trnerf/misc/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae3a468b6367aeb217efba66cd73bd2da59e0e32 Binary files /dev/null and b/codes/reconstruction/trnerf/misc/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/misc/__pycache__/summary.cpython-312.pyc b/codes/reconstruction/trnerf/misc/__pycache__/summary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d395b3f0a489c0ba0977d473ba27293c53d7ce6 Binary files /dev/null and b/codes/reconstruction/trnerf/misc/__pycache__/summary.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/misc/__pycache__/transient_volrend.cpython-312.pyc b/codes/reconstruction/trnerf/misc/__pycache__/transient_volrend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba3142a2202745889abf6b93ad82a510eceebdc1 Binary files /dev/null and b/codes/reconstruction/trnerf/misc/__pycache__/transient_volrend.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/misc/dataset_utils.py b/codes/reconstruction/trnerf/misc/dataset_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4538af85beee39b58ba38ff8655fc7bcc4ffe0 --- /dev/null +++ b/codes/reconstruction/trnerf/misc/dataset_utils.py @@ -0,0 +1,169 @@ +import os +import mat73 +import torch +import numpy as np +import json +import h5py + +def read_h5(path): + with h5py.File(path, 'r') as f: + frames = np.array(f['data']) + return frames + +def process_captured_data(files_path, savepath): + for file in os.listdir(files_path): + if file[-3:] == "mat" and (file[:-3]+"pt") not in os.listdir(savepath): + filepath = os.path.join(files_path, file) + rgba = mat73.loadmat(filepath)["transient"].transpose(1, 2, 0)[..., :][..., None] + rgba = np.flip(np.flip(rgba, 0), 1) + for i in range(3): + rgba = (rgba[1::2, ::2] + rgba[::2, ::2] + rgba[1::2, 1::2] + rgba[::2, 1::2])/4 + torch.save(rgba, os.path.join(savepath, file[:-3]+"pt")) + +def bundle_rays(pathToH5s, outputPath, trainJsonPath): + with open(trainJsonPath, "r") as fp: + meta = json.load(fp) + train_fnames = [] + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + fname = frame["filepath"][:-2]+"h5" + train_fnames.append(fname) + + frames = read_h5(os.path.join(pathToH5s, train_fnames[0])) + w = frames.shape[0] + h = frames.shape[1] + bins = frames.shape[2] + + x = np.linspace(0, h-1, h) + y = np.linspace(0, w-1, w) + X, Y = np.meshgrid(x, y) + + if len(frames.shape) == 4: + channels = 3 + else: + channels = 1 + num_train_files = len(train_fnames) + + data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32) + x_array = np.zeros(w*h*num_train_files) + y_array = np.zeros(w*h*num_train_files) + file_prefix_array = np.zeros(w*h*num_train_files) + + for ind, file in enumerate(train_fnames): + print("Opening: " + file) + frames = read_h5(os.path.join(pathToH5s, file)) + frames = frames.reshape(-1, frames.shape[2], frames.shape[3]) + + data_array[ind*w*h:(ind+1)*w*h] = frames[..., :3] + x_array[ind*w*h:(ind+1)*w*h] = X.flatten() + y_array[ind*w*h:(ind+1)*w*h] = Y.flatten() + file_prefix_array[ind*w*h:(ind+1)*w*h] = ind + + p = np.random.permutation(data_array.shape[0]) + data_array = data_array[p] + x_array = x_array[p] + y_array = y_array[p] + file_prefix_array = file_prefix_array[p] + + + print("Outputting to files") + file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w') + dataset = file.create_dataset( + "dataset", data_array.shape, dtype='f', data=data_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "x.h5"), 'w') + dataset = file.create_dataset( + "dataset", x_array.shape, dtype='f', data=x_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "y.h5"), 'w') + dataset = file.create_dataset( + "dataset", y_array.shape, dtype='f', data=y_array + ) + file.close() + file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w') + dataset = file.create_dataset( + "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array + ) + file.close() + + +def bundle_rays_cap(pathToH5s, outputPath, trainJsonPath): + with open(trainJsonPath, "r") as fp: + meta = json.load(fp) + train_fnames = [] + for i in range(len(meta["frames"])): + frame = meta["frames"][i] + fname = frame["filepath"][:-2].split("/")[-1]+"mat" + train_fnames.append(fname) + + # frames = read_h5_dataset(os.path.join(pathToH5s, train_fnames[0])) + frames = mat73.loadmat(os.path.join(pathToH5s, train_fnames[0]))["transient"].transpose(1, 2, 0) + w = frames.shape[0] + h = frames.shape[1] + # bins = frames.shape[2] + bins = 3000 + + x = np.linspace(0, h-1, h) + y = np.linspace(0, w-1, w) + X, Y = np.meshgrid(x, y) + + # if len(frames.shape) == 4: + # channels = 3 + # else: + channels = 1 + num_train_files = len(train_fnames) + + data_array = np.zeros((w*h*num_train_files, bins, channels), dtype=np.float32) + x_array = np.zeros(w*h*num_train_files) + y_array = np.zeros(w*h*num_train_files) + file_prefix_array = np.zeros(w*h*num_train_files) + + for ind, file in enumerate(train_fnames): + print("Opening: " + file) + # frames = read_h5_dataset(os.path.join(pathToH5s, file)) + frames = mat73.loadmat(os.path.join(pathToH5s, file))["transient"].transpose(1, 2, 0) + frames = frames.reshape(-1, frames.shape[2]) + + data_array[ind*w*h:(ind+1)*w*h] = frames[..., :bins, None] + # del frames + x_array[ind*w*h:(ind+1)*w*h] = X.flatten() + y_array[ind*w*h:(ind+1)*w*h] = Y.flatten() + file_prefix_array[ind*w*h:(ind+1)*w*h] = ind + + p = np.random.permutation(data_array.shape[0]) + data_array = data_array[p] + x_array = x_array[p] + y_array = y_array[p] + file_prefix_array = file_prefix_array[p] + + + print("Outputting to files") + file = h5py.File(os.path.join(outputPath, "samples.h5"), 'w') + dataset = file.create_dataset( + "dataset", data_array.shape, dtype='f', data=data_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "x.h5"), 'w') + dataset = file.create_dataset( + "dataset", x_array.shape, dtype='f', data=x_array + ) + file.close() + + file = h5py.File(os.path.join(outputPath, "y.h5"), 'w') + dataset = file.create_dataset( + "dataset", y_array.shape, dtype='f', data=y_array + ) + file.close() + file = h5py.File(os.path.join(outputPath, "file_indices.h5"), 'w') + dataset = file.create_dataset( + "dataset", file_prefix_array.shape, dtype='f', data=file_prefix_array + ) + file.close() + +if __name__=="__main__": + pass \ No newline at end of file diff --git a/codes/reconstruction/trnerf/misc/summary.py b/codes/reconstruction/trnerf/misc/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..75b842665bbda7c4f46d26b14c48dc768b6ba186 --- /dev/null +++ b/codes/reconstruction/trnerf/misc/summary.py @@ -0,0 +1,147 @@ +import imgviz +import numpy as np +from utils import render_transient +import matplotlib.pyplot as plt +import torchvision +import torch +import os + + +def _atomic_torch_save(obj, path): + folder = os.path.dirname(path) or "." + os.makedirs(folder, exist_ok=True) + tmp_path = os.path.join(folder, "." + os.path.basename(path) + ".tmp") + torch.save(obj, tmp_path) + os.replace(tmp_path, path) + + +@torch.no_grad() +def write_summary_histogram(radiance_field, occupancy_grid, writer, test_dataset, step, render_step_size, args): + img_scale = args.img_scale + radiance_field.eval() + occupancy_grid.eval() + rgb_images = [] + depth_images = [] + gt_imgs = [] + accs = [] + + pixels_to_plot = args.pixels_to_plot + plotting_transients = [] + plotting_transients_depth = [] + + plotting_transients_gt = [] + mse_list = [] + + test_list = list(range(len(test_dataset))) + # if args.version == "simulated": + # color_channels = 3 + # else: + # color_channels = 1 + # n_output_dim = args.n_bins*(color_channels) + with torch.no_grad(): + + # sample transients from network + for ind, i in enumerate(test_list): + data = test_dataset[i] + render_bkgd = data["color_bkgd"] + rays = data["rays"] + pixels = data["pixels"] + pixels = pixels.reshape(rays.origins.shape[0], rays.origins.shape[1], -1, 3) + valid_mask = data.get("valid_mask", None) + if valid_mask is not None: + valid_mask = valid_mask.to(torch.bool).cpu() + if valid_mask.ndim == 1: + valid_mask = valid_mask.reshape(rays.origins.shape[0], rays.origins.shape[1]) + + + # # rendering + out = render_transient( + radiance_field, + occupancy_grid, + rays, + near_plane=args.near_plane, + far_plane=args.far_plane, + render_step_size=render_step_size, + cone_angle=args.cone_angle, + alpha_thre=args.alpha_thre, + use_normals = False, + args = args + ) + + rgb, acc, n_rendering_samples, comp_weights, depth = [out[key] for key in ['colors', 'opacities', 'n_rendering_samples', "comp_weights", "depths"]] + del out + + rgb = rgb.reshape(rays.origins.shape[0], rays.origins.shape[1], -1, 3) + + _atomic_torch_save(rgb, os.path.join(args.outpath, f"test_{ind}_conv.pt")) + _atomic_torch_save(depth, os.path.join(args.outpath, f"test_{ind}_depth.pt")) + + # if color_channels ==1: + # gt_imgs.append(torch.clip(pixels.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)) + # rgb_images.append(torch.clip(rgb.sum(-2).cpu().repeat(1, 1, 3).permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2)) + # else: + gt_img = torch.clip(pixels.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2) + rgb_img = torch.clip(rgb.sum(-2).cpu().permute(2, 0, 1)/img_scale, 0, 1)**(1/2.2) + if valid_mask is not None: + valid3 = valid_mask[None, ...].expand_as(gt_img) + gt_imgs.append(gt_img * valid3.to(gt_img.dtype)) + rgb_images.append(rgb_img * valid3.to(rgb_img.dtype)) + if valid3.any(): + mse_list.append(((gt_img - rgb_img) ** 2)[valid3].mean()) + else: + mse_list.append(torch.tensor(float("nan"))) + else: + gt_imgs.append(gt_img) + rgb_images.append(rgb_img) + mse_list.append(torch.mean((gt_img - rgb_img) ** 2)) + accs.append(acc.repeat(1, 1, 3).permute(2, 0, 1).cpu()) + dp = imgviz.depth2rgb(depth.cpu().squeeze().numpy(), colormap="inferno") + depth_images.append(torch.from_numpy(dp).permute(2, 0, 1)) + + if ind == 0: + for pixel in pixels_to_plot: + plotting_transients.append(rgb[pixel[0], pixel[1], :, 0]) + plotting_transients_gt.append(pixels[pixel[0], pixel[1], :, 0]) + plotting_transients_depth.append(depth[pixel[0], pixel[1]]) + + + images = torchvision.utils.make_grid(torch.stack(gt_imgs + rgb_images + depth_images + accs), nrow=len(test_list), normalize=False) + mse = torch.stack(mse_list) + valid_mse = torch.isfinite(mse) + if valid_mse.any(): + psnr = -10.0 * torch.log10(torch.clamp(mse[valid_mse], min=1e-12)) + print(f"image psnr (masked): {psnr.mean():.2f}\n") + writer.add_scalar("Metric/psnr_masked", psnr.mean().item(), step) + else: + print("image psnr (masked): nan (no valid pixels)\n") + writer.add_image('rgbdn', images, step) + + figure = plt.figure(figsize=((len(pixels_to_plot)+1), 4), dpi=250) + + # plot the predicted intensity + plt.subplot(2, (len(pixels_to_plot)+1)//2, 1) + plt.imshow(gt_imgs[0].permute(1, 2, 0)) + for i, pixel in enumerate(pixels_to_plot): + plt.plot(pixel[1], pixel[0], '.', markersize=10, color='red') + plt.text(pixel[1], pixel[0], str(i), color="yellow", fontsize=10) + plt.gca().set_aspect(1.0/plt.gca().get_data_ratio(), adjustable='box') + plt.title('gt intensity') + + for i, pixel in enumerate(pixels_to_plot): + # plot transients + plt.subplot(2, (len(pixels_to_plot)+1)//2, i+2) + plt.plot(np.arange(args.n_bins), plotting_transients[i].detach().cpu(), label='pred', linewidth=0.5) + plt.plot(np.arange(args.n_bins), plotting_transients_gt[i].detach().cpu(), label='gt', linewidth=0.5) + plt.axvline(x = (plotting_transients_depth[i]/args.exposure_time).detach().cpu().numpy(), color = 'y') + plt.title(f"pixel {i}") + plt.ylabel('intensity') + plt.legend(borderpad=0, labelspacing=0) + plt.gca().set_aspect(1.0 / plt.gca().get_data_ratio(), adjustable='box') + + plt.tight_layout() + writer.add_figure("transient_plots", figure, step) + + + radiance_field.train() + occupancy_grid.train() + diff --git a/codes/reconstruction/trnerf/misc/transient_volrend.py b/codes/reconstruction/trnerf/misc/transient_volrend.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2057c0da2996a903a9a607724d4b6e9c224890 --- /dev/null +++ b/codes/reconstruction/trnerf/misc/transient_volrend.py @@ -0,0 +1,620 @@ +from typing import Callable, Dict, Optional, Tuple +import torch +from torch import Tensor +from nerfacc.pack import pack_info +from nerfacc.scan import exclusive_prod, exclusive_sum +from torch_scatter import scatter_max +import math + + +def rendering_transient_single_path( + # ray marching results + t_starts: Tensor, + t_ends: Tensor, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + # radiance field + rgb_sigma_fn: Optional[Callable] = None, + # rendering options + render_bkgd: Optional[Tensor] = None, + args = None +): + + # Query sigma and color with gradients + data = rgb_sigma_fn(t_starts, t_ends, ray_indices.long()) + rgbs, sigmas = data + dists = (t_starts + t_ends)/2 + + if args.exp: + rgbs = torch.exp(rgbs)-1 + + + # Rendering: compute weights and ray indices. + weights_non_squared, transmittance, alphas = render_weight_from_density( + t_starts, + t_ends, + sigmas, + ray_indices=ray_indices, + n_rays=n_rays + ) + + # modelling squared transmittance + # alphas = 1 - torch.exp(-sigmas * (t_ends - t_starts)) + weights = (weights_non_squared ** 2 / (alphas.squeeze() + 1e-9)) + # Some iterations can have no alive samples after occupancy sampling. + # Return zero buffers directly to avoid downstream shape edge-cases. + if t_starts.numel() == 0: + device = weights.device + dtype = weights.dtype + colors = torch.zeros((n_rays, args.n_bins, 3), device=device, dtype=dtype) + opacities = torch.zeros((n_rays, 1), device=device, dtype=dtype) + depths = torch.zeros((n_rays, 1), device=device, dtype=dtype) + depths_variance = torch.zeros((n_rays, 1), device=device, dtype=dtype) + comp_weights = torch.zeros((n_rays, args.n_bins), device=device, dtype=dtype) + return colors, opacities, depths, depths_variance, comp_weights, rgbs + weights_non_squared = weights_non_squared.reshape(-1) + weights = weights.reshape(-1) + ray_indices = ray_indices.reshape(-1).long() + t_starts = t_starts.reshape(-1) + t_ends = t_ends.reshape(-1) + dists = dists.reshape(-1) + rgbs = rgbs.reshape(-1, rgbs.shape[-1]) + + # Safety guard for occasional invalid indices from upstream CUDA kernels. + valid = (ray_indices >= 0) & (ray_indices < int(n_rays)) + if not torch.all(valid): + weights_non_squared = weights_non_squared[valid] + weights = weights[valid] + ray_indices = ray_indices[valid] + t_starts = t_starts[valid] + t_ends = t_ends[valid] + dists = dists[valid] + rgbs = rgbs[valid] + if ray_indices.numel() == 0: + device = weights.device + dtype = weights.dtype + colors = torch.zeros((n_rays, args.n_bins, 3), device=device, dtype=dtype) + opacities = torch.zeros((n_rays, 1), device=device, dtype=dtype) + depths = torch.zeros((n_rays, 1), device=device, dtype=dtype) + depths_variance = torch.zeros((n_rays, 1), device=device, dtype=dtype) + comp_weights = torch.zeros((n_rays, args.n_bins), device=device, dtype=dtype) + return colors, opacities, depths, depths_variance, comp_weights, rgbs + + # r**2 fall off + src = weights[:, None] * rgbs + src = src/(dists[:, None].detach()**2 + 1e-10) + + if args.version == "simulated": + # this code bins the output samples into a tensor of size [n_rays, n_bins, 3] + tfilter_sigma = args.tfilter_sigma + bin_mapping, dist_weights = mapping_dist_to_bin_mitsuba(dists, args.n_bins, args.exposure_time, c=1, sigma=tfilter_sigma) + src = (dist_weights[..., None] * src[:, None, :]).flatten(0, 1) + colors = torch.zeros((n_rays * args.n_bins, 3), device=weights.device) + index = ((torch.repeat_interleave(ray_indices, 8*tfilter_sigma) * args.n_bins) + bin_mapping.flatten().long())[:, None].expand(-1, 3).long() + colors.scatter_add_(0, index, src) + colors = colors.view(n_rays, args.n_bins, 3) + bin_numbers_floor, bin_numbers_ceil, alpha = mapping_dist_to_bin(dists, args.n_bins, args.exposure_time) + index_f = ((ray_indices * args.n_bins) + bin_numbers_floor.long())[:, None].expand(-1, 3).long() + index = index_f + + + if args.version == "captured": + bin_numbers_floor, bin_numbers_ceil, _ = mapping_dist_to_bin(dists, args.n_bins, args.exposure_time) + colors = torch.zeros((n_rays * args.n_bins, 3), device=weights.device) + index = ((ray_indices * args.n_bins) + bin_numbers_floor.long())[:, None].expand(-1, 3).long() + colors.scatter_add_(0, index, src) + colors = colors.view(n_rays, args.n_bins, 3) + colors = convolve_colour(colors, args.laser_kernel, n_bins=args.n_bins) + + + + # do the same for the sigmas + comp_weights = torch.zeros((n_rays * args.n_bins, 1), device=weights.device) + comp_weights.scatter_add_(0, index[:, [0]], weights_non_squared[:, None]) + comp_weights = comp_weights.reshape(n_rays, args.n_bins) + + + opacities = accumulate_along_rays( + weights, values=None, ray_indices=ray_indices, n_rays=n_rays + ) + + + out, argmax = scatter_max(weights_non_squared, ray_indices, out=torch.zeros(n_rays, device=ray_indices.device)) + + if t_starts.shape[0]!=0: + argmax[argmax==weights.shape[0]] = weights.shape[0]-1 + depths = (t_starts+t_ends)[argmax]/2 + else: + depths = out[:, None] + + to_accum_var = ((t_ends + t_starts) / 2 - depths.reshape(-1)[ray_indices]) ** 2 + depths_variance = accumulate_along_rays( + weights_non_squared.reshape(-1), + ray_indices=ray_indices, + values=to_accum_var.reshape(-1, 1), + n_rays=n_rays, + ) + depths_variance = depths_variance/(opacities+1e-10) + + + return colors, opacities, depths, depths_variance, comp_weights, rgbs + + +def mapping_dist_to_bin_mitsuba(dists, n_bins, exposure_time, c=1, sigma=5): + times = 2 * dists / c + ratio = times / exposure_time + ranges = torch.arange(0, 8 * sigma, device=dists.device)[None, :].repeat(ratio.shape[0], 1) + bin_mapping = (torch.ceil(ratio-4*sigma))[:, None]+ranges + ranges = bin_mapping - ratio[:, None] + dist_weights = torch.exp(-ranges**2/(2*sigma**2))-math.exp(-8) + + dist_weights[(bin_mapping<0) ] = 0 + dist_weights[(bin_mapping>n_bins) ] = 0 + + bin_mapping = torch.clip(bin_mapping, 0, n_bins-1) + dist_weights = (dist_weights.T/(dist_weights.sum(-1)[: None]+1e-10)).T + return bin_mapping, dist_weights + + +def mapping_dist_to_bin(dists, n_bins, exposure_time, c=1): + times = 2 * dists / c + # (torch.randn(times.shape[0])*7).to("cuda") + ratio = times / exposure_time + alpha = (torch.ceil(ratio) - ratio) / (torch.ceil(ratio) - torch.floor(ratio) + 1e-10) + + bin_numbers_floor = torch.floor(ratio) + bin_numbers_ceil = torch.ceil(ratio) + # if torch.max(bin_numbers)>bin_length: + # print("hello") + bin_numbers_floor = torch.clip(bin_numbers_floor, 0, n_bins - 1) + bin_numbers_ceil = torch.clip(bin_numbers_ceil, 0, n_bins - 1) + + return bin_numbers_floor, bin_numbers_ceil, alpha + + +def render_transmittance_from_alpha( + alphas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tensor: + """Compute transmittance :math:`T_i` from alpha :math:`\\alpha_i`. + + .. math:: + T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering transmittance with the same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices) + tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0]) + """ + if ray_indices is not None and packed_info is None: + packed_info = pack_info(ray_indices, n_rays) + + trans = exclusive_prod(1 - alphas, packed_info) + if prefix_trans is not None: + trans *= prefix_trans + return trans + +def convolve_colour(color, kernel, n_bins): + color = color.transpose(1, 2).reshape(-1, n_bins) + color = kernel(color[:, None, :]).squeeze() + color = color.reshape(-1, 3, n_bins).transpose(1, 2) + return color + +def torch_laser_kernel(laser, device='cuda'): + m = torch.nn.Conv1d(1, 1, laser.shape[0], padding=(laser.shape[0] - 1) // 2, padding_mode="zeros", device=device) + m.weight.requires_grad = False + m.bias.requires_grad = False + m.bias *= 0 + m.weight = torch.nn.Parameter(laser[None, None, ...]) + return m + +def render_transmittance_from_density( + t_starts: Tensor, + t_ends: Tensor, + sigmas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Compute transmittance :math:`T_i` from density :math:`\\sigma_i`. + + .. math:: + T_i = exp(-\\sum_{j=1}^{i-1}\\sigma_j\delta_j) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + t_starts: Where the frustum-shape sample starts along a ray. Tensor with \ + shape (all_samples,) or (n_rays, n_samples). + t_ends: Where the frustum-shape sample ends along a ray. Tensor with \ + shape (all_samples,) or (n_rays, n_samples). + sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering transmittance and opacities, both with the same shape as `sigmas`. + + Examples: + + .. code-block:: python + + >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda") + >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda") + >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance, alphas = render_transmittance_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices) + transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00] + alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59] + + """ + if ray_indices is not None and packed_info is None: + packed_info = pack_info(ray_indices, n_rays) + + sigmas_dt = sigmas * (t_ends - t_starts) + alphas = 1.0 - torch.exp(-sigmas_dt) + trans = torch.exp(-exclusive_sum(sigmas_dt, packed_info)) + if prefix_trans is not None: + trans *= prefix_trans + return trans, alphas + + +def render_weight_from_alpha( + alphas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Compute rendering weights :math:`w_i` from opacity :math:`\\alpha_i`. + + .. math:: + w_i = T_i\\alpha_i, \\quad\\textrm{where}\\quad T_i = \\prod_{j=1}^{i-1}(1-\\alpha_j) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering weights and transmittance, both with the same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> weights, transmittance = render_weight_from_alpha(alphas, ray_indices=ray_indices) + weights: [0.4, 0.48, 0.012, 0.8, 0.02, 0.0, 0.9]) + transmittance: [1.00, 0.60, 0.12, 1.00, 0.20, 1.00, 1.00] + + """ + trans = render_transmittance_from_alpha( + alphas, packed_info, ray_indices, n_rays, prefix_trans + ) + weights = trans * alphas + return weights, trans + + +def render_weight_from_density( + t_starts: Tensor, + t_ends: Tensor, + sigmas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + prefix_trans: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor, Tensor]: + """Compute rendering weights :math:`w_i` from density :math:`\\sigma_i` and interval :math:`\\delta_i`. + + .. math:: + 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) + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + t_starts: The start time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + t_ends: The end time of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + sigmas: The density values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + The rendering weights, transmittance and opacities, both with the same shape as `sigmas`. + + Examples: + + .. code-block:: python + + >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda") + >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda") + >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> weights, transmittance, alphas = render_weight_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices) + weights: [0.33, 0.37, 0.03, 0.55, 0.04, 0.00, 0.59] + transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00] + alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59] + + """ + trans, alphas = render_transmittance_from_density( + t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans + ) + weights = trans * alphas + return weights, trans, alphas + + +@torch.no_grad() +def render_visibility_from_alpha( + alphas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + early_stop_eps: float = 1e-4, + alpha_thre: float = 0.0, + prefix_trans: Optional[Tensor] = None, +) -> Tensor: + """Compute visibility from opacity :math:`\\alpha_i`. + + In this function, we first compute the transmittance from the sample opacity. The + transmittance is then used to filter out occluded samples. And opacity is used to + filter out transparent samples. The function returns a boolean tensor indicating + which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`). + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + early_stop_eps: The early stopping threshold on transmittance. + alpha_thre: The threshold on opacity. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + A boolean tensor indicating which samples are visible. Same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> alphas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance = render_transmittance_from_alpha(alphas, ray_indices=ray_indices) + tensor([1.0, 0.6, 0.12, 1.0, 0.2, 1.0, 1.0]) + >>> visibility = render_visibility_from_alpha( + >>> alphas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2) + tensor([True, True, False, True, False, False, True]) + + """ + trans = render_transmittance_from_alpha( + alphas, packed_info, ray_indices, n_rays, prefix_trans + ) + vis = trans >= early_stop_eps + if alpha_thre > 0: + vis = vis & (alphas >= alpha_thre) + return vis + + +@torch.no_grad() +def render_visibility_from_density( + t_starts: Tensor, + t_ends: Tensor, + sigmas: Tensor, + packed_info: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, + early_stop_eps: float = 1e-4, + alpha_thre: float = 0.0, + prefix_trans: Optional[Tensor] = None, +) -> Tensor: + """Compute visibility from density :math:`\\sigma_i` and interval :math:`\\delta_i`. + + In this function, we first compute the transmittance and opacity from the sample density. The + transmittance is then used to filter out occluded samples. And opacity is used to + filter out transparent samples. The function returns a boolean tensor indicating + which samples are visible (`transmittance > early_stop_eps` and `opacity > alpha_thre`). + + This function supports both batched and flattened input tensor. For flattened input tensor, either + (`packed_info`) or (`ray_indices` and `n_rays`) should be provided. + + Args: + alphas: The opacity values of the samples. Tensor with shape (all_samples,) or (n_rays, n_samples). + packed_info: A tensor of shape (n_rays, 2) that specifies the start and count + of each chunk in the flattened samples, with in total n_rays chunks. + Useful for flattened input. + ray_indices: Ray indices of the flattened samples. LongTensor with shape (all_samples). + n_rays: Number of rays. Only useful when `ray_indices` is provided. + early_stop_eps: The early stopping threshold on transmittance. + alpha_thre: The threshold on opacity. + prefix_trans: The pre-computed transmittance of the samples. Tensor with shape (all_samples,). + + Returns: + A boolean tensor indicating which samples are visible. Same shape as `alphas`. + + Examples: + + .. code-block:: python + + >>> t_starts = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], device="cuda") + >>> t_ends = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], device="cuda") + >>> sigmas = torch.tensor([0.4, 0.8, 0.1, 0.8, 0.1, 0.0, 0.9], device="cuda") + >>> ray_indices = torch.tensor([0, 0, 0, 1, 1, 2, 2], device="cuda") + >>> transmittance, alphas = render_transmittance_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices) + transmittance: [1.00, 0.67, 0.30, 1.00, 0.45, 1.00, 1.00] + alphas: [0.33, 0.55, 0.095, 0.55, 0.095, 0.00, 0.59] + >>> visibility = render_visibility_from_density( + >>> t_starts, t_ends, sigmas, ray_indices=ray_indices, early_stop_eps=0.3, alpha_thre=0.2) + tensor([True, True, False, True, False, False, True]) + + """ + trans, alphas = render_transmittance_from_density( + t_starts, t_ends, sigmas, packed_info, ray_indices, n_rays, prefix_trans + ) + vis = trans >= early_stop_eps + if alpha_thre > 0: + vis = vis & (alphas >= alpha_thre) + return vis + + +def accumulate_along_rays( + weights: Tensor, + values: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + n_rays: Optional[int] = None, +) -> Tensor: + """Accumulate volumetric values along the ray. + + This function supports both batched inputs and flattened inputs with + `ray_indices` and `n_rays` provided. + + Note: + This function is differentiable to `weights` and `values`. + + Args: + weights: Weights to be accumulated. If `ray_indices` not provided, + `weights` must be batched with shape (n_rays, n_samples). Else it + must be flattened with shape (all_samples,). + values: Values to be accumulated. If `ray_indices` not provided, + `values` must be batched with shape (n_rays, n_samples, D). Else it + must be flattened with shape (all_samples, D). None means + we accumulate weights along rays. Default: None. + ray_indices: Ray indices of the samples with shape (all_samples,). + If provided, `weights` must be a flattened tensor with shape (all_samples,) + and values (if not None) must be a flattened tensor with shape (all_samples, D). + Default: None. + n_rays: Number of rays. Should be provided together with `ray_indices`. Default: None. + + Returns: + Accumulated values with shape (n_rays, D). If `values` is not given we return + the accumulated weights, in which case D == 1. + + Examples: + + .. code-block:: python + + # Rendering: accumulate rgbs, opacities, and depths along the rays. + colors = accumulate_along_rays(weights, rgbs, ray_indices, n_rays) + opacities = accumulate_along_rays(weights, None, ray_indices, n_rays) + depths = accumulate_along_rays( + weights, + (t_starts + t_ends)[:, None] / 2.0, + ray_indices, + n_rays, + ) + # (n_rays, 3), (n_rays, 1), (n_rays, 1) + print(colors.shape, opacities.shape, depths.shape) + + """ + if values is None: + src = weights[..., None] + else: + assert values.dim() == weights.dim() + 1 + assert weights.shape == values.shape[:-1] + src = weights[..., None] * values + if ray_indices is not None: + assert n_rays is not None, "n_rays must be provided" + assert weights.dim() == 1, "weights must be flattened" + outputs = torch.zeros( + (n_rays, src.shape[-1]), device=src.device, dtype=src.dtype + ) + outputs.index_add_(0, ray_indices, src) + else: + outputs = torch.sum(src, dim=-2) + return outputs + + +def accumulate_along_rays_( + weights: Tensor, + values: Optional[Tensor] = None, + ray_indices: Optional[Tensor] = None, + outputs: Optional[Tensor] = None, +) -> None: + """Accumulate volumetric values along the ray. + + Inplace version of :func:`accumulate_along_rays`. + """ + if weights.shape[0] == 0: + return 0 + if values is None: + src = weights[..., None] + else: + assert values.dim() == weights.dim() + 1 + assert weights.shape == values.shape[:-1] + src = weights[..., None] * values + if ray_indices is not None: + # assert weights.dim() == 1, "weights must be flattened" + # assert ( + # outputs.dim() == 2 and outputs.shape[-1] == src.shape[-1] + # ), "outputs must be of shape (n_rays, D)" + outputs.index_add_(0, ray_indices, src) + else: + outputs.add_(src.sum(dim=-2)) + + +def shift_transient_grid_sample_3d(transient, depth, exposure_time, n_bins): + x_dim = transient.shape[0] + bins_move = depth/exposure_time + if x_dim%2 == 0: + x = (torch.arange(x_dim, device=transient.device)-x_dim//2+0.5)/(x_dim//2-0.5) + else: + x = (torch.arange(x_dim, device=transient.device)-x_dim//2)/(x_dim//2) + + if x_dim == 1: + x = torch.zeros_like(x) + + z = torch.arange(n_bins, device=transient.device).float() + X, Z = torch.meshgrid(x, z, indexing="ij") + Z = Z - bins_move + Z[Z<0] = n_bins+1 + Z = (Z-n_bins//2+0.5)/(n_bins//2-0.5) + grid = torch.stack((Z, X), dim=-1)[None, ...] + shifted_transient = torch.nn.functional.grid_sample(transient.permute(2, 0, 1)[None], grid, align_corners=True).squeeze(0).permute(1, 2, 0) + return shifted_transient diff --git a/codes/reconstruction/trnerf/radiance_fields/__init__.py b/codes/reconstruction/trnerf/radiance_fields/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/codes/reconstruction/trnerf/radiance_fields/__pycache__/__init__.cpython-312.pyc b/codes/reconstruction/trnerf/radiance_fields/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bb6433090344c3f6cda2fbe5a0d9881812f23ec Binary files /dev/null and b/codes/reconstruction/trnerf/radiance_fields/__pycache__/__init__.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/radiance_fields/__pycache__/ngp.cpython-312.pyc b/codes/reconstruction/trnerf/radiance_fields/__pycache__/ngp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d90770bd0a6a9803bf10c441bb3328ee1b85584 Binary files /dev/null and b/codes/reconstruction/trnerf/radiance_fields/__pycache__/ngp.cpython-312.pyc differ diff --git a/codes/reconstruction/trnerf/radiance_fields/ngp.py b/codes/reconstruction/trnerf/radiance_fields/ngp.py new file mode 100644 index 0000000000000000000000000000000000000000..04d869751d567b22dcfc1a932bf22d1dac38d302 --- /dev/null +++ b/codes/reconstruction/trnerf/radiance_fields/ngp.py @@ -0,0 +1,299 @@ +""" +Copyright (c) 2022 Ruilong Li, UC Berkeley. +""" + +from typing import Callable, List, Union + +import numpy as np +import torch +from torch.autograd import Function +from torch.cuda.amp import custom_bwd, custom_fwd +import torch.nn.functional as F + +try: + import tinycudann as tcnn +except ImportError as e: + print( + f"Error: {e}! " + "Please install tinycudann by: " + "pip install git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch" + ) + exit() + + +class _TruncExp(Function): # pylint: disable=abstract-method + # Implementation from torch-ngp: + # https://github.com/ashawkey/torch-ngp/blob/93b08a0d4ec1cc6e69d85df7f0acdfb99603b628/activation.py + @staticmethod + @custom_fwd(cast_inputs=torch.float32) + def forward(ctx, x): # pylint: disable=arguments-differ + ctx.save_for_backward(x) + return torch.exp(x) + + @staticmethod + @custom_bwd + def backward(ctx, g): # pylint: disable=arguments-differ + x = ctx.saved_tensors[0] + return g * torch.exp(torch.clamp(x, max=15)) + + +trunc_exp = _TruncExp.apply + + +def contract_to_unisphere( + x: torch.Tensor, + aabb: torch.Tensor, + ord: Union[str, int] = 2, + # ord: Union[float, int] = float("inf"), + eps: float = 1e-6, + derivative: bool = False, +): + aabb_min, aabb_max = torch.split(aabb, 3, dim=-1) + x = (x - aabb_min) / (aabb_max - aabb_min) + x = x * 2 - 1 # aabb is at [-1, 1] + mag = torch.linalg.norm(x, ord=ord, dim=-1, keepdim=True) + mask = mag.squeeze(-1) > 1 + + if derivative: + dev = (2 * mag - 1) / mag**2 + 2 * x**2 * ( + 1 / mag**3 - (2 * mag - 1) / mag**4 + ) + dev[~mask] = 1.0 + dev = torch.clamp(dev, min=eps) + return dev + else: + x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask]) + x = x / 4 + 0.5 # [-inf, inf] is at [0, 1] + return x + + +class NGPRadianceField(torch.nn.Module): + """Instance-NGP Radiance Field""" + + def __init__( + self, + aabb: Union[torch.Tensor, List[float]], + num_dim: int = 3, + use_viewdirs: bool = True, + density_activation: Callable = lambda x: trunc_exp(x - 1), + radiance_activation: Callable = lambda x: F.sigmoid(x), + unbounded: bool = False, + base_resolution: int = 16, + max_resolution: int = 4096, + geo_feat_dim: int = 15, + n_levels: int = 16, + log2_hashmap_size: int = 19, + args = None + ) -> None: + super().__init__() + if not isinstance(aabb, torch.Tensor): + aabb = torch.tensor(aabb, dtype=torch.float32) + self.register_buffer("aabb", aabb) + self.num_dim = num_dim + self.radiance_activation = radiance_activation + self.use_viewdirs = use_viewdirs + self.density_activation = density_activation + self.unbounded = unbounded + self.base_resolution = base_resolution + self.max_resolution = max_resolution + self.geo_feat_dim = geo_feat_dim + self.n_levels = n_levels + self.log2_hashmap_size = log2_hashmap_size + self.version = args.version + self.radiance_activation = radiance_activation + self.n_output_dim = 3 + + + + + per_level_scale = np.exp( + (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1) + ).tolist() + + if self.use_viewdirs: + self.direction_encoding = tcnn.Encoding( + n_input_dims=num_dim, + encoding_config={ + "otype": "Composite", + "nested": [ + { + "n_dims_to_encode": 3, + "otype": "SphericalHarmonics", + "degree": 4, + }, + # {"otype": "Identity", "n_bins": 4, "degree": 4}, + ], + }, + ) + + self.mlp_base = tcnn.NetworkWithInputEncoding( + n_input_dims=num_dim, + n_output_dims=1 + self.geo_feat_dim, + encoding_config={ + "otype": "HashGrid", + "n_levels": n_levels, + "n_features_per_level": 2, + "log2_hashmap_size": log2_hashmap_size, + "base_resolution": base_resolution, + "per_level_scale": per_level_scale, + }, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 1, + }, + ) + if self.geo_feat_dim > 0: + self.mlp_head = tcnn.Network( + n_input_dims=( + ( + self.direction_encoding.n_output_dims + if self.use_viewdirs + else 0 + ) + + self.geo_feat_dim + ), + n_output_dims=self.n_output_dim, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 2, + }, + ) + + def query_density(self, x, return_feat: bool = False): + if self.unbounded: + x = contract_to_unisphere(x, self.aabb) + else: + aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1) + x = (x - aabb_min) / (aabb_max - aabb_min) + selector = ((x > 0.0) & (x < 1.0)).all(dim=-1) + x = ( + self.mlp_base(x.view(-1, self.num_dim)) + .view(list(x.shape[:-1]) + [1 + self.geo_feat_dim]) + .to(x) + ) + density_before_activation, base_mlp_out = torch.split( + x, [1, self.geo_feat_dim], dim=-1 + ) + density = ( + self.density_activation(density_before_activation) + * selector[..., None] + ) + if return_feat: + return density, base_mlp_out + else: + return density + + def _query_rgb(self, dir, embedding, apply_act: bool = True): + # tcnn requires directions in the range [0, 1] + if self.use_viewdirs: + dir = (dir + 1.0) / 2.0 + d = self.direction_encoding(dir.reshape(-1, dir.shape[-1])) + h = torch.cat([d, embedding.reshape(-1, self.geo_feat_dim)], dim=-1) + else: + h = embedding.reshape(-1, self.geo_feat_dim) + rgb = ( + self.mlp_head(h) + .reshape(list(embedding.shape[:-1]) + [self.n_output_dim]) + .to(embedding) + ) + if apply_act: + rgb = self.radiance_activation(rgb) + + return rgb + + def forward( + self, + positions: torch.Tensor, + directions: torch.Tensor = None, + ): + if positions.shape[0] == 0: + density = torch.zeros(0, device=positions.device) + color = torch.zeros(0, 1200, device=positions.device) + return color, density + + if self.use_viewdirs and (directions is not None): + assert ( + positions.shape == directions.shape + ), f"{positions.shape} v.s. {directions.shape}" + density, embedding = self.query_density(positions, return_feat=True) + rgb = self._query_rgb(directions, embedding=embedding) + else: + density, embedding = self.query_density(positions, return_feat=True) + rgb = self._query_rgb(directions, embedding=embedding) + return rgb, density # type: ignore + + +class NGPDensityField(torch.nn.Module): + """Instance-NGP Density Field used for resampling""" + + def __init__( + self, + aabb: Union[torch.Tensor, List[float]], + num_dim: int = 3, + density_activation: Callable = lambda x: trunc_exp(x - 1), + unbounded: bool = False, + base_resolution: int = 16, + max_resolution: int = 128, + n_levels: int = 5, + log2_hashmap_size: int = 17, + ) -> None: + super().__init__() + if not isinstance(aabb, torch.Tensor): + aabb = torch.tensor(aabb, dtype=torch.float32) + self.register_buffer("aabb", aabb) + self.num_dim = num_dim + self.density_activation = density_activation + self.unbounded = unbounded + self.base_resolution = base_resolution + self.max_resolution = max_resolution + self.n_levels = n_levels + self.log2_hashmap_size = log2_hashmap_size + + per_level_scale = np.exp( + (np.log(max_resolution) - np.log(base_resolution)) / (n_levels - 1) + ).tolist() + + self.mlp_base = tcnn.NetworkWithInputEncoding( + n_input_dims=num_dim, + n_output_dims=1, + encoding_config={ + "otype": "HashGrid", + "n_levels": n_levels, + "n_features_per_level": 2, + "log2_hashmap_size": log2_hashmap_size, + "base_resolution": base_resolution, + "per_level_scale": per_level_scale, + }, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 1, + }, + ) + + def forward(self, positions: torch.Tensor): + if self.unbounded: + positions = contract_to_unisphere(positions, self.aabb) + else: + aabb_min, aabb_max = torch.split(self.aabb, self.num_dim, dim=-1) + positions = (positions - aabb_min) / (aabb_max - aabb_min) + selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1) + density_before_activation = ( + self.mlp_base(positions.view(-1, self.num_dim)) + .view(list(positions.shape[:-1]) + [1]) + .to(positions) + ) + density = ( + self.density_activation(density_before_activation) + * selector[..., None] + ) + return density + \ No newline at end of file diff --git a/codes/reconstruction/trnerf/requirements.txt b/codes/reconstruction/trnerf/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..30f33abc3975082f988b469f1da26d3ec6c5dd81 --- /dev/null +++ b/codes/reconstruction/trnerf/requirements.txt @@ -0,0 +1,25 @@ +# Install PyTorch 2.5.1 / CUDA 11.8 first; see README. +ConfigArgParse==1.7.5 +ImageIO==2.37.2 +Pillow==9.4.0 +PyYAML==6.0.2 +h5py==3.14.0 +imgviz==1.7.6 +lpips==0.1.4 +mat73==0.65 +matplotlib==3.9.4 +nerfacc==0.5.3 +numpy==1.26.4 +packaging==26.0 +pandas==2.3.3 +scikit-image==0.24.0 +scipy==1.13.1 +sparse==0.15.5 +tensorboard==2.10.1 +torch==2.5.1 +torchvision==0.20.1 +tqdm==4.67.3 + +# CUDA extensions (install after PyTorch; source build needs the CUDA toolchain). +torch_scatter==2.1.2 +tinycudann @ git+https://github.com/NVlabs/tiny-cuda-nn@2e757bbe781db59c4980d389d7dccbf5edc09669#subdirectory=bindings/torch diff --git a/codes/reconstruction/trnerf/train_ours.py b/codes/reconstruction/trnerf/train_ours.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d86a89e8af895bb6904ae425f56e19854bfbb0 --- /dev/null +++ b/codes/reconstruction/trnerf/train_ours.py @@ -0,0 +1,572 @@ +import math +import os + +import configargparse +import numpy as np +import pandas as pd +import scipy.io as sio +import torch +import torch.multiprocessing as mp +import tqdm +from nerfacc.estimators.occ_grid import OccGridEstimator +from torch.utils.tensorboard import SummaryWriter + +from misc.summary import write_summary_histogram +from misc.transient_volrend import torch_laser_kernel +from radiance_fields.ngp import NGPRadianceField +from utils import ( + load_args, + make_save_folder, + make_save_folder_final, + render_transient, + set_random_seed, +) + +if mp.get_start_method(allow_none=True) is None: + mp.set_start_method("spawn") + + +def load_args_ours(): + parser = configargparse.ArgumentParser() + parser.add_argument('--skip_train_summaries', action='store_true') + parser.add_argument( + "--irf_path", + type=str, + default="", + help="Path to IRF file. Supports .csv/.npy/.mat/.pt. If empty, fallback to --pulse_path.", + ) + parser.add_argument( + "--irf_column", + type=str, + default="irf", + help="CSV column name for IRF values.", + ) + parser.add_argument( + "--irf_half_window", + type=int, + default=50, + help="Half window size for cropping around IRF peak. Set <=0 to disable crop.", + ) + parser.add_argument( + "--no_irf_reverse", + action="store_true", + help="Disable reverse before Conv1d kernel creation.", + ) + parser.add_argument( + "--measurement_root", + type=str, + default="", + help="Optional root directory of measurement files (.npz/.txt/.pt/.h5).", + ) + parser.add_argument( + "--data_exts", + type=str, + default=".npz,.txt,.pt,.h5,.hdf5", + help="Comma-separated measurement extensions lookup order.", + ) + parser.add_argument( + "--bin_width_s_loader", + type=float, + default=None, + help="Bin width in seconds for shift resampling. If empty, derived from exposure_time / c.", + ) + parser.add_argument( + "--img_height", + type=int, + default=None, + help="Training image height. If empty, use --img_shape.", + ) + parser.add_argument( + "--img_width", + type=int, + default=None, + help="Training image width. If empty, use --img_shape.", + ) + parser.add_argument( + "--img_height_test", + type=int, + default=None, + help="Test image height. If empty, use --img_shape_test.", + ) + parser.add_argument( + "--img_width_test", + type=int, + default=None, + help="Test image width. If empty, use --img_shape_test.", + ) + parser.add_argument( + "--meas_peak_min", + type=float, + default=100.0, + help=( + "Minimum raw histogram peak per pixel to keep it in photometric loss. " + "<=0 disables this mask. Threshold is interpreted in pre-normalization measurement scale." + ), + ) + parser.add_argument( + "--invalid_mask_path", + type=str, + default="", + help=( + "Path to offset map used to build valid-pixel mask. " + "Pixels with offset > invalid_mask_invalid_gt are excluded from training/eval." + ), + ) + parser.add_argument( + "--invalid_mask_invalid_gt", + type=float, + default=10.0, + help="Offset threshold for invalid pixels in invalid_mask_path.", + ) + return load_args(eval=True, parser=parser) + + +def _to_numpy(x): + if isinstance(x, np.ndarray): + return x + if isinstance(x, torch.Tensor): + return x.detach().cpu().numpy() + return np.asarray(x) + + +def _load_irf_series(path: str, column: str) -> np.ndarray: + ext = os.path.splitext(path)[1].lower() + if ext == ".csv": + df = pd.read_csv(path, sep=",") + if column in df.columns: + arr = df[column].to_numpy(dtype=np.float64) + else: + numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)] + if not numeric_cols: + raise ValueError(f"No numeric columns found in IRF CSV: {path}") + arr = df[numeric_cols[0]].to_numpy(dtype=np.float64) + return arr.squeeze() + if ext == ".npy": + return np.load(path).astype(np.float64).squeeze() + if ext == ".mat": + mat = sio.loadmat(path) + if "out" in mat: + return _to_numpy(mat["out"]).astype(np.float64).squeeze() + for value in mat.values(): + if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1: + return _to_numpy(value).astype(np.float64).squeeze() + raise ValueError(f"Cannot find valid IRF series in mat file: {path}") + if ext == ".pt": + return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze() + raise ValueError(f"Unsupported IRF extension: {ext}") + + +def build_irf_kernel(args, device): + irf_path = args.irf_path if args.irf_path else args.pulse_path + if not irf_path: + raise ValueError("IRF path is empty. Set --irf_path or --pulse_path.") + + irf = _load_irf_series(irf_path, args.irf_column) + if irf.ndim != 1: + irf = irf.reshape(-1) + if irf.size == 0: + raise ValueError(f"Loaded empty IRF from: {irf_path}") + + peak_idx = int(np.argmax(irf)) + if args.irf_half_window and args.irf_half_window > 0: + lo = max(0, peak_idx - int(args.irf_half_window)) + hi = min(len(irf), peak_idx + int(args.irf_half_window) + 1) + irf = irf[lo:hi] + + irf = irf / (irf.sum() + 1e-8) + if not args.no_irf_reverse: + irf = irf[::-1].copy() + + laser = torch.tensor(irf, dtype=torch.float32, device=device) + return torch_laser_kernel(laser, device=device) + + +def run(): + args = load_args_ours() + device = torch.device(args.device) + args.device = str(device) + if device.type == "cuda": + if not torch.cuda.is_available(): + raise RuntimeError(f"CUDA device requested but CUDA is unavailable: {device}") + torch.cuda.set_device(device) + torch.cuda.empty_cache() + set_random_seed(args.seed) + + train_h = int(args.img_height) if args.img_height is not None else int(args.img_shape) + train_w = int(args.img_width) if args.img_width is not None else int(args.img_shape) + test_h = int(args.img_height_test) if args.img_height_test is not None else int(args.img_shape_test) + test_w = int(args.img_width_test) if args.img_width_test is not None else int(args.img_shape_test) + img_shape = (train_h, train_w) + img_shape_test = (test_h, test_w) + + aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device) + train_dataset_kwargs = {} + test_dataset_kwargs = {} + + rfilter_sigma = args.rfilter_sigma + max_steps = args.max_steps + sample_as_per_distribution = args.sample_as_per_distribution + target_sample_batch_size = 1 << 16 + + if args.version == "simulated": + from loaders.loader_synthetic import SubjectLoaderTransient as SubjectLoader + + test_dataset_kwargs = { + "img_shape": img_shape_test, + "have_images": True, + "n_bins": args.n_bins, + "color_bkgd_aug": "black", + "rfilter_sigma": rfilter_sigma, + "sample_as_per_distribution": sample_as_per_distribution, + } + train_dataset_kwargs = { + "img_shape": img_shape, + "n_bins": args.n_bins, + "color_bkgd_aug": "black", + "rfilter_sigma": rfilter_sigma, + "sample_as_per_distribution": sample_as_per_distribution, + } + + train_dataset = SubjectLoader( + root_fp=args.data_root_fp, + subject_id=args.exp_name, + split="train", + num_rays=target_sample_batch_size // args.render_n_samples, + **train_dataset_kwargs, + num_views=args.num_views, + ) + train_dataset.camtoworlds = train_dataset.camtoworlds.to(device) + train_dataset.K = train_dataset.K.to(device) + + if not args.skip_train_summaries: + test_dataset = SubjectLoader( + root_fp=args.data_root_fp, + subject_id=args.exp_name, + split="test", + num_rays=None, + **test_dataset_kwargs, + ) + if test_dataset_kwargs["have_images"]: + test_dataset.images = test_dataset.images.to(device) + test_dataset.camtoworlds = test_dataset.camtoworlds.to(device) + test_dataset.K = test_dataset.K.to(device) + else: + from loaders.loader_captured_ours import LearnRays, SubjectLoaderTransientRealOurs as SubjectLoader + + params = np.load(args.intrinsics, allow_pickle=True)[()] + shift = _to_numpy(params["shift"]) + rays = _to_numpy(params["rays"]) + source_img_shape = (int(rays.shape[0]), int(rays.shape[1])) + + measurement_root = args.measurement_root.strip() or None + invalid_mask_path = args.invalid_mask_path.strip() or None + data_exts = tuple(e.strip() for e in args.data_exts.split(",") if e.strip()) + if args.bin_width_s_loader is not None: + bin_width_s_loader = float(args.bin_width_s_loader) + else: + bin_width_s_loader = float(args.exposure_time) / 299792458.0 + + test_dataset_kwargs = { + "img_shape": img_shape_test, + "have_images": True, + "n_bins": args.n_bins, + "color_bkgd_aug": "black", + "rfilter_sigma": rfilter_sigma, + "sample_as_per_distribution": sample_as_per_distribution, + "shift": shift, + "measurement_root": measurement_root, + "data_exts": data_exts, + "bin_width_s": bin_width_s_loader, + "source_img_shape": source_img_shape, + "invalid_mask_path": invalid_mask_path, + "invalid_mask_invalid_gt": float(args.invalid_mask_invalid_gt), + } + train_dataset_kwargs = { + "img_shape": img_shape, + "n_bins": args.n_bins, + "color_bkgd_aug": "black", + "rfilter_sigma": rfilter_sigma, + "sample_as_per_distribution": sample_as_per_distribution, + "shift": shift, + "measurement_root": measurement_root, + "data_exts": data_exts, + "bin_width_s": bin_width_s_loader, + "source_img_shape": source_img_shape, + "invalid_mask_path": invalid_mask_path, + "invalid_mask_invalid_gt": float(args.invalid_mask_invalid_gt), + } + + train_dataset = SubjectLoader( + root_fp=args.data_root_fp, + subject_id=args.exp_name, + split="train", + num_rays=target_sample_batch_size // args.render_n_samples, + **train_dataset_kwargs, + ) + train_dataset.camtoworlds = train_dataset.camtoworlds.to(device) + train_dataset.K = LearnRays(rays, device=device, img_shape=img_shape).to(device) + + if not args.skip_train_summaries: + test_dataset = SubjectLoader( + root_fp=args.data_root_fp, + subject_id=args.exp_name, + split="test", + num_rays=None, + **test_dataset_kwargs, + ) + if test_dataset_kwargs["have_images"]: + test_dataset.images = test_dataset.images.to(device) + test_dataset.camtoworlds = test_dataset.camtoworlds.to(device) + test_dataset.K = LearnRays(rays, device=device, img_shape=img_shape_test).to(device) + + args.laser_kernel = build_irf_kernel(args, device=device) + train_dataset_scale = float(_to_numpy(train_dataset.max).reshape(-1)[0]) + if train_dataset_scale <= 0: + train_dataset_scale = 1.0 + + scene_aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device) + render_step_size = ((scene_aabb[3:] - scene_aabb[:3]).max() * math.sqrt(3) / args.render_n_samples).item() + + grad_scaler = torch.cuda.amp.GradScaler(2**10) + radiance_field = NGPRadianceField( + use_viewdirs=True, + aabb=args.aabb, + unbounded=False, + radiance_activation=torch.exp, + args=args, + ).to(device) + + optimizer = torch.optim.Adam(radiance_field.parameters(), lr=args.lr, eps=1e-15) + scheduler = torch.optim.lr_scheduler.MultiStepLR( + optimizer, + milestones=[max_steps // 2, max_steps * 3 // 4, max_steps * 9 // 10], + gamma=0.33, + ) + occupancy_grid = OccGridEstimator( + roi_aabb=aabb, + resolution=args.grid_resolution, + levels=args.grid_nlvl, + ).to(device) + + if args.final: + writer, step, outpath = make_save_folder_final( + args, + optimizer, + scheduler, + radiance_field, + occupancy_grid, + ) + args.outpath = outpath + else: + outpath = make_save_folder(args) + args.outpath = outpath + writer = SummaryWriter(log_dir=outpath) + step = 0 + + if step > 0: + training_state = torch.load(os.path.join(outpath, 'variables.pth'), map_location='cpu', weights_only=True) + previous_gradient_scale = float(training_state.get('optimizer_gradient_scale', 2**10)) + if previous_gradient_scale != 1.0: + for optimizer_state in optimizer.state.values(): + optimizer_state['exp_avg'].div_(previous_gradient_scale) + optimizer_state['exp_avg_sq'].div_(previous_gradient_scale**2) + print(f'Converted legacy Adam moments from gradient scale {previous_gradient_scale} to unscaled units.', flush=True) + if 'amp_scaler' in training_state: + grad_scaler.load_state_dict(training_state['amp_scaler']) + + if args.version == "captured": + import sys + from pathlib import Path + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from evaluation.units import record_training_units + record_training_units(outpath, train_dataset_scale, 1.0, + Path(args.data_root_fp)/"transforms_train.json", "trnerf", + measurement_root=measurement_root, intrinsics=args.intrinsics) + + # When resuming (final=True), show progress from resumed step. + pbar = tqdm.tqdm(total=args.max_steps, initial=min(step, args.max_steps)) + zero_sample_streak = 0 + gradient_overflow_streak = 0 + while step < max_steps: + + if args.version == "simulated" and step % 1000 == 0: + if train_dataset.rep < 30: + train_dataset.rep += 2 + + radiance_field.train() + + i = torch.randint(0, len(train_dataset), (1,)).item() + data = train_dataset[i] + rays = data["rays"] + num_base_rays = int(rays.origins.shape[0] / train_dataset.rep) + pixs = torch.reshape( + data["pixels"][:num_base_rays], + (-1, args.n_bins, 3), + ) + data_valid_mask = data.get("valid_mask") + if data_valid_mask is not None: + data_valid_mask = data_valid_mask.to(device=device, dtype=torch.bool).reshape(-1) + if data_valid_mask.numel() < num_base_rays: + raise ValueError( + f"valid_mask has too few elements: {data_valid_mask.numel()} < base rays {num_base_rays}" + ) + data_valid_mask = data_valid_mask[:num_base_rays] + else: + data_valid_mask = torch.ones(pixs.shape[0], dtype=torch.bool, device=device) + # Use measurement peak (pre-log) to exclude low-signal / out-of-range pixels. + if args.version == "captured" and float(args.meas_peak_min) > 0: + peak_thre_norm = float(args.meas_peak_min) / float(train_dataset_scale) + meas_peak = torch.amax(pixs[..., 0], dim=-1) + meas_valid_mask = meas_peak >= peak_thre_norm + else: + meas_valid_mask = torch.ones(pixs.shape[0], dtype=torch.bool, device=pixs.device) + + def occ_eval_fn(x): + density = radiance_field.query_density(x) + density = torch.nan_to_num(density, nan=0.0, posinf=0.0, neginf=0.0) + return density.squeeze(-1) * render_step_size + + base_occ_thre = float(args.occ_thre) + if args.version == "captured": + warmup_steps = int(args.thold_warmup) if int(args.thold_warmup) > 0 else 10000 + occ_thre = min(base_occ_thre, 1e-6) if step < warmup_steps else base_occ_thre + else: + occ_thre = base_occ_thre + + try: + occupancy_grid.update_every_n_steps(step=step, occ_eval_fn=occ_eval_fn, occ_thre=occ_thre) + except RuntimeError as ex: + if "invalid configuration argument" in str(ex).lower(): + raise RuntimeError( + "CUDA invalid configuration argument during occupancy update. " + "This is often an async CUDA error from an earlier kernel. " + "Rerun with CUDA_LAUNCH_BLOCKING=1 to get the first failing op." + ) from ex + raise + + out = render_transient( + radiance_field, + occupancy_grid, + rays, + near_plane=args.near_plane, + far_plane=args.far_plane, + render_step_size=render_step_size, + cone_angle=args.cone_angle, + alpha_thre=args.alpha_thre, + use_normals=False, + args=args, + ) + + rgb, acc, n_rendering_samples, comp_weights = [ + out[key] for key in ["colors", "opacities", "n_rendering_samples", "comp_weights"] + ] + del out + + if n_rendering_samples == 0: + # Avoid infinite loops where step never advances. + zero_sample_streak += 1 + if zero_sample_streak % 100 == 0: + print( + f"[WARN] n_rendering_samples==0 streak={zero_sample_streak} " + f"at step={step}. Try lowering occ_thre (current={occ_thre})." + ) + if zero_sample_streak >= 1000: + raise RuntimeError('No rendering samples for 1000 consecutive attempts; training cannot advance.') + continue + zero_sample_streak = 0 + + train_dataset.update_num_rays(args.num_rays_per_batch) + + alive_ray_mask = acc.squeeze(-1) > 0 + alive_ray_mask = alive_ray_mask.reshape(train_dataset.rep, -1) + alive_ray_mask = alive_ray_mask.sum(0).bool() + supervised_mask = alive_ray_mask & meas_valid_mask & data_valid_mask + + rgba = torch.reshape(rgb, (-1, args.n_bins, 3)) * data["weights"][:, None, None] + carve_mask = pixs.sum(-1).repeat(train_dataset.rep, 1) < 1e-7 + valid_mask_flat = data_valid_mask.repeat(train_dataset.rep)[:, None] + carve_mask = carve_mask & valid_mask_flat.expand(-1, args.n_bins) + carve_vals = comp_weights[carve_mask] + if carve_vals.numel() > 0: + comp_weights = carve_vals.mean() + else: + comp_weights = torch.tensor(0.0, device=device, dtype=rgba.dtype) + rgb = torch.zeros((int(rgba.shape[0] / train_dataset.rep), args.n_bins, 3), device=device) + index = ( + torch.arange(int(rgba.shape[0] / train_dataset.rep), device=device) + .repeat(train_dataset.rep)[:, None, None] + .expand(-1, args.n_bins, 3) + ) + rgb.scatter_add_(0, index.type(torch.int64), rgba) + + pixs = torch.log(pixs + 1) + rgb = torch.log(rgb + 1) + if supervised_mask.any(): + photometric_loss = torch.nn.functional.l1_loss(rgb[supervised_mask], pixs[supervised_mask]) + else: + photometric_loss = torch.tensor(0.0, device=device) + loss = photometric_loss + comp_weights * args.space_carving + + if not torch.isfinite(loss): + raise FloatingPointError(f'Non-finite training loss before optimizer update {step + 1}; checkpoints are not overwritten.') + + optimizer.zero_grad() + previous_scale = grad_scaler.get_scale() + grad_scaler.scale(loss).backward() + grad_scaler.step(optimizer) + grad_scaler.update() + if grad_scaler.get_scale() < previous_scale: + gradient_overflow_streak += 1 + print(f'[AMP] Skipped non-finite gradient update at step {step}; scale={grad_scaler.get_scale()}.', flush=True) + if gradient_overflow_streak >= 100: + raise FloatingPointError('Non-finite gradients for 100 consecutive attempts; training cannot advance.') + continue + gradient_overflow_streak = 0 + scheduler.step() + step += 1 + pbar.update(1) + + writer.add_scalar("Loss/train", loss.detach().cpu().numpy(), step) + writer.add_scalar("Loss/photometric", photometric_loss.detach().cpu().numpy(), step) + writer.add_scalar("Mask/supervised_ratio", supervised_mask.float().mean().detach().cpu().numpy(), step) + + if step > 0 and step % 10000 == 0: + print( + "[TRAIN_PROGRESS] " + f"step={step}/{max_steps} " + f"loss={float(loss.detach().cpu()):.6f} " + f"photometric_loss={float(photometric_loss.detach().cpu()):.6f} " + f"space_carving_loss={float(comp_weights.detach().cpu()):.6f} " + f"supervised_ratio={float(supervised_mask.float().mean().detach().cpu()):.6f} " + f"n_rendering_samples={n_rendering_samples} " + f"lr={optimizer.param_groups[0]['lr']:.8f} " + f"outpath={outpath}", + flush=True, + ) + + if not step % args.steps_til_checkpoint or step == max_steps: + path = os.path.join(outpath, "radiance_field_{:04d}.pth".format(step)) + torch.save(radiance_field.state_dict(), path) + path = os.path.join(outpath, "occupancy_grid_{:04d}.pth".format(step)) + torch.save(occupancy_grid.state_dict(), path) + path = os.path.join(outpath, "optimizer_{:04d}.pth".format(step)) + torch.save(optimizer.state_dict(), path) + path = os.path.join(outpath, "scheduler_{:04d}.pth".format(step)) + torch.save(scheduler.state_dict(), path) + torch.save({"step": step, "rays_per_pixel": train_dataset.rep, + "optimizer_gradient_scale": 1.0, "amp_scaler": grad_scaler.state_dict()}, + os.path.join(outpath, "variables.pth")) + + if test_dataset_kwargs["have_images"] and not args.skip_train_summaries: + write_summary_histogram( + radiance_field, + occupancy_grid, + writer, + test_dataset, + step, + render_step_size, + args, + ) + +if __name__ == "__main__": + run() diff --git a/codes/reconstruction/trnerf/utils.py b/codes/reconstruction/trnerf/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..add9fc6a206841d0ba5ddb2fae7a985b16529a73 --- /dev/null +++ b/codes/reconstruction/trnerf/utils.py @@ -0,0 +1,539 @@ +from datetime import datetime +import random +from typing import Optional +import ast +import configargparse +import os +import numpy as np +import torch +from loaders.utils import Rays, namedtuple_map +from nerfacc.estimators.occ_grid import OccGridEstimator +from nerfacc.grid import ray_aabb_intersect, traverse_grids +from misc.transient_volrend import ( +rendering_transient_single_path) + +from torch.utils.tensorboard import SummaryWriter +import shutil + + +def set_random_seed(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + +def render_transient( + # scene + radiance_field: torch.nn.Module, + occupancy_grid: OccGridEstimator, + rays: Rays, + # rendering options + near_plane = 0, + far_plane = 2**15, + render_step_size: float = 1e-3, + cone_angle: float = 0.0, + alpha_thre: float = 0.0, + # test options + # only useful for dnerf + chunk = 8192*128, + use_normals = False, + args = None +): + """Render the pixels of an image.""" + rays_shape = rays.origins.shape + if len(rays_shape) == 3: + height, width, _ = rays_shape + n_rays = height * width + rays = namedtuple_map( + lambda r: r.reshape([n_rays] + list(r.shape[2:])), rays + ) + else: + n_rays, _ = rays_shape + + results = [] + + def rgb_sigma_fn(t_starts, t_ends, ray_indices): + t_origins = chunk_rays.origins[ray_indices] + t_dirs = chunk_rays.viewdirs[ray_indices] + positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0 + rgbs, sigmas = radiance_field(positions, t_dirs) + return rgbs, sigmas.squeeze(-1) + + + for i in range(0, n_rays, chunk): + chunk_rays = namedtuple_map(lambda r: r[i : i + chunk], rays) + + def sigma_fn(t_starts, t_ends, ray_indices): + t_origins = chunk_rays.origins[ray_indices] + t_dirs = chunk_rays.viewdirs[ray_indices] + positions = t_origins + t_dirs * (t_starts + t_ends)[:, None] / 2.0 + sigmas = radiance_field.query_density(positions) + return sigmas.squeeze(-1) + + ray_indices, t_starts, t_ends = occupancy_grid.sampling( + chunk_rays.origins, + chunk_rays.viewdirs, + sigma_fn=sigma_fn, + near_plane=near_plane, + far_plane=far_plane, + render_step_size=render_step_size, + stratified=radiance_field.training, + cone_angle=cone_angle, + alpha_thre=alpha_thre, + ) + rgb, opacity, depth, depth_variance, comp_weights, raw_rgbs = rendering_transient_single_path( + t_starts=t_starts, + t_ends=t_ends, + ray_indices=ray_indices, + n_rays=n_rays, + # radiance field + rgb_sigma_fn=rgb_sigma_fn, + # rendering options + render_bkgd=None, + args = args + ) + + chunk_results_single = [rgb, opacity, depth, depth_variance, comp_weights, raw_rgbs, len(t_starts)] + results.append(chunk_results_single) + + colors_single, opacities_single, depths_single, depths_variance, densities, raw_rgbs, n_rendering_samples = [ + torch.cat(r, dim=0) if isinstance(r[0], torch.Tensor) else r + for r in zip(*results) + ] + + normals_loss = 0 + + colors = torch.reshape(colors_single, (-1, args.n_bins, 3)) + + return {'colors': colors.view((*rays_shape[:-1], -1)), + 'opacities': opacities_single.view((*rays_shape[:-1], -1)), + 'depths': depths_single.view((*rays_shape[:-1], -1)), + 'depths_variance' : depths_variance.view((*rays_shape[:-1], -1)), + 'n_rendering_samples': sum(n_rendering_samples), + 'normals_loss': normals_loss, + 'comp_weights': comp_weights, + "raw_rgbs":raw_rgbs} + + +def parse_list(arg): + try: + return ast.literal_eval(arg) + except (SyntaxError, ValueError): + raise configargparse.ArgumentTypeError(f"Invalid list format: {arg}") + +def str2bool(v): + if isinstance(v, bool): + return v + if v.lower() in ('yes', 'true', 't', 'y', '1'): + return True + elif v.lower() in ('no', 'false', 'f', 'n', '0'): + return False + else: + raise configargparse.ArgumentTypeError('Boolean value expected.') + + +def load_args(eval = False, parser= None): + # parser = configargparse.ArgumentParser() + if not eval: + parser = configargparse.ArgumentParser() + + has_test_config = ( + eval + and parser is not None + and hasattr(parser, "_option_string_actions") + and "--test_config" in parser._option_string_actions + ) + my_config_default = None + parser.add('-c', '--my-config', + is_config_file=True, + default=my_config_default, + help='Path to config file.' + ) + parser.add_argument( + '--exp_name', + type=str, + default='lego_two_views', + help='Experiment name.' + ) + parser.add_argument( + "--aabb", + nargs='+', + type = lambda s: ast.literal_eval(s), + default="[-1.5,-1.5,-1.5,1.5,1.5, 1.5]", + help="AABB size.", + ) + parser.add_argument( + "--test_chunk_size", + type=int, + default=512, + help="Test chunk size..", + ) + parser.add_argument( + "--num_rays_per_batch", + type=int, + default=512, + help="Number of rays per batch.", + ) + parser.add_argument( + "--starting_rays_per_pixel", + type=int, + default=1, + help="Starting rays per pixels.", + ) + parser.add_argument( + "--tfilter_sigma", + type=int, + default=3, + help="Temporal filter standard deviation.", + ) + parser.add_argument( + "--space_carving", + type=float, + default=7*1e-3, + help="Space carvig regaularization strength.", + ) + # parser.add_argument( + # "--dataset_scale", + # type=int, + # default=46, + # help="Scale for all transient images.", + # ) + parser.add_argument( + "--rfilter_sigma", + type=float, + default=0.15, + help="Spatial filter standard deviation.", + ) + parser.add_argument( + "--exposure_time", + type=float, + default=0.01, + help="Exposure length per bin in meters.", + ) + parser.add_argument( + "--lr", + type=float, + default=1e-3, + help="Learning rate.", + ) + parser.add_argument( + "--steps_til_checkpoint", + type=int, + default=20000, + help="Steps per checkpoint.", + ) + parser.add_argument( + "--n_bins", + type=int, + default=1200, + help="Number of bins.", + ) + parser.add_argument( + "--img_shape", + type=int, + default=512, + help="Shape of training image.", + ) + parser.add_argument( + "--sample_as_per_distribution", + action="store_true", + help="Sample as per distribution or uniformly.", + ) + parser.add_argument( + "--render_n_samples", + type=int, + default=4096, + help="Num samples per ray.", + ) + parser.add_argument( + "--exp", + type=str2bool, + default="true", + help="Use double exp.", + ) + parser.add_argument( + "--max_steps", + type=int, + default=300000, + help="Max number of steps.", + ) + parser.add_argument( + "--near_plane", + type=float, + default=0.0, + help="Near plane value.", + ) + parser.add_argument( + "--alpha_thre", + type=float, + default=0, + ) + parser.add_argument( + "--far_plane", + type=float, + default=float(2**15), + help="Far plane value.", + ) + parser.add_argument( + "--version", + type=str, + default="simulated", + choices=["captured", "simulated"], + help="Dataset being trained, captured or simulated.", + ) + parser.add_argument( + "--occ_thre", + type=float, + default=0.01, + help="Occupancy threshold", + ) + parser.add_argument( + "--thold_warmup", + type=int, + default=-1, + help="Warmup period for the occupancy threshold.", + ) + parser.add_argument( + "--final", + type=str2bool, + default="false", + help="If final version or debug mode (creates dated folder).", + ) + parser.add_argument( + "--grid_resolution", + type=int, + default=128, + help="Occgrid resolution.", + ) + parser.add_argument( + "--grid_nlvl", + type=int, + default=1, + help="Number of grid levels.", + ) + parser.add_argument( + "--outpath", + type=str, + default="./results", + help="Path to results folder.", + ) + parser.add_argument( + "--data_root_fp", + type=str, + default="./data/lego_data/lego_jsons/two_views", + help="Root of dataset directory (where the transforms directory is).", + ) + parser.add_argument( + "--pulse_path", + type=str, + default="./datasets/pulse_low_flux.mat", + help="Path to pulse for captured dataset.", + ) + parser.add_argument( + "--intrinsics", + type=str, + default="./data/lego_data/lego_jsons/two_views", + help="Path to intrinsics for captured dataset", + ) + parser.add_argument( + "--pixels_to_plot", + nargs='+', + type = lambda s: ast.literal_eval(s), + default=[(16, 16), (20, 16), (28, 25)], + help="Pixels used for plotting in the summary.", + ) + parser.add_argument( + "--img_scale", + type=int, + default=100, + help="Image scale used in summary.", + ) + parser.add_argument( + "--num_views", + type=int, + default=2, + help="Number of views trained on.", + ) + parser.add_argument( + "--img_shape_test", + type=int, + default=64, + help="Test image shape.", + ) + parser.add_argument( + "--seed", + type=int, + default=42, + help="Seed.", + ) + parser.add_argument( + "--device", + type=str, + default="cuda:7", + help="Device.", + ) + parser.add_argument("--cone_angle", type=float, default=0.0) + parser.add_argument( + "--resume", + type=str, + default=None, + help="Path to a checkpoint directory to resume training from.", + ) + args = parser.parse_args() + return args + +def make_save_folder(args): + now = datetime.now() + now = now.strftime("%m-%d_%H:%M:%S") + exp_name = args.exp_name + "_" + now + outpath = os.path.join(args.outpath, exp_name) + os.makedirs(args.outpath, exist_ok=True) + os.mkdir(outpath) + shutil.copy(args.my_config, os.path.join(outpath, "params.txt")) + + with open(os.path.join(outpath, "params_full.txt"), "w") as out_file: + param_list = [] + for key, value in vars(args).items(): + if type(value) == list: + value = [eval(f"{x}") for x in value] + elif type(value) != int and type(value) != float: + value = str(value) + value = f"'{value}'" + param_list.append("%s= %s" % (key, value)) + + out_file.write('\n'.join(param_list)) + return outpath + +def make_save_folder_final(args, optimizer, scheduler, radiance_field, occupancy_grid): + outpath = os.path.join(args.outpath, args.exp_name) + + if not os.path.isdir(outpath): + + os.makedirs(outpath, exist_ok=True) + with open(os.path.join(outpath, "params_full.txt"), "w") as out_file: + param_list = [] + for key, value in vars(args).items(): + if type(value) != int and type(value) != float: + value = str(value) + value = f"'{value}'" + param_list.append("%s= %s" % (key, value)) + + out_file.write('\n'.join(param_list)) + step = 0 + writer = SummaryWriter(log_dir=outpath) + + else: + ckpt_path_var = os.path.join(outpath, 'variables.pth') + if not os.path.isfile(ckpt_path_var): + print(f"warning: '{ckpt_path_var}' not found; starting fresh in existing directory.") + step = 0 + writer = SummaryWriter(log_dir=outpath) + return writer, step, outpath + + ckpt = torch.load(ckpt_path_var, map_location="cpu") + step = int(ckpt.get('step', 0)) + + ckpt_path_rf = os.path.join(outpath, 'radiance_field_%04d.pth' % (step)) + ckpt_path_oc = os.path.join(outpath, 'occupancy_grid_%04d.pth' % (step)) + ckpt_path_opt = os.path.join(outpath, 'optimizer_%04d.pth' % (step)) + ckpt_path_sch = os.path.join(outpath, 'scheduler_%04d.pth' % (step)) + + if not (os.path.isfile(ckpt_path_rf) and os.path.isfile(ckpt_path_oc)): + print( + "warning: model checkpoint files missing for saved step; " + "starting fresh optimizer/model state." + ) + step = 0 + writer = SummaryWriter(log_dir=outpath) + return writer, step, outpath + + ckpt = torch.load(ckpt_path_rf, map_location=args.device) + radiance_field.load_state_dict(ckpt) + radiance_field = radiance_field.to(args.device) + + ckpt = torch.load(ckpt_path_oc, map_location=args.device) + occupancy_grid.load_state_dict(ckpt) + occupancy_grid = occupancy_grid.to(args.device) + + if os.path.isfile(ckpt_path_opt): + ckpt = torch.load(ckpt_path_opt, map_location=args.device) + optimizer.load_state_dict(ckpt) + else: + print(f"warning: optimizer checkpoint missing at '{ckpt_path_opt}', using fresh optimizer state.") + + if os.path.isfile(ckpt_path_sch): + ckpt = torch.load(ckpt_path_sch, map_location=args.device) + scheduler.load_state_dict(ckpt) + else: + print(f"warning: scheduler checkpoint missing at '{ckpt_path_sch}', using fresh scheduler state.") + + print(f"previous checkpoint loaded; current step: {step}") + writer = SummaryWriter(log_dir=outpath) + + return writer, step, outpath + + +def resume_training(args, optimizer, scheduler, radiance_field, occupancy_grid): + """Load a previous checkpoint and prepare writer/step/outpath.""" + ckpt_dir = args.resume + if ckpt_dir is None: + raise ValueError("args.resume is None, cannot resume.") + if not os.path.isdir(ckpt_dir): + raise FileNotFoundError(f"Checkpoint directory not found: {ckpt_dir}") + + variables_path = os.path.join(ckpt_dir, "variables.pth") + step = 0 + rays_per_pixel = None + if os.path.isfile(variables_path): + ckpt_vars = torch.load(variables_path, map_location="cpu") + step = ckpt_vars.get("step", 0) + rays_per_pixel = ckpt_vars.get("rays_per_pixel") + else: + ckpt_steps = [] + for name in os.listdir(ckpt_dir): + if name.startswith("radiance_field_") and name.endswith(".pth"): + try: + ckpt_steps.append(int(name.split("_")[-1].split(".")[0])) + except ValueError: + continue + if not ckpt_steps: + raise FileNotFoundError( + "No checkpoint files found to resume from in " + f"{ckpt_dir}. Expected radiance_field_XXXX.pth." + ) + step = max(ckpt_steps) + + rf_path = os.path.join(ckpt_dir, f"radiance_field_{step:04d}.pth") + oc_path = os.path.join(ckpt_dir, f"occupancy_grid_{step:04d}.pth") + opt_path = os.path.join(ckpt_dir, f"optimizer_{step:04d}.pth") + sch_path = os.path.join(ckpt_dir, f"scheduler_{step:04d}.pth") + + for required_path in [rf_path, oc_path]: + if not os.path.isfile(required_path): + raise FileNotFoundError(f"Missing checkpoint file: {required_path}") + + radiance_field.load_state_dict( + torch.load(rf_path, map_location=args.device) + ) + radiance_field = radiance_field.to(args.device) + + occupancy_grid.load_state_dict( + torch.load(oc_path, map_location=args.device) + ) + occupancy_grid = occupancy_grid.to(args.device) + + if os.path.isfile(opt_path): + optimizer.load_state_dict(torch.load(opt_path, map_location=args.device)) + else: + print(f"warning: missing optimizer checkpoint '{opt_path}', using fresh optimizer state.") + + if os.path.isfile(sch_path): + scheduler.load_state_dict(torch.load(sch_path, map_location=args.device)) + else: + print(f"warning: missing scheduler checkpoint '{sch_path}', using fresh scheduler state.") + + writer = SummaryWriter(log_dir=ckpt_dir) + args.outpath = ckpt_dir + return writer, step, ckpt_dir, rays_per_pixel + +if __name__=="__main__": + pass