# ============================================================
# 教程配套脚本 10：结果汇总与论文图表导出
# 作用：把关键结果汇总成论文用表格，并导出高分辨率图
# ============================================================

library(tidyverse)

# ---- 1. 汇总关键数字（供论文 Results 引用）----
deg <- read.csv("results/DEGs_tumor_vs_normal.csv")
deg_pyro <- read.csv("results/DEGs_pyroptosis.csv")

summary_stats <- data.frame(
  item = c("差异基因总数", "上调基因数", "下调基因数",
           "差异焦亡基因数", "hub 基因数"),
  value = c(nrow(deg),
            sum(deg$logFC > 0),
            sum(deg$logFC < 0),
            nrow(deg_pyro),
            length(read.csv("results/hub_genes_degree.csv")$gene))
)
print(summary_stats)
write.csv(summary_stats, "results/summary_statistics.csv", row.names = FALSE)

# ---- 2. 论文表格：多因素 Cox 结果（示例）----
# 正式分析中从 coxph 对象提取：
# tbl <- broom::tidy(cox_multi, conf.int = TRUE, exponentiate = TRUE)
# 教学演示给一个模板结构：
paper_table <- data.frame(
  Variable = c("GSDMD (high vs low)", "Age (per year)", "Stage (III/IV vs I/II)"),
  HR = c(2.15, 1.04, 2.44),
  lower_95 = c(1.44, 1.01, 1.63),
  upper_95 = c(3.21, 1.07, 3.66),
  P_value = c("<0.001", "0.008", "<0.001")
)
write.csv(paper_table, "results/paper_table_multivariate_cox.csv", row.names = FALSE)

# ---- 3. 图表导出规范提示 ----
# 论文图统一导出：ggsave(filename, width, height, dpi = 300)
# 位图：PNG/TIFF 300dpi；矢量：PDF/SVG（期刊偏好）
# 示例：
# ggsave("figures/Figure2_volcano.png", p_volcano, width = 7, height = 5.5, dpi = 300)

# ---- 4. 生成复现记录 ----
writeLines(c(
  paste0("分析时间: ", Sys.time()),
  paste0("R 版本: ", R.version.string),
  "关键包: limma, clusterProfiler, survival, glmnet, timeROC",
  "数据: TCGA-LIHC (UCSC Xena), GSE14520 (GEO)"
), "results/reproducibility_note.txt")

cat("结果汇总完成！检查 results/ 目录。\n")
cat("下一步：按教程第 13 章组织论文图表与手稿。\n")
