File size: 7,613 Bytes
12c6e53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import argparse
import os

import numpy as np


PERCENTILES = [0, 0.1, 1, 5, 25, 50, 75, 95, 99, 99.9, 100]


def _as_float_array(values):
    return np.asarray(values, dtype=np.float64)


def _format_float(value):
    if value is None or not np.isfinite(value):
        return str(value)
    return f"{value:.8g}"


def _field_stats(values):
    arr = _as_float_array(values).reshape(-1)
    finite_mask = np.isfinite(arr)
    finite = arr[finite_mask]

    stats = {
        "count": int(arr.size),
        "finite": int(finite.size),
        "nan": int(np.isnan(arr).sum()),
        "pos_inf": int(np.isposinf(arr).sum()),
        "neg_inf": int(np.isneginf(arr).sum()),
        "zero": int((arr == 0).sum()),
        "neg": int((arr < 0).sum()),
        "pos": int((arr > 0).sum()),
    }

    if finite.size == 0:
        stats.update({
            "min": None,
            "max": None,
            "mean": None,
            "std": None,
            "abs_max": None,
            "percentiles": None,
        })
        return stats

    stats.update({
        "min": float(np.min(finite)),
        "max": float(np.max(finite)),
        "mean": float(np.mean(finite)),
        "std": float(np.std(finite)),
        "abs_max": float(np.max(np.abs(finite))),
        "percentiles": np.percentile(finite, PERCENTILES),
    })
    return stats


def _print_field_stats(name, values, top_extreme=0):
    stats = _field_stats(values)
    count = max(stats["count"], 1)
    finite_ratio = 100.0 * stats["finite"] / count
    zero_ratio = 100.0 * stats["zero"] / count

    print(f"\n[{name}]")
    print(
        "  count={count} finite={finite} ({finite_ratio:.2f}%) "
        "nan={nan} +inf={pos_inf} -inf={neg_inf}".format(
            finite_ratio=finite_ratio, **stats
        )
    )
    print(
        "  min={min} max={max} mean={mean} std={std} abs_max={abs_max}".format(
            min=_format_float(stats["min"]),
            max=_format_float(stats["max"]),
            mean=_format_float(stats["mean"]),
            std=_format_float(stats["std"]),
            abs_max=_format_float(stats["abs_max"]),
        )
    )
    print(
        "  zero={zero} ({zero_ratio:.2f}%) neg={neg} pos={pos}".format(
            zero_ratio=zero_ratio, **stats
        )
    )

    if stats["percentiles"] is not None:
        pairs = [
            f"p{p:g}={_format_float(v)}"
            for p, v in zip(PERCENTILES, stats["percentiles"])
        ]
        print("  " + " ".join(pairs))

    if top_extreme > 0:
        arr = _as_float_array(values).reshape(-1)
        finite_idx = np.flatnonzero(np.isfinite(arr))
        if finite_idx.size > 0:
            finite_vals = arr[finite_idx]
            k = min(top_extreme, finite_vals.size)
            order = np.argsort(np.abs(finite_vals))[-k:][::-1]
            items = [
                f"idx={int(finite_idx[i])}:value={_format_float(finite_vals[i])}"
                for i in order
            ]
            print("  top_abs: " + ", ".join(items))


def _existing_fields(names, prefix):
    return sorted(
        [name for name in names if name.startswith(prefix)],
        key=lambda x: int(x[len(prefix):]) if x[len(prefix):].isdigit() else x,
    )


def _stack_fields(vertex, fields):
    if not fields:
        return None
    return np.stack([vertex[name] for name in fields], axis=1).astype(np.float64)


def _print_vector_stats(label, arr):
    if arr is None:
        return
    finite_rows = np.isfinite(arr).all(axis=1)
    print(f"\n[{label} vector]")
    print(f"  shape={arr.shape} finite_rows={int(finite_rows.sum())}/{arr.shape[0]}")

    norms = np.linalg.norm(arr, axis=1)
    _print_field_stats(f"{label}_norm", norms)

    if arr.shape[1] == 3 and label == "scale_log":
        scale = np.exp(np.clip(arr, -80, 80))
        _print_field_stats("scale_actual_min_axis", scale.min(axis=1))
        _print_field_stats("scale_actual_max_axis", scale.max(axis=1))
        aspect = scale.max(axis=1) / np.maximum(scale.min(axis=1), 1e-12)
        _print_field_stats("scale_aspect_ratio", aspect)

    if arr.shape[1] == 4 and label == "rotation":
        norm = np.linalg.norm(arr, axis=1)
        bad = np.abs(norm - 1.0) > 1e-2
        print(f"  rotation_norm_not_1(>|1e-2|)={int(bad.sum())}/{arr.shape[0]}")


def inspect_ply(path, top_extreme=0, only_bad=False):
    try:
        from plyfile import PlyData
    except ImportError as exc:
        raise ImportError(
            "Missing dependency 'plyfile'. Install it with: pip install plyfile"
        ) from exc

    if not os.path.exists(path):
        raise FileNotFoundError(path)

    ply = PlyData.read(path)
    if "vertex" not in ply:
        raise ValueError("PLY does not contain a vertex element")

    vertex = ply["vertex"]
    names = list(vertex.data.dtype.names)
    n_points = len(vertex)

    print(f"file: {os.path.abspath(path)}")
    print(f"points: {n_points}")
    print(f"fields ({len(names)}): {', '.join(names)}")

    for name in names:
        values = vertex[name]
        stats = _field_stats(values)
        if only_bad and stats["nan"] == 0 and stats["pos_inf"] == 0 and stats["neg_inf"] == 0:
            continue
        _print_field_stats(name, values, top_extreme=top_extreme)

    scale_fields = [name for name in ["scale_0", "scale_1", "scale_2"] if name in names]
    rot_fields = [name for name in ["rot_0", "rot_1", "rot_2", "rot_3"] if name in names]
    pos_fields = [name for name in ["x", "y", "z"] if name in names]
    dc_fields = [name for name in ["f_dc_0", "f_dc_1", "f_dc_2"] if name in names]
    sh_fields = _existing_fields(names, "f_rest_")

    _print_vector_stats("position", _stack_fields(vertex, pos_fields) if len(pos_fields) == 3 else None)
    _print_vector_stats("scale_log", _stack_fields(vertex, scale_fields) if len(scale_fields) == 3 else None)
    _print_vector_stats("rotation", _stack_fields(vertex, rot_fields) if len(rot_fields) == 4 else None)
    _print_vector_stats("dc", _stack_fields(vertex, dc_fields) if len(dc_fields) == 3 else None)

    if sh_fields:
        sh = _stack_fields(vertex, sh_fields)
        _print_vector_stats("sh_rest", sh)
        _print_field_stats("sh_rest_all_values", sh.reshape(-1), top_extreme=top_extreme)

    if "opacity" in names:
        opacity_logit = _as_float_array(vertex["opacity"])
        opacity_sigmoid = 1.0 / (1.0 + np.exp(-np.clip(opacity_logit, -80, 80)))
        _print_field_stats("opacity_sigmoid", opacity_sigmoid)

    if "filter_3D" in names:
        unique = np.unique(np.asarray(vertex["filter_3D"]))
        print(f"\n[filter_3D unique]")
        print(f"  unique_count={len(unique)}")
        if len(unique) <= 20:
            print("  values=" + ", ".join(_format_float(float(v)) for v in unique))
        else:
            print("  first20=" + ", ".join(_format_float(float(v)) for v in unique[:20]))


def parse_args():
    parser = argparse.ArgumentParser(
        description="Inspect numeric distributions of all vertex fields in a PLY file."
    )
    parser.add_argument("ply_path", help="Path to the PLY file to inspect.")
    parser.add_argument(
        "--top_extreme",
        type=int,
        default=0,
        help="Print top-k absolute extreme values per field with flat indices.",
    )
    parser.add_argument(
        "--only_bad",
        action="store_true",
        help="Only print fields containing NaN or Inf. Combined diagnostics are still printed.",
    )
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    inspect_ply(args.ply_path, top_extreme=args.top_extreme, only_bad=args.only_bad)