| |
| |
| """ |
| build_v11_longitudinal.py (seed=20260618, 可复现) |
| |
| 把 pseudo_dataset_v10(每人单时间点横截面)扩成 3 期纵向版 |
| pseudo_dataset_v11_longitudinal: |
| - 00_00_visit (基线, 100%) |
| - 01_00_visit (≈+2y, ~60%) |
| - 02_00_visit (≈+4y, ~35%) —— 单调随访保留(到达 k 期则拥有 0..k 期) |
| |
| 设计原则 |
| -------- |
| 1. 仅扩"会随时间变化的队列横截面模块"(EXPAND_TABLES);静态生物学/注解表 |
| (human_genetics / family_history / population 人口学 / curated_phenotypes / |
| sociodemographics / *_tag / 组学原始/bulk 等)一律不动(已由 APFS 克隆保留)。 |
| 2. **stage0 行 = v10 基线值逐字保留**(唯一规范化:research_stage 统一成 '00_00_visit', |
| 修掉 blood_tests 的 'undefined' 缺陷);随访行从基线做"个体内自相关漂移"。 |
| 3. schema / dtype / 列序完全不变 —— 通过"复制基线帧→只改时间锚点列+连续测量列"保证。 |
| 4. 同一 participant 的随访间隔(offset)跨所有模块共享 → 随访日期跨表协调一致。 |
| 5. 连续测量列:nunique>15 视为连续 → AR(1) 漂移,按基线 [min,max] 裁剪,保留 dtype; |
| 低基数数值列(≤15,疑似编码/类别)与类别/对象/容器列 → 跨期保持不变。 |
| 6. 任意 datetime 列(collection_date/collection_timestamp/cgm_connection_* 等) |
| 按该人随访 offset 整体推进。 |
| 7. 重建 events.parquet:覆盖全部 3000 人 ×各自随访期,作为纵向锚点表。 |
| """ |
| import os, sys, shutil |
| import numpy as np |
| import pandas as pd |
| import pyarrow as pa |
| import pyarrow.parquet as pq |
|
|
|
|
| def write_like(df, src_path, dst_path): |
| """写出 df,但把 v10 中为整数(可空 int64)、而经 pandas 变成 float 的列强制 cast 回 v10 的整数 |
| Arrow 物理类型,保证磁盘 schema 与 v10 严格一致(其余列保持默认推断)。""" |
| target = pq.read_schema(src_path) |
| tname = set(target.names) |
| tbl = pa.Table.from_pandas(df, preserve_index=False) |
| arrays, names = [], [] |
| for name in tbl.column_names: |
| col = tbl.column(name) |
| if name in tname: |
| tgt = target.field(name).type |
| if pa.types.is_integer(tgt) and pa.types.is_floating(col.type): |
| col = col.cast(tgt, safe=False) |
| arrays.append(col); names.append(name) |
| pq.write_table(pa.table(arrays, names=names), dst_path) |
|
|
| SEED = 20260618 |
| SRC = "pseudo_dataset_v10" |
| DST = "pseudo_dataset_v11_longitudinal" |
|
|
| STAGE_LABELS = ["00_00_visit", "01_00_visit", "02_00_visit"] |
| |
| MAX_STAGE_P = {0: 0.40, 1: 0.25, 2: 0.35} |
| |
| INTERVAL_MEAN_DAYS = 730 |
| INTERVAL_SD_DAYS = 60 |
| DRIFT_FRAC = 0.15 |
| CONT_NUNIQUE_MIN = 15 |
|
|
| |
| STATIC_COLS = { |
| "participant_id", "study_id", "cohort", "timezone", "hmo", |
| "sex", "gender", "genetic_sex", "year_of_birth", "month_of_birth", |
| "array_index", "sample_name", "sample_id", "registration_code", |
| "study_family_member_participant_id", |
| } |
|
|
| |
| EXPAND_TABLES = [ |
| "anthropometrics/anthropometrics.parquet", |
| "blood_pressure/blood_pressure.parquet", |
| "blood_tests/blood_tests.parquet", |
| "body_composition/body_composition.parquet", |
| "bone_density/bone_density.parquet", |
| "carotid_ultrasound/carotid_ultrasound.parquet", |
| "cgm/cgm.parquet", |
| "cgm/iglu.parquet", |
| "cgm/iglu_daily.parquet", |
| "diet_logging/diet_logging.parquet", |
| "ecg/ecg.parquet", |
| "ecg/ecg_qc.parquet", |
| "fundus/fundus.parquet", |
| "fundus/microvasculature.parquet", |
| "gut_microbiome/gut_microbiome.parquet", |
| "hand_grip/hand_grip.parquet", |
| "health_and_medical_history/initial_medical.parquet", |
| "health_and_medical_history/ukbb.parquet", |
| "lifestyle_and_environment/lifestyle_and_environment.parquet", |
| "liver_ultrasound/liver_ultrasound.parquet", |
| "liver_ultrasound/liver_ultrasound_aggregated.parquet", |
| "medical_conditions/medical_conditions.parquet", |
| "medical_procedures/follow_up_medical.parquet", |
| "medical_procedures/initial_medical.parquet", |
| "medical_symptoms/digestive_health.parquet", |
| "medical_symptoms/follow_up_ukbb.parquet", |
| "medical_symptoms/initial_medical.parquet", |
| "nightingale_metabolomics/nightingale_metabolomics.parquet", |
| "oral_microbiome/oral_microbiome.parquet", |
| "oral_microbiome/oral_microbiome_2025_04_UUID.parquet", |
| "rna_seq/rna_seq.parquet", |
| "vascular_health/vascular_health.parquet", |
| ] |
|
|
|
|
| def build_roster(rng): |
| """每个 participant 一行: max_stage + 期1/期2 的随访 offset(天)。跨表共享。""" |
| pop = pd.read_parquet(os.path.join(SRC, "population/population.parquet"), |
| columns=["participant_id"]) |
| pids = np.sort(pop["participant_id"].unique()) |
| n = len(pids) |
| stages = np.array(list(MAX_STAGE_P.keys())) |
| probs = np.array([MAX_STAGE_P[s] for s in stages], float) |
| probs /= probs.sum() |
| max_stage = rng.choice(stages, size=n, p=probs) |
| iv1 = np.round(rng.normal(INTERVAL_MEAN_DAYS, INTERVAL_SD_DAYS, n)).astype(int) |
| iv2 = iv1 + np.round(rng.normal(INTERVAL_MEAN_DAYS, INTERVAL_SD_DAYS, n)).astype(int) |
| iv1 = np.clip(iv1, 365, None) |
| iv2 = np.clip(iv2, iv1 + 200, None) |
| offset_days = {0: np.zeros(n, int), 1: iv1, 2: iv2} |
| roster = pd.DataFrame({"participant_id": pids, "max_stage": max_stage, |
| "off1": iv1, "off2": iv2}) |
| return roster.set_index("participant_id"), pids, offset_days |
|
|
|
|
| def classify_columns(df): |
| """返回 (datetime_cols, continuous_cols)。其余列跨期保持不变。""" |
| dt_cols, cont_cols = [], [] |
| for c in df.columns: |
| if c in STATIC_COLS or c == "research_stage": |
| continue |
| if str(c).endswith("_tag") or str(c).endswith("_parquet"): |
| continue |
| dtype = df[c].dtype |
| if pd.api.types.is_datetime64_any_dtype(dtype): |
| dt_cols.append(c) |
| elif pd.api.types.is_numeric_dtype(dtype) and not pd.api.types.is_bool_dtype(dtype): |
| if df[c].nunique(dropna=True) > CONT_NUNIQUE_MIN: |
| cont_cols.append(c) |
| return dt_cols, cont_cols |
|
|
|
|
| def expand_table(rel, roster, rng): |
| src = os.path.join(SRC, rel) |
| dst = os.path.join(DST, rel) |
| base = pd.read_parquet(src) |
| if "participant_id" not in base.columns or "research_stage" not in base.columns: |
| return rel, "SKIP(no pid/research_stage)", len(base), len(base) |
| if base["participant_id"].duplicated().any(): |
| return rel, "SKIP(already multi-row)", len(base), len(base) |
|
|
| n0 = len(base) |
| base = base.sort_values("participant_id").reset_index(drop=True) |
| pid = base["participant_id"].to_numpy() |
| ms = roster.reindex(pid)["max_stage"].to_numpy() |
| off1 = roster.reindex(pid)["off1"].to_numpy() |
| off2 = roster.reindex(pid)["off2"].to_numpy() |
| off_by_stage = {0: np.zeros(len(pid), int), 1: off1, 2: off2} |
|
|
| dt_cols, cont_cols = classify_columns(base) |
| |
| cont_stats = {} |
| for c in cont_cols: |
| v = pd.to_numeric(base[c], errors="coerce") |
| sd = float(np.nanstd(v.to_numpy())) |
| cont_stats[c] = {"sd": sd if np.isfinite(sd) and sd > 0 else 0.0, |
| "min": float(np.nanmin(v.to_numpy())) if v.notna().any() else np.nan, |
| "max": float(np.nanmax(v.to_numpy())) if v.notna().any() else np.nan, |
| "is_int": pd.api.types.is_integer_dtype(base[c].dtype)} |
|
|
| |
| cur = {c: pd.to_numeric(base[c], errors="coerce").astype(float).to_numpy() for c in cont_cols} |
|
|
| frames = [] |
| for k, label in enumerate(STAGE_LABELS): |
| f = base.copy() |
| f["research_stage"] = label |
| |
| if k > 0: |
| delta = pd.to_timedelta(off_by_stage[k], unit="D") |
| for c in dt_cols: |
| f[c] = base[c] + delta |
| |
| for c in cont_cols: |
| st = cont_stats[c] |
| if st["sd"] > 0: |
| step = rng.normal(0.0, DRIFT_FRAC * st["sd"], size=len(pid)) |
| cur[c] = np.clip(cur[c] + step, st["min"], st["max"]) |
| vals = cur[c].copy() |
| if st["is_int"]: |
| out = np.where(np.isnan(vals), np.nan, np.round(vals)) |
| f[c] = pd.Series(out, index=f.index).astype(base[c].dtype, errors="ignore") |
| |
| try: |
| f[c] = pd.array(np.round(vals), dtype=base[c].dtype) |
| except Exception: |
| f[c] = vals |
| else: |
| f[c] = vals.astype(base[c].dtype, copy=False) |
| |
| f = f[ms >= k] |
| frames.append(f) |
|
|
| out = pd.concat(frames, ignore_index=True) |
| out = out.sort_values(["participant_id", "research_stage"]).reset_index(drop=True) |
| |
| for c in base.columns: |
| if out[c].dtype != base[c].dtype: |
| try: |
| out[c] = out[c].astype(base[c].dtype) |
| except Exception: |
| pass |
| write_like(out, src, dst) |
| return rel, "OK", n0, len(out) |
|
|
|
|
| def rebuild_events(roster, rng): |
| pop = pd.read_parquet(os.path.join(SRC, "population/population.parquet")) |
| |
| anth = pd.read_parquet(os.path.join(SRC, "anthropometrics/anthropometrics.parquet"), |
| columns=["participant_id", "collection_date"]) |
| base_date = anth.set_index("participant_id")["collection_date"] |
| ev_old = pd.read_parquet(os.path.join(SRC, "events/events.parquet")) |
| vc_pool = ev_old["visit_center"].dropna().to_numpy() |
| if len(vc_pool) == 0: |
| vc_pool = np.array(["unknown"]) |
|
|
| rows = [] |
| for _, r in pop.iterrows(): |
| pid = int(r["participant_id"]) |
| if pid not in roster.index: |
| continue |
| ms = int(roster.loc[pid, "max_stage"]) |
| offs = {0: 0, 1: int(roster.loc[pid, "off1"]), 2: int(roster.loc[pid, "off2"])} |
| bd = base_date.get(pid, pd.Timestamp("2021-06-01")) |
| if pd.isna(bd): |
| bd = pd.Timestamp("2021-06-01") |
| yob = int(r["year_of_birth"]) if pd.notna(r["year_of_birth"]) and int(r["year_of_birth"]) > 1900 else None |
| vcenter = str(rng.choice(vc_pool)) |
| for k in range(ms + 1): |
| d = bd + pd.Timedelta(days=offs[k]) |
| ts = pd.Timestamp(d).tz_localize("UTC") if pd.Timestamp(d).tz is None else pd.Timestamp(d) |
| if yob is not None: |
| age = float(np.clip(d.year - yob + (d.month - 1) / 12.0, 18, 90)) |
| age = round(age, 1) |
| else: |
| age = float("nan") |
| rows.append({ |
| "month_of_birth": r["month_of_birth"], |
| "year_of_birth": r["year_of_birth"], |
| "sex": r["sex"], |
| "research_stage_type": STAGE_LABELS[k], |
| "visit_center": vcenter, |
| "research_stage_timestamp": ts, |
| "research_stage_date": pd.Timestamp(d), |
| "age_at_research_stage": age, |
| "study_id": f"P{pid}_study_id_01", |
| "timezone": "Asia/Jerusalem", |
| "participant_id": pid, |
| "cohort": "10k", |
| "research_stage": STAGE_LABELS[k], |
| "array_index": 0, |
| }) |
| ev = pd.DataFrame(rows, columns=ev_old.columns.tolist()) |
| |
| ev["research_stage_date"] = pd.to_datetime(ev["research_stage_date"]) |
| ev["research_stage_timestamp"] = pd.to_datetime(ev["research_stage_timestamp"], utc=True) |
| ev["age_at_research_stage"] = ev["age_at_research_stage"].astype("float64") |
| for c in ["year_of_birth", "participant_id", "array_index"]: |
| try: |
| ev[c] = ev[c].astype(ev_old[c].dtype) |
| except Exception: |
| pass |
| write_like(ev, os.path.join(SRC, "events/events.parquet"), |
| os.path.join(DST, "events/events.parquet")) |
| return len(ev_old), len(ev), ev["participant_id"].nunique() |
|
|
|
|
| def main(): |
| if not os.path.isdir(DST): |
| print(f"[FATAL] 目标 {DST} 不存在,请先 APFS 克隆 v10。", file=sys.stderr) |
| sys.exit(1) |
| rng = np.random.default_rng(SEED) |
| roster, pids, _ = build_roster(rng) |
| print(f"== roster: {len(pids)} 人; max_stage 分布 = " |
| f"{roster['max_stage'].value_counts().sort_index().to_dict()}") |
| s1 = int((roster['max_stage'] >= 1).sum()); s2 = int((roster['max_stage'] >= 2).sum()) |
| print(f"== 期成员: stage0={len(pids)}(100%) stage1={s1}({s1/len(pids):.0%}) stage2={s2}({s2/len(pids):.0%})") |
| print("== 扩展模块表:") |
| total_in = total_out = 0 |
| for rel in EXPAND_TABLES: |
| try: |
| r, status, n0, n1 = expand_table(rel, roster, rng) |
| except Exception as e: |
| print(f" [ERR] {rel}: {e}") |
| continue |
| total_in += n0; total_out += n1 |
| print(f" {status:<24} {rel:<55} {n0:>6} -> {n1:>6} 行") |
| print(f"== 扩展合计: {total_in} -> {total_out} 行") |
| o, n, npid = rebuild_events(roster, rng) |
| print(f"== events 重建: {o} -> {n} 行, 覆盖 {npid} 人 (期望 3000)") |
| print("== DONE") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|