File size: 29,400 Bytes
b6619c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
import numpy as np
from plyfile import PlyData, PlyElement
from sklearn.cluster import AgglomerativeClustering
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.transform import Rotation as R
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
import os
import json


# ============================================================
#  Merge 相关函数
# ============================================================

def read_ply(ply_path):
    plydata = PlyData.read(ply_path)
    vertex  = plydata['vertex']
    positions = np.stack([vertex['x'], vertex['y'], vertex['z']], axis=1)
    opacities = vertex['opacity'][:, np.newaxis]
    scales    = np.stack([vertex['scale_0'], vertex['scale_1'], vertex['scale_2']], axis=1)
    rotations = np.stack([vertex['rot_0'], vertex['rot_1'], vertex['rot_2'], vertex['rot_3']], axis=1)
    filter_3D = np.stack([vertex['filter_3D']], axis=1)
    dc        = np.stack([vertex['f_dc_0'], vertex['f_dc_1'], vertex['f_dc_2']], axis=1)
    sh_keys   = [key for key in vertex.data.dtype.names if key.startswith('f_rest_')]
    sh_rest   = np.stack([vertex[key] for key in sh_keys], axis=1) if sh_keys else None

    # point_id:每个点的唯一标识,原始PLY没有该字段时自动生成 0~N-1
    if 'point_id' in vertex.data.dtype.names:
        point_ids = vertex['point_id'].astype(np.int64)
    else:
        point_ids = np.arange(len(positions), dtype=np.int64)

    return {
        'positions': positions, 'opacities': opacities, 'scales': scales,
        'rotations': rotations, 'dc': dc, 'sh_rest': sh_rest,
        'plydata': plydata, 'filter_3D': filter_3D,
        'point_ids': point_ids,  # shape (N,),每个点的唯一ID
    }


def quaternion_to_rotation_matrix(q):
    try:
        rot = R.from_quat(q)
    except:
        rot = R.from_quat([q[1], q[2], q[3], q[0]])
    return rot.as_matrix()


def compute_covariance(rotation, scale_log):
    R_mat        = quaternion_to_rotation_matrix(rotation)
    scale_actual = np.exp(scale_log)
    S_mat        = np.diag(scale_actual)
    return R_mat @ S_mat @ S_mat.T @ R_mat.T


def covariance_to_rotation_scale(cov):
    eigenvalues, eigenvectors = np.linalg.eigh(cov)
    eigenvalues = np.maximum(eigenvalues, 1e-7)
    scale       = np.sqrt(eigenvalues)
    if np.linalg.det(eigenvectors) < 0:
        eigenvectors[:, 0] *= -1
    rotation = R.from_matrix(eigenvectors).as_quat()  # [x,y,z,w]
    return rotation, scale


def dc_to_rgb(dc):
    C0 = 0.28209479177387814
    return np.clip(dc * C0 + 0.5, 0, 1)


def build_octree(positions, max_points=5000):
    cells = []
    def subdivide(indices, bbox_min, bbox_max, depth=0):
        if len(indices) <= max_points or depth > 10:
            cells.append({'indices': indices, 'bbox_min': bbox_min, 'bbox_max': bbox_max})
            return
        center = (bbox_min + bbox_max) / 2
        for i in range(8):
            sub_min = np.array([
                center[0] if (i & 1)      else bbox_min[0],
                center[1] if (i >> 1 & 1) else bbox_min[1],
                center[2] if (i >> 2 & 1) else bbox_min[2],
            ])
            sub_max = np.array([
                bbox_max[0] if (i & 1)      else center[0],
                bbox_max[1] if (i >> 1 & 1) else center[1],
                bbox_max[2] if (i >> 2 & 1) else center[2],
            ])
            mask        = np.all((positions[indices] >= sub_min) & (positions[indices] < sub_max), axis=1)
            sub_indices = indices[mask]
            if len(sub_indices) > 0:
                subdivide(sub_indices, sub_min, sub_max, depth + 1)
    subdivide(np.arange(len(positions)), positions.min(axis=0), positions.max(axis=0))
    return cells


def build_knn_connectivity_graph(positions, k=10):
    n_points = len(positions)
    nbrs     = NearestNeighbors(n_neighbors=min(k+1, n_points), algorithm='kd_tree').fit(positions)
    _, indices = nbrs.kneighbors(positions)
    rows, cols = [], []
    for i in range(n_points):
        for j in range(1, len(indices[i])):
            rows += [i, indices[i][j]]
            cols += [indices[i][j], i]
    return csr_matrix((np.ones(len(rows)), (rows, cols)), shape=(n_points, n_points))


def get_connected_clusters(labels, connectivity_matrix):
    refined_labels = labels.copy()
    next_label     = labels.max() + 1
    for cluster_id in np.unique(labels):
        cluster_indices = np.where(labels == cluster_id)[0]
        if len(cluster_indices) <= 1:
            continue
        subgraph = connectivity_matrix[cluster_indices, :][:, cluster_indices]
        n_components, component_labels = connected_components(subgraph, directed=False, return_labels=True)
        if n_components > 1:
            for comp_id in range(1, n_components):
                refined_labels[cluster_indices[component_labels == comp_id]] = next_label
                next_label += 1
    return refined_labels


def cluster_and_merge_cell(data, cell_indices, bbox_min, bbox_max,

                           k_neighbors=5, spread_factor=0.01,

                           aspect_ratio_threshold=5.0, compress_ratio=4,

                           id_counter=None):
    """

    对单个 cell 内的点进行聚类和合并。



    id_counter: 一个长度为1的列表 [int],用于跨cell生成全局唯一的新point_id。

                每产生一个合并点就将其自增1。



    返回:

        merged_data  : 合并后各属性(含 point_ids 字段)

        cell_lineage : dict { child_id(int): [parent_id(int), ...] }

    """
    if len(cell_indices) < 4:
        return None, None

    n_clusters = max(1, len(cell_indices) // compress_ratio)

    cell_positions  = data['positions'][cell_indices]
    cell_dc         = data['dc'][cell_indices]
    cell_opacities  = data['opacities'][cell_indices]
    cell_scales     = data['scales'][cell_indices]
    cell_rotations  = data['rotations'][cell_indices]
    cell_filter_3D  = data['filter_3D'][cell_indices]
    cell_point_ids  = data['point_ids'][cell_indices]   # 父节点的 point_id

    connectivity_matrix = build_knn_connectivity_graph(cell_positions, k=k_neighbors)

    cell_size      = np.maximum(bbox_max - bbox_min, 1e-6)
    norm_positions = (cell_positions - bbox_min) / cell_size
    rgb            = dc_to_rgb(cell_dc)

    features = np.concatenate([norm_positions * np.sqrt(0.8), rgb * np.sqrt(0.2)], axis=1)
    labels   = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward').fit_predict(features)
    refined_labels   = get_connected_clusters(labels, connectivity_matrix)
    final_n_clusters = len(np.unique(refined_labels))
    print(f"  原始簇数: {n_clusters}, 连通性约束后簇数: {final_n_clusters}")

    merged_data = {
        'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
        'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
        'filter_3D': [], 'point_ids': []
    }
    # 族谱:{child_point_id: [parent_point_id, ...]}
    cell_lineage = {}

    for cluster_id in np.unique(refined_labels):
        idx_in_cell = np.where(refined_labels == cluster_id)[0]
        if len(idx_in_cell) == 0:
            continue

        # 父节点的 point_id(与顺序无关的唯一标识)
        parent_ids = [int(x) for x in cell_point_ids[idx_in_cell]]

        # 为本合并点分配新的唯一 point_id
        child_id = int(id_counter[0])
        id_counter[0] += 1

        scale_actual       = np.exp(cell_scales[idx_in_cell])
        approx_volumes     = np.prod(scale_actual, axis=1, keepdims=True)
        actual_opacities   = 1.0 / (1.0 + np.exp(-cell_opacities[idx_in_cell]))
        weights            = actual_opacities * approx_volumes
        normalized_weights = weights / weights.sum()

        merged_position  = (cell_positions[idx_in_cell] * normalized_weights).sum(axis=0)
        merged_dc        = (cell_dc[idx_in_cell] * normalized_weights).sum(axis=0)
        merged_filter_3D = (cell_filter_3D[idx_in_cell] * normalized_weights).sum(axis=0)

        if data['sh_rest'] is not None:
            merged_sh_rest = (data['sh_rest'][cell_indices][idx_in_cell] * normalized_weights).sum(axis=0)

        covariances = np.array([compute_covariance(cell_rotations[i], cell_scales[i]) for i in idx_in_cell])
        merged_cov  = np.zeros((3, 3))
        for i, orig_idx in enumerate(idx_in_cell):
            diff = cell_positions[orig_idx] - merged_position
            merged_cov += normalized_weights[i, 0] * (covariances[i] + spread_factor * np.outer(diff, diff))

        merged_rotation, merged_scale = covariance_to_rotation_scale(merged_cov)

        min_s = merged_scale.min()
        if merged_scale.max() / (min_s + 1e-8) > aspect_ratio_threshold:
            merged_scale = np.clip(merged_scale, None, min_s * aspect_ratio_threshold)

        merged_opacity_actual = (cell_opacities[idx_in_cell] * normalized_weights).sum(axis=0)
        merged_opacity_actual = np.clip(merged_opacity_actual, 1e-5, 1.0 - 1e-5)
        merged_opacity        = np.log(merged_opacity_actual / (1.0 - merged_opacity_actual))

        merged_data['positions'].append(merged_position)
        merged_data['opacities'].append(merged_opacity)
        merged_data['scales'].append(merged_scale)
        merged_data['rotations'].append(merged_rotation)
        merged_data['dc'].append(merged_dc)
        merged_data['point_ids'].append(child_id)
        if data['sh_rest'] is not None:
            merged_data['sh_rest'].append(merged_sh_rest)
        merged_data['filter_3D'].append(merged_filter_3D)

        # 族谱:child_id → parent_ids(均为 point_id,与顺序无关)
        cell_lineage[child_id] = parent_ids

    for key in merged_data:
        if merged_data[key] is not None and len(merged_data[key]) > 0:
            merged_data[key] = np.array(merged_data[key])

    return merged_data, cell_lineage


def validate_data(merged_data):
    print("\n" + "="*60 + "\n数据验证报告\n" + "="*60)
    total   = len(merged_data['positions'])
    has_nan = np.zeros(total, dtype=bool)
    has_inf = np.zeros(total, dtype=bool)
    for key in ['positions', 'opacities', 'scales', 'rotations', 'dc']:
        arr = merged_data[key]
        if arr.ndim == 1:
            has_nan |= np.isnan(arr)
            has_inf |= np.isinf(arr)
        else:
            has_nan |= np.isnan(arr).any(axis=1)
            has_inf |= np.isinf(arr).any(axis=1)
    print(f"总点数: {total}  NaN点: {has_nan.sum()}  Inf点: {has_inf.sum()}")
    print("="*60 + "\n")
    return {'has_nan': has_nan.sum(), 'has_inf': has_inf.sum(), 'total': total}


def save_ply(merged_data, original_plydata, output_path):
    n_points   = len(merged_data['positions'])
    dtype_list = [
        ('x','f4'),('y','f4'),('z','f4'),('opacity','f4'),
        ('scale_0','f4'),('scale_1','f4'),('scale_2','f4'),
        ('rot_0','f4'),('rot_1','f4'),('rot_2','f4'),('rot_3','f4'),
        ('f_dc_0','f4'),('f_dc_1','f4'),('f_dc_2','f4'),
        ('point_id', 'i8'),   # 每个点的唯一ID,用于族谱对应,与顺序无关
    ]
    n_sh = 0
    if merged_data['sh_rest'] is not None:
        n_sh = merged_data['sh_rest'].shape[1]
        dtype_list += [(f'f_rest_{i}','f4') for i in range(n_sh)]
    if merged_data.get('filter_3D') is not None:
        dtype_list.append(('filter_3D','f4'))

    vd = np.empty(n_points, dtype=dtype_list)
    vd['x']        = merged_data['positions'][:,0]
    vd['y']        = merged_data['positions'][:,1]
    vd['z']        = merged_data['positions'][:,2]
    vd['opacity']  = merged_data['opacities'].flatten()
    vd['scale_0']  = np.log(merged_data['scales'][:,0])
    vd['scale_1']  = np.log(merged_data['scales'][:,1])
    vd['scale_2']  = np.log(merged_data['scales'][:,2])
    vd['rot_0']    = merged_data['rotations'][:,0]
    vd['rot_1']    = merged_data['rotations'][:,1]
    vd['rot_2']    = merged_data['rotations'][:,2]
    vd['rot_3']    = merged_data['rotations'][:,3]
    vd['f_dc_0']   = merged_data['dc'][:,0]
    vd['f_dc_1']   = merged_data['dc'][:,1]
    vd['f_dc_2']   = merged_data['dc'][:,2]
    vd['point_id'] = merged_data['point_ids'].astype(np.int64)
    if merged_data['sh_rest'] is not None:
        for i in range(n_sh):
            vd[f'f_rest_{i}'] = merged_data['sh_rest'][:,i]
    if merged_data.get('filter_3D') is not None:
        vd['filter_3D'] = merged_data['filter_3D'].flatten()

    PlyData([PlyElement.describe(vd, 'vertex')]).write(output_path)


# ============================================================
#  Merge 主流程(含族谱收集)
# ============================================================

def run_merge(data, compress_ratio=4, k_neighbors=5,

              spread_factor=0.0, aspect_ratio_threshold=15.0,

              id_counter=None):
    """

    对整份数据执行一次 merge,返回合并后数据和本级族谱。



    族谱格式(level_lineage):

        dict { child_point_id(int): [parent_point_id(int), ...] }

        与点的存储顺序完全无关,通过 point_id 唯一定位每个点。



    id_counter: [int],跨 cell 全局唯一ID生成器,由外部传入以保证跨级唯一性。

    """
    if id_counter is None:
        id_counter = [0]

    n_input = len(data['positions'])
    cells   = build_octree(data['positions'], max_points=5000)
    print(f"划分为 {len(cells)} 个 cells")

    all_merged = {
        'positions': [], 'opacities': [], 'scales': [], 'rotations': [],
        'dc': [], 'sh_rest': [] if data['sh_rest'] is not None else None,
        'filter_3D': [], 'point_ids': []
    }
    level_lineage = {}   # {child_id: [parent_id, ...]}

    for i, cell in enumerate(cells):
        if i % 100 == 0:
            print(f"  处理进度: {i}/{len(cells)}")

        merged, cell_lineage = cluster_and_merge_cell(
            data, cell['indices'], cell['bbox_min'], cell['bbox_max'],
            k_neighbors=k_neighbors, spread_factor=spread_factor,
            aspect_ratio_threshold=aspect_ratio_threshold,
            compress_ratio=compress_ratio,
            id_counter=id_counter,
        )
        if merged is None:
            continue

        for key in all_merged:
            if all_merged[key] is not None and len(merged[key]) > 0:
                all_merged[key].append(merged[key])

        level_lineage.update(cell_lineage)   # 合并各cell的族谱dict

    final_data = {
        key: np.concatenate(all_merged[key], axis=0)
        for key in all_merged
        if all_merged[key] is not None and len(all_merged[key]) > 0
    }
    n_merged = len(final_data['positions'])
    print(f"合并后点数: {n_merged}  压缩率: {n_merged/n_input*100:.2f}%")

    return final_data, level_lineage


# ============================================================
#  Fine-tuning 阶段
# ============================================================

def finetune_merged_gaussians(

    merged_ply_path,

    original_source_path,

    output_ply_path,

    image_resolution=1,

    sh_degree=3,

    num_epochs=500,

    lr_opacity=0.05,

    lr_scaling=0.005,

    lr_rotation=0.001,

    lr_features_dc=0.0025,

    lr_features_rest=0.000125,

    white_background=False,

    kernel_size=0.1,

    gpu_id=0,

    log_interval=50,

):
    """

    冻结高斯点位置,用下采样 GT 图像对其余参数做 fine-tuning。



    original_source_path : 原始分辨率 COLMAP 目录,程序内部自动 in-memory 下采样。

    image_resolution     : GT 图像边长缩小倍率(1=原图, 2=1/2边长, 4=1/4边长, 8=1/8边长)。

    """
    import torch
    import torch.nn.functional as F
    from gaussian_renderer import render, GaussianModel
    from scene.dataset_readers import sceneLoadTypeCallbacks
    from utils.camera_utils import loadCam
    from utils.loss_utils import l1_loss, ssim
    import random

    device     = f'cuda:{gpu_id}'
    torch.cuda.set_device(device)
    bg_color   = [1,1,1] if white_background else [0,0,0]
    background = torch.tensor(bg_color, dtype=torch.float32, device=device)

    # 1. 加载高斯模型
    print("\n[Fine-tune] 加载 merge 后的高斯模型...")
    gaussians = GaussianModel(sh_degree)
    gaussians.load_ply(merged_ply_path)
    print(f"[Fine-tune] 高斯点数: {gaussians.get_xyz.shape[0]}")

    # 2. 冻结位置
    gaussians._xyz.requires_grad_(False)
    optimizer = torch.optim.Adam([
        {'params': [gaussians._features_dc],   'lr': lr_features_dc,   'name': 'f_dc'},
        {'params': [gaussians._features_rest],  'lr': lr_features_rest, 'name': 'f_rest'},
        {'params': [gaussians._opacity],        'lr': lr_opacity,       'name': 'opacity'},
        {'params': [gaussians._scaling],        'lr': lr_scaling,       'name': 'scaling'},
        {'params': [gaussians._rotation],       'lr': lr_rotation,      'name': 'rotation'},
    ], eps=1e-15)

    # 3. 读取相机(原始分辨率)
    print(f"[Fine-tune] 读取相机,GT 将 in-memory 下采样 1/{image_resolution} 边长...")
    if os.path.exists(os.path.join(original_source_path, "sparse")):
        scene_info = sceneLoadTypeCallbacks["Colmap"](
            original_source_path, "images", eval=False, resolution=1)
    elif os.path.exists(os.path.join(original_source_path, "transforms_train.json")):
        scene_info = sceneLoadTypeCallbacks["Blender"](
            original_source_path, white_background, eval=False, resolution=1)
    else:
        raise ValueError(f"[Fine-tune] 无法识别数据集格式: {original_source_path}")

    class _LoadArgs:
        resolution  = 1
        data_device = device

    cameras = []
    for i, ci in enumerate(scene_info.train_cameras):
        try:
            cameras.append(loadCam(_LoadArgs(), i, ci, 1.0, load_image=True))
        except Exception as e:
            print(f"[Fine-tune] 跳过相机 {i}: {e}")

    if not cameras:
        raise RuntimeError("[Fine-tune] 没有可用的训练相机。")

    # 4. in-memory 下采样:GT 图像 + 渲染分辨率同步缩小
    if image_resolution > 1:
        print(f"[Fine-tune] 对 {len(cameras)} 个相机做 1/{image_resolution} 边长下采样...")
        for cam in cameras:
            gt_orig  = cam.original_image.to(device)
            H, W     = gt_orig.shape[1], gt_orig.shape[2]
            new_H, new_W = H // image_resolution, W // image_resolution
            cam.original_image = F.interpolate(
                gt_orig.unsqueeze(0), size=(new_H, new_W),
                mode='bilinear', align_corners=False
            ).squeeze(0).cpu()
            # FoVx/FoVy 不变,渲染器根据新 image_width/height 自动反算 focal length
            cam.image_width  = new_W
            cam.image_height = new_H
        print(f"[Fine-tune] 下采样后尺寸: {cameras[0].image_height} x {cameras[0].image_width}")

    # 5. 训练循环
    class _Pipeline:
        convert_SHs_python = False
        compute_cov3D_python = False
        debug = False

    pipeline     = _Pipeline()
    lambda_dssim = 0.2

    print(f"\n[Fine-tune] 开始优化,共 {num_epochs} epochs,{len(cameras)} 张图像...")
    for epoch in range(1, num_epochs + 1):
        random.shuffle(cameras)
        epoch_loss = 0.0
        for cam in cameras:
            optimizer.zero_grad()
            rendered = render(cam, gaussians, pipeline, background, kernel_size=kernel_size)["render"]
            gt       = cam.original_image.to(device)
            if rendered.shape != gt.shape:
                gt = F.interpolate(gt.unsqueeze(0), size=rendered.shape[1:],
                                   mode='bilinear', align_corners=False).squeeze(0)
            loss = (1.0 - lambda_dssim) * l1_loss(rendered, gt) \
                 + lambda_dssim * (1.0 - ssim(rendered, gt))
            loss.backward()
            optimizer.step()
            epoch_loss += loss.item()
        if epoch % log_interval == 0 or epoch == 1:
            print(f"[Fine-tune] Epoch {epoch:4d}/{num_epochs}  avg_loss={epoch_loss/len(cameras):.6f}")

    # 6. 保存
    print(f"\n[Fine-tune] 保存至 {output_ply_path} ...")
    os.makedirs(os.path.dirname(os.path.abspath(output_ply_path)), exist_ok=True)
    gaussians.save_ply(output_ply_path)
    print("[Fine-tune] 保存完成。")


# ============================================================
#  完整流程入口
# ============================================================

def run_all(

    input_ply,

    original_source_path,

    output_base,

    # merge 参数

    k_neighbors=5,

    spread_factor=0.0,

    aspect_ratio_threshold=15.0,

    # fine-tune 参数

    sh_degree=3,

    num_epochs=500,

    lr_opacity=0.05,

    lr_scaling=0.005,

    lr_rotation=0.001,

    lr_features_dc=0.0025,

    lr_features_rest=0.000125,

    white_background=False,

    kernel_size=0.1,

    gpu_id=0,

    log_interval=50,

):
    """

    完整流程:级联 merge(三级)+ 每级 fine-tune + 族谱保存。



    输出目录结构:

        output_base/

        ├── L1/

        │   ├── merged.ply       # 1/4 点数,merge 后未微调

        │   └── finetuned.ply    # 1/4 点数,微调后

        ├── L2/

        │   ├── merged.ply       # 1/16 点数

        │   └── finetuned.ply

        ├── L3/

        │   ├── merged.ply       # 1/64 点数

        │   └── finetuned.ply

        └── lineage.json         # 完整族谱



    族谱结构(lineage.json):

        {

          "L1": [[idx, ...], [idx, ...], ...],

            // L1[i] = 原始 PLY 中哪些点合并成了 L1 第 i 个点



          "L2": [[idx, ...], ...],

            // L2[i] = L1 finetuned PLY 中哪些点合并成了 L2 第 i 个点



          "L3": [[idx, ...], ...]

            // L3[i] = L2 finetuned PLY 中哪些点合并成了 L3 第 i 个点

        }



    层级恢复示例(从 L3 追溯到原始点):

        L3[i] 由 L2 中的 lineage["L3"][i] 合并而来

        其中 L2[j] 又由 L1 中的 lineage["L2"][j] 合并而来

        其中 L1[k] 又由原始点中的 lineage["L1"][k] 合并而来

    """

    # 三级配置:(级别名, image_resolution)
    # compress_ratio 固定为 4,每级压缩 1/4 点数
    levels = [
        ("L1", 2),   # 原始   → 1/4  点,图像边长 1/2
        ("L2", 4),   # L1结果 → 1/16 点,图像边长 1/4
        ("L3", 8),   # L2结果 → 1/64 点,图像边长 1/8
    ]

    finetune_kwargs = dict(
        original_source_path=original_source_path,
        sh_degree=sh_degree,
        num_epochs=num_epochs,
        lr_opacity=lr_opacity,
        lr_scaling=lr_scaling,
        lr_rotation=lr_rotation,
        lr_features_dc=lr_features_dc,
        lr_features_rest=lr_features_rest,
        white_background=white_background,
        kernel_size=kernel_size,
        gpu_id=gpu_id,
        log_interval=log_interval,
    )

    merge_kwargs = dict(
        compress_ratio=4,
        k_neighbors=k_neighbors,
        spread_factor=spread_factor,
        aspect_ratio_threshold=aspect_ratio_threshold,
    )

    # id_counter 跨三级共享,保证所有点的 point_id 全局唯一:
    #   原始点   : point_id = 0 ~ N_original-1  (read_ply 自动生成)
    #   L1合并点 : point_id 从 N_original 开始递增
    #   L2、L3  : 继续递增,绝不与任何已有 point_id 冲突
    current_data     = read_ply(input_ply)
    n_original       = len(current_data['positions'])
    id_counter       = [n_original]  # 合并点编号从原始点数量之后开始
    full_lineage     = {}            # {level: {str(child_id): [parent_id, ...]}}
    current_ply_path = input_ply

    for level, image_resolution in levels:
        print("\n" + "=" * 70)
        print(f"级别: {level}  |  本级压缩 1/4  |  图像边长缩小 1/{image_resolution}")
        print(f"输入 PLY: {current_ply_path}")
        print("=" * 70)

        level_dir     = os.path.join(output_base, level)
        merged_ply    = os.path.join(level_dir, "merged.ply")
        finetuned_ply = os.path.join(level_dir, "finetuned.ply")
        os.makedirs(level_dir, exist_ok=True)

        # --- Merge ---
        print(f"\n[{level}] Step 1: Merge")
        final_data, level_lineage = run_merge(
            current_data, id_counter=id_counter, **merge_kwargs)

        result = validate_data(final_data)
        if result['has_nan'] or result['has_inf']:
            print(f"⚠️  NaN={result['has_nan']}  Inf={result['has_inf']}")

        save_ply(final_data, current_data['plydata'], merged_ply)
        print(f"[{level}] Merge PLY 已保存: {merged_ply}")

        # 族谱 key 转 str(JSON 要求 key 必须是字符串)
        # 格式:{"child_point_id": [parent_point_id, ...], ...}
        full_lineage[level] = {str(k): v for k, v in level_lineage.items()}
        lineage_path = os.path.join(output_base, "lineage.json")
        with open(lineage_path, 'w') as f:
            json.dump(full_lineage, f)
        print(f"[{level}] 族谱已保存(当前已完成: {list(full_lineage.keys())})")

        # --- Fine-tune ---
        print(f"\n[{level}] Step 2: Fine-tune (image_resolution=1/{image_resolution})")
        finetune_merged_gaussians(
            merged_ply_path=merged_ply,
            output_ply_path=finetuned_ply,
            image_resolution=image_resolution,
            **finetune_kwargs,
        )

        # 下一级从 finetuned.ply 出发(fine-tune 不改变点数和 point_id,只改属性)
        current_ply_path = finetuned_ply
        current_data     = read_ply(finetuned_ply)

    # 族谱已在每级完成后实时写盘,此处仅做最终确认
    lineage_path = os.path.join(output_base, "lineage.json")
    print(f"\n✅  族谱完整保存至: {lineage_path}")

    print("\n🎉  所有级别完成!")
    print(f"输出目录: {output_base}")
    print("  L1/merged.ply, L1/finetuned.ply  — 1/4 点数")
    print("  L2/merged.ply, L2/finetuned.ply  — 1/16 点数")
    print("  L3/merged.ply, L3/finetuned.ply  — 1/64 点数")
    print("  lineage.json                      — 完整族谱")


# ============================================================
#  族谱工具函数(供后续训练代码使用)
# ============================================================

def load_lineage(lineage_path):
    """加载族谱文件"""
    with open(lineage_path, 'r') as f:
        lineage = json.load(f)
    return lineage


def trace_to_original(child_point_id, level, lineage):
    """

    从某一级的点(通过 point_id 指定)追溯到原始点的 point_id 集合。



    参数:

        child_point_id : 要追溯的点的 point_id(int 或 str 均可)

        level          : 该点所在级别,"L1" / "L2" / "L3"

        lineage        : load_lineage() 返回的族谱 dict



    返回:

        List[int],原始 PLY 中的 point_id 列表(即 0 ~ N_original-1 范围内的值)



    示例:

        lineage = load_lineage("low_results/lineage.json")

        # 查询 L3 中 point_id=500100 的点对应的所有原始点

        orig_ids = trace_to_original(500100, "L3", lineage)

    """
    levels    = ["L1", "L2", "L3"]
    level_idx = levels.index(level)

    # 当前层的父节点 point_id 列表
    current_ids = lineage[level][str(child_point_id)]

    # 逐级向上追溯,直到 L1 的父节点(即原始点 point_id)
    for parent_level in reversed(levels[:level_idx]):
        next_ids = []
        for pid in current_ids:
            # 原始点的 point_id 不在族谱里(它们是叶子节点),直接保留
            key = str(pid)
            if key in lineage[parent_level]:
                next_ids.extend(lineage[parent_level][key])
            else:
                next_ids.append(pid)
        current_ids = next_ids

    return [int(x) for x in current_ids]


# ============================================================
#  入口
# ============================================================



if __name__ == "__main__":

    run_all(
        input_ply           = "merge/original_3dgs.ply",
        original_source_path = "data",   # 唯一需要提供的 COLMAP 目录
        output_base         = "outputs",

        # merge 参数
        k_neighbors=5,
        spread_factor=0.0,
        aspect_ratio_threshold=15.0,

        # fine-tune 参数
        sh_degree=3,
        num_epochs=250,
        lr_opacity=0.05,
        lr_scaling=0.005,
        lr_rotation=0.001,
        lr_features_dc=0.0025,
        lr_features_rest=0.000125,
        white_background=False,
        kernel_size=0.1,
        gpu_id=2,
        log_interval=50,
    )