SlekLi commited on
Commit
14ee4bb
·
verified ·
1 Parent(s): 3b4bce3

Delete change_lineage.py

Browse files
Files changed (1) hide show
  1. change_lineage.py +0 -151
change_lineage.py DELETED
@@ -1,151 +0,0 @@
1
- import json
2
- import pickle
3
- import numpy as np
4
-
5
-
6
- def convert_lineage_json_to_genealogy_pkl(
7
- lineage_json_path: str,
8
- save_pkl_path: str,
9
- max_children: int = 4,
10
- ):
11
- """
12
- 将 merge 代码生成的 lineage.json 转换为
13
- build_sequences.py 需要的 genealogy.pkl。
14
-
15
- lineage.json 格式(子→父,merge方向):
16
- lineage["L1"][i] = [p0, p1, ...] # L1[i] 由 L0 中这些点 merge 来
17
- lineage["L2"][i] = [p0, p1, ...] # L2[i] 由 L1 中这些点 merge 来
18
- lineage["L3"][i] = [p0, p1, ...] # L3[i] 由 L2 中这些点 merge 来
19
-
20
- genealogy.pkl 格式(父→子,split方向):
21
- genealogy[1]['children_ids'] shape (N_L0, 4) # L0每个点在L1中的子节点
22
- genealogy[2]['children_ids'] shape (N_L1, 4) # L1每个点在L2中的子节点
23
- genealogy[3]['children_ids'] shape (N_L2, 4) # L2每个点在L3中的子节点
24
-
25
- 注意:merge 是多→一(多个父点合成一个子点),
26
- split 是一→多(一个父点分裂出多个子点),
27
- 所以这里的"子节点"含义是:
28
- L0[p] 参与 merge 成了 L1[i],则 L1[i] 就是 L0[p] 的一个"子节点"
29
- """
30
- print(f"[convert] 加载 {lineage_json_path}")
31
- with open(lineage_json_path, 'r') as f:
32
- lineage = json.load(f)
33
-
34
- genealogy = {}
35
-
36
- level_map = {
37
- "L1": 1, # genealogy key=1 对应 L0→L1
38
- "L2": 2, # genealogy key=2 对应 L1→L2
39
- "L3": 3, # genealogy key=3 对应 L2→L3
40
- }
41
-
42
- for level_name, gen_key in level_map.items():
43
- if level_name not in lineage:
44
- print(f"[convert] 警告:lineage 中无 {level_name},跳过")
45
- continue
46
-
47
- merge_list = lineage[level_name] # list of list,长度 = 该级点数
48
- n_children = len(merge_list) # 子尺度(更粗)点数
49
-
50
- # 父尺度点数:取所有父索引的最大值+1
51
- all_parent_indices = [idx for parents in merge_list for idx in parents]
52
- if not all_parent_indices:
53
- print(f"[convert] 警告:{level_name} 族谱为空,跳过")
54
- continue
55
- n_parents = max(all_parent_indices) + 1
56
-
57
- print(f"[convert] {level_name}:父尺度点数={n_parents},子尺度点数={n_children}")
58
-
59
- # 初始化 children_ids,-1 为空位
60
- children_ids = np.full((n_parents, max_children), fill_value=-1, dtype=np.int32)
61
- child_count = np.zeros(n_parents, dtype=np.int32)
62
- skipped = 0
63
-
64
- # merge_list[child_idx] = [parent_idx, ...]
65
- # 反转:对每个 parent_idx,把 child_idx 填入其 children_ids
66
- for child_idx, parent_indices in enumerate(merge_list):
67
- for p_idx in parent_indices:
68
- if child_count[p_idx] < max_children:
69
- children_ids[p_idx, child_count[p_idx]] = child_idx
70
- child_count[p_idx] += 1
71
- else:
72
- skipped += 1
73
-
74
- # 统计
75
- has_children = child_count > 0
76
- childless = (~has_children).sum()
77
- avg_child = child_count[has_children].mean() if has_children.any() else 0
78
-
79
- print(f" 有子节点的父点:{has_children.sum()}/{n_parents}")
80
- print(f" 无子节点的父点(孤立点,不会生成序列):{childless}")
81
- print(f" 平均子节点数:{avg_child:.2f}")
82
- if skipped:
83
- print(f" ⚠️ 因超过 {max_children} 个子节点被截断:{skipped} 条")
84
-
85
- genealogy[gen_key] = {
86
- 'children_ids': children_ids, # (N_parents, max_children)
87
- }
88
-
89
- # 保存
90
- with open(save_pkl_path, 'wb') as f:
91
- pickle.dump(genealogy, f, protocol=4)
92
-
93
- size_mb = os.path.getsize(save_pkl_path) / 1024 / 1024
94
- print(f"\n[convert] 族谱已保存 → {save_pkl_path} ({size_mb:.2f} MB)")
95
- return genealogy
96
-
97
-
98
- # ── 快速验证 ──────────────────────────────────────────────────
99
-
100
- def verify_conversion(lineage_json_path: str, genealogy_pkl_path: str, n_sample: int = 5):
101
- """
102
- 抽查几个点,确认转换逻辑正确:
103
- lineage["L1"][child_idx] 里的每个 parent_idx
104
- 都应该出现在 genealogy[1]['children_ids'][parent_idx] 中。
105
- """
106
- import os
107
- with open(lineage_json_path, 'r') as f:
108
- lineage = json.load(f)
109
- with open(genealogy_pkl_path, 'rb') as f:
110
- genealogy = pickle.load(f)
111
-
112
- print("\n[verify] 抽查转换正确性...")
113
- for level_name, gen_key in [("L1", 1), ("L2", 2), ("L3", 3)]:
114
- if level_name not in lineage or gen_key not in genealogy:
115
- continue
116
-
117
- merge_list = lineage[level_name]
118
- children_ids = genealogy[gen_key]['children_ids']
119
- errors = 0
120
-
121
- sample_indices = np.random.choice(len(merge_list), min(n_sample, len(merge_list)), replace=False)
122
- for child_idx in sample_indices:
123
- parent_indices = merge_list[child_idx]
124
- for p_idx in parent_indices:
125
- row = children_ids[p_idx]
126
- if child_idx not in row:
127
- print(f" ❌ {level_name} child={child_idx} 的父节点 p={p_idx} "
128
- f"的 children_ids={row},未包含 {child_idx}")
129
- errors += 1
130
-
131
- if errors == 0:
132
- print(f" ✅ {level_name}:抽查 {len(sample_indices)} 个子节点,全部正确")
133
- else:
134
- print(f" ❌ {level_name}:发现 {errors} 处错误!")
135
-
136
-
137
- # ── 入口 ──────────────────────────────────────────────────────
138
-
139
- if __name__ == '__main__':
140
- import os
141
-
142
- lineage_json = "outputs/lineage.json"
143
- genealogy_pkl = "outputs/genealogy.pkl"
144
-
145
- genealogy = convert_lineage_json_to_genealogy_pkl(
146
- lineage_json_path=lineage_json,
147
- save_pkl_path=genealogy_pkl,
148
- max_children=4,
149
- )
150
-
151
- verify_conversion(lineage_json, genealogy_pkl, n_sample=10)