#!/usr/bin/env Rscript
# -*- coding: utf-8 -*-
# 复现：Oropouche virus causes severe congenital disease in embryonic mice
#       (Nature Communications 2026, doi:10.1038/s41467-026-77294-6)
#       Fig. 7a —— OROV 胎内感染 E17.5 小鼠胚胎各器官细胞因子 log2 表达变化热图
#
# 数据：orov_cytokines_fig7a.csv（156 行真实胚胎级数据，直接取自论文补充材料
# Source Data MOESM4，sheet 'Figure 7'，非模拟；其中 CCL5 列有 1 个缺失值，
# 论文原数据即如此）。作图时按细胞因子×器官取均值（与原图每个格子颜色单调一致）。
#
# 输出：repro_r.png（300 dpi；ragg 输出）
try(invisible(Sys.setlocale("LC_ALL", "C.utf8")), silent = TRUE)  # 沙箱 locale=C 中文会变点点
suppressPackageStartupMessages({
  library(ggplot2)
  library(ragg)
  library(systemfonts)
})

# ---- 中文字体（随附 NotoSansSC）----
FONT_PATH <- "/home/hatch/workspace/arbovirus-site/day1-figure/NotoSansSC-Regular.ttf"
register_font("NotoSC", plain = FONT_PATH)

# ---- 读数据并聚合均值 ----
df <- read.csv("orov_cytokines_fig7a.csv", stringsAsFactors = FALSE)
cyto_order <- c("IL6", "IL1b", "CCL5", "TNFa", "IFNg")
cyto_lab   <- c(IL6 = "IL6", IL1b = "IL1β", CCL5 = "CCL5", TNFa = "TNFα", IFNg = "IFNγ")
org_order  <- c("Brain", "Lungs", "Heart", "Liver")

agg <- aggregate(log2_fold_change ~ cytokine + organ, data = df, FUN = mean)
cat("每格样本数：\n")
print(xtabs(~ cytokine + organ, data = df))
cat("\n每格 log2FC 均值（=热图颜色映射值）：\n")
print(agg[order(match(agg$cytokine, cyto_order), match(agg$organ, org_order)), ])

agg$cytokine <- factor(agg$cytokine, levels = rev(cyto_order))  # IL6 在上
agg$organ    <- factor(agg$organ, levels = org_order)

# ---- 配色：与原图一致的蓝单色标（浅→深）----
NAVY <- "#010184"  # 深端藏青（原图最深格 ~#010180 附近采样）
PALE <- "#FCFCFF"  # 浅端近白淡蓝

p <- ggplot(agg, aes(x = organ, y = cytokine, fill = log2_fold_change)) +
  geom_tile(color = "#000000", linewidth = 0.8, width = 1, height = 1) +
  scale_fill_gradient(low = PALE, high = NAVY, limits = c(0, 8),
                      breaks = c(2, 4, 6), name = "Log2 Fold change") +
  scale_x_discrete(expand = c(0, 0)) +
  scale_y_discrete(labels = cyto_lab, expand = c(0, 0)) +
  coord_fixed(ratio = 1.35) +
  labs(title = "a. OROV 胎内感染小鼠胚胎各器官细胞因子表达变化（log2 差异倍数）",
       x = NULL, y = NULL) +
  guides(fill = guide_colorbar(title.position = "top", title.hjust = 0.5,
                               barwidth = 0.8, barheight = 12)) +
  theme_minimal(base_family = "NotoSC", base_size = 12) +
  theme(
    plot.title = element_text(size = 13, hjust = 0.5, margin = margin(b = 12)),
    axis.line = element_line(color = "black", linewidth = 0.8),
    axis.text.x = element_text(size = 11, color = "black", family = "sans"),
    axis.text.y = element_text(size = 11, color = "black", family = "sans"),
    panel.grid = element_blank(),
    legend.title = element_text(size = 11, family = "sans"),
    legend.text = element_text(size = 10, family = "sans")
  )

agg_png("repro_r.png", width = 6.4, height = 4.8, units = "in", res = 300)
print(p)
invisible(dev.off())
cat("已输出 repro_r.png\n")
